Skip to main content

adk_vision/
verify.rs

1//! The verifier loop (spec 3.7 §7.14, "Verification"): after an action or a claim, a fresh
2//! observation is compared with the one before it, region by region.
3//!
4//! | Step | What happens |
5//! |------|--------------|
6//! | Observe | The [`Observer`] takes the observation before the action |
7//! | Act | The [`VerifiedAction`] acts and states the [`ExpectedChange`] |
8//! | Re-observe | A fresh observation is taken |
9//! | Check | [`check_change`] compares the two: every expected region appeared or disappeared, and nothing else did |
10//! | Re-ground | A failed check is handed back to the action once, which grounds its target again and acts again |
11//! | Hold | A second failed check holds for a person: [`VerificationHold::governed_call`] puts the before and after frames on one card |
12//!
13//! The loop is generic: a screen copilot's observer takes screenshots, an Inspector's reads
14//! a camera, and a claim with no action checks one observation against what it states.
15
16use std::sync::Arc;
17
18use adk_core::egress::ToolEgress;
19use adk_core::{Evidence, GovernedCall, ImageEvidence, ToolEffect};
20use async_trait::async_trait;
21use serde::{Deserialize, Serialize};
22use serde_json::json;
23
24use crate::cx::VisionCx;
25use crate::digest::Digest;
26use crate::error::Result;
27use crate::geometry::{BBox, Region, RegionSet};
28use crate::media::ImageRef;
29
30/// The governed call a failed verification is held as.
31///
32/// # Example
33///
34/// ```
35/// assert_eq!(adk_vision::VERIFICATION_TOOL, "vision_verification_failed");
36/// ```
37pub const VERIFICATION_TOOL: &str = "vision_verification_failed";
38
39/// One fresh look: the regions found and, when it was stored, the frame they were found in.
40#[derive(Clone, Debug, PartialEq)]
41#[non_exhaustive]
42pub struct Observation {
43    /// The regions, in the frame's source pixels.
44    pub regions: RegionSet,
45    /// The stored frame, for a card.
46    pub frame: Option<ImageRef>,
47}
48
49impl Observation {
50    /// An observation of `regions`.
51    pub fn new(regions: RegionSet) -> Self {
52        Self { regions, frame: None }
53    }
54
55    /// The stored frame the regions were found in.
56    #[must_use]
57    pub fn with_frame(mut self, frame: ImageRef) -> Self {
58        self.frame = Some(frame);
59        self
60    }
61}
62
63/// Takes fresh observations.
64#[async_trait]
65pub trait Observer: Send + Sync {
66    /// Observes now.
67    ///
68    /// # Errors
69    ///
70    /// The source's or the perception backend's error.
71    async fn observe(&self, cx: &VisionCx) -> Result<Observation>;
72}
73
74/// A region the action expects to appear or disappear: a label, and optionally where.
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77#[non_exhaustive]
78pub struct RegionExpectation {
79    /// The class.
80    pub label: String,
81    /// Where, in source pixels; anywhere when `None`.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub within: Option<BBox>,
84}
85
86impl RegionExpectation {
87    /// A region of `label` anywhere.
88    pub fn label(label: impl Into<String>) -> Self {
89        Self { label: label.into(), within: None }
90    }
91
92    /// Only inside `bbox`.
93    #[must_use]
94    pub fn within(mut self, bbox: BBox) -> Self {
95        self.within = Some(bbox);
96        self
97    }
98
99    fn matches(&self, region: &Region) -> bool {
100        region.label.as_deref() == Some(self.label.as_str())
101            && match (self.within, region.shape.bbox()) {
102                (None, _) => true,
103                (Some(area), Some(bbox)) => {
104                    let [cx, cy] = bbox.center();
105                    cx >= area.x0 && cx <= area.x1 && cy >= area.y0 && cy <= area.y1
106                }
107                (Some(_), None) => false,
108            }
109    }
110}
111
112/// What an action should change: regions that appear, regions that disappear; everything
113/// else stays.
114#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub struct ExpectedChange {
118    /// Regions that should appear.
119    #[serde(default, skip_serializing_if = "Vec::is_empty")]
120    pub appear: Vec<RegionExpectation>,
121    /// Regions that should disappear.
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub disappear: Vec<RegionExpectation>,
124    /// The overlap at which a region before and one after count as the same; 0.5 by default.
125    #[serde(default = "default_iou")]
126    pub same_iou: f32,
127}
128
129fn default_iou() -> f32 {
130    0.5
131}
132
133impl ExpectedChange {
134    /// Nothing should change.
135    pub fn none() -> Self {
136        Self { same_iou: default_iou(), ..Self::default() }
137    }
138
139    /// `expectation` should appear.
140    #[must_use]
141    pub fn appears(mut self, expectation: RegionExpectation) -> Self {
142        self.appear.push(expectation);
143        self
144    }
145
146    /// `expectation` should disappear.
147    #[must_use]
148    pub fn disappears(mut self, expectation: RegionExpectation) -> Self {
149        self.disappear.push(expectation);
150        self
151    }
152}
153
154/// What changed between two observations.
155#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
156#[serde(rename_all = "camelCase")]
157#[non_exhaustive]
158pub struct RegionDiff {
159    /// Regions after with no counterpart before.
160    pub appeared: Vec<Region>,
161    /// Regions before with no counterpart after.
162    pub disappeared: Vec<Region>,
163}
164
165/// Pairs regions of the same label across two observations by overlap.
166///
167/// # Example
168///
169/// ```
170/// use adk_vision::{
171///     BBox, BackendId, CoordFrame, Digest, RawRegion, RegionNormalizer, RegionSet,
172///     TransformChain, diff_regions,
173/// };
174///
175/// fn set(boxes: &[(f32, &str)]) -> RegionSet {
176///     let digest = Digest::of(b"frame");
177///     let normalizer = RegionNormalizer::new(
178///         digest,
179///         TransformChain::new(100, 100),
180///         CoordFrame::SentPixels,
181///         BackendId::new("test"),
182///     );
183///     let raw = boxes
184///         .iter()
185///         .map(|(x, label)| RawRegion::boxed(BBox::new(*x, 10.0, x + 10.0, 20.0), *label, 0.9))
186///         .collect();
187///     RegionSet::new(digest, 100, 100, normalizer.regions(raw).unwrap())
188/// }
189///
190/// let before = set(&[(10.0, "button")]);
191/// let after = set(&[(10.0, "button"), (50.0, "dialog")]);
192/// let diff = diff_regions(&before, &after, 0.5);
193/// assert_eq!(diff.appeared.len(), 1);
194/// assert!(diff.disappeared.is_empty());
195/// ```
196pub fn diff_regions(before: &RegionSet, after: &RegionSet, same_iou: f32) -> RegionDiff {
197    let same = |a: &Region, b: &Region| {
198        a.label == b.label
199            && match (a.shape.bbox(), b.shape.bbox()) {
200                (Some(x), Some(y)) => x.iou(&y) >= same_iou,
201                _ => false,
202            }
203    };
204    let mut matched = vec![false; after.regions.len()];
205    let mut disappeared = Vec::new();
206    for old in &before.regions {
207        match after.regions.iter().enumerate().position(|(i, new)| !matched[i] && same(old, new)) {
208            Some(index) => matched[index] = true,
209            None => disappeared.push(old.clone()),
210        }
211    }
212    let appeared = after
213        .regions
214        .iter()
215        .zip(matched)
216        .filter(|(_, matched)| !matched)
217        .map(|(region, _)| region.clone())
218        .collect();
219    RegionDiff { appeared, disappeared }
220}
221
222/// The outcome of one check.
223#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225#[non_exhaustive]
226pub struct VerificationReport {
227    /// Whether every expected change happened and nothing else changed.
228    pub passed: bool,
229    /// Expected changes that did not happen, described.
230    pub missing: Vec<String>,
231    /// Changes nobody expected.
232    pub unexpected: Vec<Region>,
233    /// What changed.
234    pub diff: RegionDiff,
235    /// The frame before.
236    pub before: Digest,
237    /// The frame after.
238    pub after: Digest,
239}
240
241/// Checks `expected` against what changed from `before` to `after`.
242///
243/// # Example
244///
245/// ```rust,ignore
246/// let report = check_change(&before, &after, &ExpectedChange::none().appears(RegionExpectation::label("saved")));
247/// assert!(report.passed);
248/// ```
249pub fn check_change(
250    before: &RegionSet,
251    after: &RegionSet,
252    expected: &ExpectedChange,
253) -> VerificationReport {
254    let diff = diff_regions(before, after, expected.same_iou);
255    let mut missing = Vec::new();
256    let mut appeared: Vec<Option<&Region>> = diff.appeared.iter().map(Some).collect();
257    let mut disappeared: Vec<Option<&Region>> = diff.disappeared.iter().map(Some).collect();
258    for (want, pool, verb) in [
259        (&expected.appear, &mut appeared, "appear"),
260        (&expected.disappear, &mut disappeared, "disappear"),
261    ] {
262        for expectation in want {
263            match pool.iter_mut().find(|r| r.is_some_and(|r| expectation.matches(r))) {
264                Some(slot) => *slot = None,
265                None => missing.push(format!(
266                    "`{}` did not {verb}{}",
267                    expectation.label,
268                    expectation
269                        .within
270                        .map(|b| format!(" in [{}, {}, {}, {}]", b.x0, b.y0, b.x1, b.y1))
271                        .unwrap_or_default()
272                )),
273            }
274        }
275    }
276    let unexpected: Vec<Region> =
277        appeared.into_iter().chain(disappeared).flatten().cloned().collect();
278    VerificationReport {
279        passed: missing.is_empty() && unexpected.is_empty(),
280        missing,
281        unexpected,
282        diff,
283        before: before.image,
284        after: after.image,
285    }
286}
287
288/// An action, or a claim, the loop verifies.
289#[async_trait]
290pub trait VerifiedAction: Send + Sync {
291    /// Acts and says what should change. `failed` is `None` on the first attempt and the
292    /// failed check on the re-grounded one, which grounds the target again before acting.
293    ///
294    /// # Errors
295    ///
296    /// The action's error, which ends the loop.
297    async fn act(
298        &self,
299        cx: &VisionCx,
300        failed: Option<&VerificationReport>,
301    ) -> Result<ExpectedChange>;
302}
303
304/// How a verified action ended.
305#[derive(Clone, Debug, PartialEq)]
306#[non_exhaustive]
307pub enum LoopOutcome {
308    /// The check passed, after `attempts` attempts.
309    Verified {
310        /// 1, or 2 when re-grounding fixed it.
311        attempts: u32,
312        /// The passing check.
313        report: VerificationReport,
314    },
315    /// Both checks failed; a person decides.
316    Held(VerificationHold),
317}
318
319/// A verification that failed twice, for a person.
320#[derive(Clone, Debug, PartialEq)]
321#[non_exhaustive]
322pub struct VerificationHold {
323    /// Both failed checks.
324    pub reports: Vec<VerificationReport>,
325    /// The frames before and after the last attempt, when they were stored.
326    pub frames: Vec<ImageRef>,
327}
328
329impl VerificationHold {
330    /// The governed call to hold for a person: the failed checks as arguments and the
331    /// stored frames, with what changed drawn on the last, as evidence.
332    pub fn governed_call(&self, function_call_id: &str) -> GovernedCall {
333        let evidence = self
334            .frames
335            .iter()
336            .enumerate()
337            .map(|(index, frame)| {
338                let mut image = ImageEvidence::new(
339                    frame.digest.to_string(),
340                    frame.artifact.clone(),
341                    frame.mime_type.clone(),
342                    frame.width,
343                    frame.height,
344                )
345                .with_caption(if index == 0 {
346                    "Before the action"
347                } else {
348                    "After the action"
349                });
350                if index + 1 == self.frames.len()
351                    && let Some(report) = self.reports.last()
352                {
353                    let regions = RegionSet::new(
354                        frame.digest,
355                        frame.width,
356                        frame.height,
357                        report.unexpected.clone(),
358                    );
359                    image = image.with_regions(serde_json::to_value(regions).unwrap_or_default());
360                }
361                Evidence::from(image)
362            })
363            .collect::<Vec<_>>();
364        let mut call = GovernedCall::new(
365            VERIFICATION_TOOL,
366            function_call_id,
367            json!({ "reports": self.reports }),
368        )
369        .with_effect(ToolEffect::Idempotent)
370        .with_egress(ToolEgress::None)
371        .with_evidence(evidence);
372        call.requires_confirmation = true;
373        call
374    }
375}
376
377/// Observe, act, re-observe, check; re-ground once; then hold (spec 3.7 §7.14).
378///
379/// # Example
380///
381/// ```rust,ignore
382/// let outcome = VerifierLoop::new(screen_observer).run(&cx, &click_save).await?;
383/// if let LoopOutcome::Held(hold) = outcome {
384///     adk_core::authorize_tool_call(&gate, hold.governed_call("verify-1")).await?;
385/// }
386/// ```
387pub struct VerifierLoop {
388    observer: Arc<dyn Observer>,
389    regrounds: u32,
390}
391
392impl VerifierLoop {
393    /// A loop observing through `observer` that re-grounds once.
394    pub fn new(observer: Arc<dyn Observer>) -> Self {
395        Self { observer, regrounds: 1 }
396    }
397
398    /// Runs `action` under the loop.
399    ///
400    /// # Errors
401    ///
402    /// The observer's and the action's errors.
403    pub async fn run(&self, cx: &VisionCx, action: &dyn VerifiedAction) -> Result<LoopOutcome> {
404        let mut before = self.observer.observe(cx).await?;
405        let mut reports: Vec<VerificationReport> = Vec::new();
406        let mut frames = Vec::new();
407        for attempt in 0..=self.regrounds {
408            let expected = action.act(cx, reports.last()).await?;
409            let after = self.observer.observe(cx).await?;
410            let report = check_change(&before.regions, &after.regions, &expected);
411            tracing::debug!(
412                vision.attempt = attempt + 1,
413                vision.passed = report.passed,
414                vision.unexpected = report.unexpected.len(),
415                "verification checked"
416            );
417            if report.passed {
418                return Ok(LoopOutcome::Verified { attempts: attempt + 1, report });
419            }
420            frames = before.frame.iter().chain(after.frame.iter()).cloned().collect();
421            reports.push(report);
422            before = after;
423        }
424        tracing::info!(vision.reports = reports.len(), "verification failed; held for a person");
425        Ok(LoopOutcome::Held(VerificationHold { reports, frames }))
426    }
427}