1use 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
30pub const VERIFICATION_TOOL: &str = "vision_verification_failed";
38
39#[derive(Clone, Debug, PartialEq)]
41#[non_exhaustive]
42pub struct Observation {
43 pub regions: RegionSet,
45 pub frame: Option<ImageRef>,
47}
48
49impl Observation {
50 pub fn new(regions: RegionSet) -> Self {
52 Self { regions, frame: None }
53 }
54
55 #[must_use]
57 pub fn with_frame(mut self, frame: ImageRef) -> Self {
58 self.frame = Some(frame);
59 self
60 }
61}
62
63#[async_trait]
65pub trait Observer: Send + Sync {
66 async fn observe(&self, cx: &VisionCx) -> Result<Observation>;
72}
73
74#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77#[non_exhaustive]
78pub struct RegionExpectation {
79 pub label: String,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub within: Option<BBox>,
84}
85
86impl RegionExpectation {
87 pub fn label(label: impl Into<String>) -> Self {
89 Self { label: label.into(), within: None }
90 }
91
92 #[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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub struct ExpectedChange {
118 #[serde(default, skip_serializing_if = "Vec::is_empty")]
120 pub appear: Vec<RegionExpectation>,
121 #[serde(default, skip_serializing_if = "Vec::is_empty")]
123 pub disappear: Vec<RegionExpectation>,
124 #[serde(default = "default_iou")]
126 pub same_iou: f32,
127}
128
129fn default_iou() -> f32 {
130 0.5
131}
132
133impl ExpectedChange {
134 pub fn none() -> Self {
136 Self { same_iou: default_iou(), ..Self::default() }
137 }
138
139 #[must_use]
141 pub fn appears(mut self, expectation: RegionExpectation) -> Self {
142 self.appear.push(expectation);
143 self
144 }
145
146 #[must_use]
148 pub fn disappears(mut self, expectation: RegionExpectation) -> Self {
149 self.disappear.push(expectation);
150 self
151 }
152}
153
154#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
156#[serde(rename_all = "camelCase")]
157#[non_exhaustive]
158pub struct RegionDiff {
159 pub appeared: Vec<Region>,
161 pub disappeared: Vec<Region>,
163}
164
165pub 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225#[non_exhaustive]
226pub struct VerificationReport {
227 pub passed: bool,
229 pub missing: Vec<String>,
231 pub unexpected: Vec<Region>,
233 pub diff: RegionDiff,
235 pub before: Digest,
237 pub after: Digest,
239}
240
241pub 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#[async_trait]
290pub trait VerifiedAction: Send + Sync {
291 async fn act(
298 &self,
299 cx: &VisionCx,
300 failed: Option<&VerificationReport>,
301 ) -> Result<ExpectedChange>;
302}
303
304#[derive(Clone, Debug, PartialEq)]
306#[non_exhaustive]
307pub enum LoopOutcome {
308 Verified {
310 attempts: u32,
312 report: VerificationReport,
314 },
315 Held(VerificationHold),
317}
318
319#[derive(Clone, Debug, PartialEq)]
321#[non_exhaustive]
322pub struct VerificationHold {
323 pub reports: Vec<VerificationReport>,
325 pub frames: Vec<ImageRef>,
327}
328
329impl VerificationHold {
330 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
377pub struct VerifierLoop {
388 observer: Arc<dyn Observer>,
389 regrounds: u32,
390}
391
392impl VerifierLoop {
393 pub fn new(observer: Arc<dyn Observer>) -> Self {
395 Self { observer, regrounds: 1 }
396 }
397
398 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}