Skip to main content

adk_computer_use/contracts/
target.rs

1//! Target evidence and value-free accessibility sensitivity contracts.
2//!
3//! These types bind a proposed action to a *fresh* desktop observation and
4//! carry only digests and structured signals — never raw field values — so the
5//! wire payload cannot leak sensitive content across the ADK/runtime boundary.
6
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::collections::HashSet;
10
11/// Evidence binding an action to a fresh desktop observation.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13#[serde(rename_all = "camelCase")]
14pub struct TargetEvidence {
15    /// Platform identifier for the observed target (e.g. `darwin`, `windows`).
16    pub platform: String,
17    /// Application/bundle identifier of the observed target.
18    pub app_id: String,
19    /// Process identifier of the observed target, when known.
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub pid: Option<u32>,
22    /// Platform-specific window identifier, when known.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub window_id: Option<Value>,
25    /// Digest of the window title (never the raw title).
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub window_title_digest: Option<String>,
28    /// Display identifier hosting the target, when known.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub display_id: Option<String>,
31    /// Accessibility role of the target element, when known.
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub role: Option<String>,
34    /// Digest of the element label (never the raw label).
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub label_digest: Option<String>,
37    /// Bounding box of the target element, when known.
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub bounds: Option<Bounds>,
40    /// Identifier of the observation frame this evidence came from.
41    pub observation_id: String,
42    /// Hash of the screenshot backing this observation, when captured.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub screenshot_hash: Option<String>,
45    /// Pixels per logical point of the screenshot `screenshot_hash` names: 2.0 for a
46    /// 3024×1964 screenshot of a 1512×982-point display.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub device_pixel_ratio: Option<f64>,
49    /// Revision of the UI tree backing this observation, when captured.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub ui_tree_revision: Option<String>,
52    /// Observation confidence in `0.0..=1.0`.
53    pub confidence: f64,
54    /// RFC 3339 timestamp of the observation.
55    pub captured_at: String,
56}
57
58impl TargetEvidence {
59    /// Checks that the evidence binds its bounds to its screenshot (spec 3.7 V-I14): a
60    /// target with both bounds and a screenshot hash states the screenshot's device pixel
61    /// ratio, the bounds carry the same ratio, and the box is finite and not inverted.
62    ///
63    /// # Errors
64    ///
65    /// Returns a message naming the violated rule.
66    ///
67    /// # Example
68    ///
69    /// ```
70    /// use adk_computer_use::{Bounds, TargetEvidence};
71    ///
72    /// let mut target = TargetEvidence {
73    ///     platform: "darwin".into(),
74    ///     app_id: "com.example.crm".into(),
75    ///     pid: None,
76    ///     window_id: None,
77    ///     window_title_digest: None,
78    ///     display_id: Some("built-in".into()),
79    ///     role: None,
80    ///     label_digest: None,
81    ///     bounds: Some(Bounds::points(960.0, 590.0, 90.0, 40.0, 2.0)),
82    ///     observation_id: "observation-1".into(),
83    ///     screenshot_hash: Some("sha256:ab12".into()),
84    ///     device_pixel_ratio: Some(2.0),
85    ///     ui_tree_revision: None,
86    ///     confidence: 0.9,
87    ///     captured_at: "2026-11-22T10:00:00Z".into(),
88    /// };
89    /// assert!(target.check_screen_binding().is_ok());
90    /// target.device_pixel_ratio = None;
91    /// assert!(target.check_screen_binding().is_err());
92    /// ```
93    pub fn check_screen_binding(&self) -> Result<(), String> {
94        let Some(bounds) = &self.bounds else { return Ok(()) };
95        bounds.validate()?;
96        if self.screenshot_hash.is_none() {
97            return Ok(());
98        }
99        let Some(ratio) = self.device_pixel_ratio else {
100            return Err(
101                "target bounds from a screenshot must state the screenshot's devicePixelRatio"
102                    .into(),
103            );
104        };
105        if !(ratio.is_finite() && ratio > 0.0) {
106            return Err(format!("devicePixelRatio must be a positive number, not {ratio}"));
107        }
108        if (ratio - bounds.device_pixel_ratio).abs() > f64::EPSILON {
109            return Err(format!(
110                "target bounds are at device pixel ratio {} but the screenshot is at {ratio}",
111                bounds.device_pixel_ratio
112            ));
113        }
114        Ok(())
115    }
116}
117
118/// The coordinate space a [`Bounds`] is in.
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "snake_case")]
121pub enum CoordinateSpace {
122    /// Logical display points, the space a desktop runtime acts in. Bounds without a
123    /// stated space are read as points.
124    #[default]
125    LogicalPoints,
126    /// Pixels of the screenshot the evidence's `screenshotHash` names.
127    ScreenshotPixels,
128}
129
130fn unit_ratio() -> f64 {
131    1.0
132}
133
134/// Axis-aligned bounding box, with the coordinate space it is in and the device pixel
135/// ratio that relates screenshot pixels to logical points.
136///
137/// # Example
138///
139/// ```
140/// use adk_computer_use::{Bounds, CoordinateSpace};
141///
142/// // A Save button at (1920, 1180)–(2100, 1260) in a 3024×1964 screenshot of a
143/// // 1512×982-point display.
144/// let pixels = Bounds::pixels(1920.0, 1180.0, 180.0, 80.0, 2.0);
145/// let points = pixels.to_points();
146/// assert_eq!(points.space, CoordinateSpace::LogicalPoints);
147/// assert_eq!((points.x, points.y, points.width, points.height), (960.0, 590.0, 90.0, 40.0));
148/// assert!(points.contains(points.center()));
149/// ```
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct Bounds {
153    /// Left edge.
154    pub x: f64,
155    /// Top edge.
156    pub y: f64,
157    /// Width.
158    pub width: f64,
159    /// Height.
160    pub height: f64,
161    /// The space `x`, `y`, `width` and `height` are in.
162    #[serde(default)]
163    pub space: CoordinateSpace,
164    /// Screenshot pixels per logical point; 1.0 when unstated.
165    #[serde(default = "unit_ratio")]
166    pub device_pixel_ratio: f64,
167}
168
169impl Bounds {
170    /// A box in logical points of a display at `device_pixel_ratio`.
171    pub fn points(x: f64, y: f64, width: f64, height: f64, device_pixel_ratio: f64) -> Self {
172        Self { x, y, width, height, space: CoordinateSpace::LogicalPoints, device_pixel_ratio }
173    }
174
175    /// A box in screenshot pixels of a display at `device_pixel_ratio`.
176    pub fn pixels(x: f64, y: f64, width: f64, height: f64, device_pixel_ratio: f64) -> Self {
177        Self { x, y, width, height, space: CoordinateSpace::ScreenshotPixels, device_pixel_ratio }
178    }
179
180    fn ratio(&self) -> f64 {
181        if self.device_pixel_ratio.is_finite() && self.device_pixel_ratio > 0.0 {
182            self.device_pixel_ratio
183        } else {
184            1.0
185        }
186    }
187
188    fn scaled(&self, factor: f64, space: CoordinateSpace) -> Self {
189        Self {
190            x: self.x * factor,
191            y: self.y * factor,
192            width: self.width * factor,
193            height: self.height * factor,
194            space,
195            device_pixel_ratio: self.device_pixel_ratio,
196        }
197    }
198
199    /// The box in logical points.
200    pub fn to_points(&self) -> Self {
201        match self.space {
202            CoordinateSpace::LogicalPoints => self.clone(),
203            CoordinateSpace::ScreenshotPixels => {
204                self.scaled(1.0 / self.ratio(), CoordinateSpace::LogicalPoints)
205            }
206        }
207    }
208
209    /// The box in screenshot pixels.
210    pub fn to_pixels(&self) -> Self {
211        match self.space {
212            CoordinateSpace::ScreenshotPixels => self.clone(),
213            CoordinateSpace::LogicalPoints => {
214                self.scaled(self.ratio(), CoordinateSpace::ScreenshotPixels)
215            }
216        }
217    }
218
219    /// The centre, in the box's own space.
220    pub fn center(&self) -> [f64; 2] {
221        [self.x + self.width / 2.0, self.y + self.height / 2.0]
222    }
223
224    /// Whether `point`, in the box's own space, lies inside it (right and bottom edges
225    /// exclusive).
226    pub fn contains(&self, point: [f64; 2]) -> bool {
227        point[0] >= self.x
228            && point[1] >= self.y
229            && point[0] < self.x + self.width
230            && point[1] < self.y + self.height
231    }
232
233    fn validate(&self) -> Result<(), String> {
234        let values = [self.x, self.y, self.width, self.height, self.device_pixel_ratio];
235        if values.iter().any(|value| !value.is_finite()) {
236            return Err("target bounds must be finite numbers".into());
237        }
238        if self.width < 0.0 || self.height < 0.0 {
239            return Err("target bounds must not have a negative width or height".into());
240        }
241        if self.device_pixel_ratio <= 0.0 {
242            return Err("target bounds must have a positive devicePixelRatio".into());
243        }
244        Ok(())
245    }
246}
247
248/// Conclusion of an accessibility-based target sensitivity check.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(rename_all = "snake_case")]
251pub enum TargetSensitivityAssessment {
252    /// The target holds sensitive content (e.g. a password field).
253    Sensitive,
254    /// The target is confirmed non-sensitive.
255    NonSensitive,
256    /// Sensitivity could not be determined.
257    Unknown,
258}
259
260/// Source of a [`TargetSensitivityEvidence`] assessment.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "snake_case")]
263pub enum TargetSensitivitySource {
264    /// Derived from platform accessibility APIs.
265    Accessibility,
266    /// Native sensitivity signals were unavailable.
267    Unavailable,
268}
269
270/// A single value-free signal contributing to a sensitivity assessment.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
272#[serde(rename_all = "snake_case")]
273pub enum TargetSensitivitySignal {
274    /// Element reports a secure accessibility role.
275    SecureRole,
276    /// Element reports a secure accessibility subrole.
277    SecureSubrole,
278    /// Element is marked as protected content.
279    ProtectedContent,
280    /// UI Automation reports the element as a password field.
281    UiaIsPassword,
282    /// Element label matched a sensitive pattern.
283    SensitiveLabel,
284    /// Multiple candidate elements matched ambiguously.
285    AmbiguousMatch,
286    /// The referenced element was not found.
287    ElementNotFound,
288    /// Inspection raised an error.
289    InspectionError,
290    /// The field was invalid for inspection.
291    InvalidField,
292    /// Native sensitivity signals were unavailable.
293    NativeSignalUnavailable,
294}
295
296/// Value-free native accessibility evidence used for action risk and revalidation.
297///
298/// Construct with [`TargetSensitivityEvidence::try_new`]; the constructor and the
299/// deserializer enforce the same invariants (bounded/unique signals, conclusive
300/// assessments require accessibility evidence for a checked field).
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(try_from = "RawTargetSensitivityEvidence", into = "RawTargetSensitivityEvidence")]
303pub struct TargetSensitivityEvidence {
304    assessment: TargetSensitivityAssessment,
305    source: TargetSensitivitySource,
306    signals: Vec<TargetSensitivitySignal>,
307    fields_checked: u32,
308    observed_at: String,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(rename_all = "camelCase", deny_unknown_fields)]
313struct RawTargetSensitivityEvidence {
314    assessment: TargetSensitivityAssessment,
315    source: TargetSensitivitySource,
316    signals: Vec<TargetSensitivitySignal>,
317    fields_checked: u32,
318    observed_at: String,
319}
320
321impl TargetSensitivityEvidence {
322    /// Build validated sensitivity evidence.
323    ///
324    /// # Errors
325    ///
326    /// Returns a message describing the violated invariant when signals exceed
327    /// 10, contain duplicates, `fields_checked` exceeds 100, a conclusive
328    /// assessment lacks accessibility evidence for a checked field, a
329    /// `Sensitive` assessment has no signals, or `observed_at` is blank.
330    ///
331    /// # Example
332    ///
333    /// ```
334    /// use adk_computer_use::{
335    ///     TargetSensitivityAssessment, TargetSensitivityEvidence, TargetSensitivitySignal,
336    ///     TargetSensitivitySource,
337    /// };
338    ///
339    /// let evidence = TargetSensitivityEvidence::try_new(
340    ///     TargetSensitivityAssessment::Sensitive,
341    ///     TargetSensitivitySource::Accessibility,
342    ///     vec![TargetSensitivitySignal::UiaIsPassword],
343    ///     1,
344    ///     "2026-07-13T12:00:00Z",
345    /// )
346    /// .unwrap();
347    /// assert_eq!(evidence.fields_checked(), 1);
348    /// ```
349    pub fn try_new(
350        assessment: TargetSensitivityAssessment,
351        source: TargetSensitivitySource,
352        signals: Vec<TargetSensitivitySignal>,
353        fields_checked: u32,
354        observed_at: impl Into<String>,
355    ) -> Result<Self, String> {
356        RawTargetSensitivityEvidence {
357            assessment,
358            source,
359            signals,
360            fields_checked,
361            observed_at: observed_at.into(),
362        }
363        .try_into()
364    }
365
366    /// The conclusion of the sensitivity check.
367    pub fn assessment(&self) -> TargetSensitivityAssessment {
368        self.assessment
369    }
370
371    /// The source of the assessment.
372    pub fn source(&self) -> TargetSensitivitySource {
373        self.source
374    }
375
376    /// The distinct signals that contributed to the assessment.
377    pub fn signals(&self) -> &[TargetSensitivitySignal] {
378        &self.signals
379    }
380
381    /// The number of fields inspected during the check.
382    pub fn fields_checked(&self) -> u32 {
383        self.fields_checked
384    }
385
386    /// RFC 3339 timestamp of the observation.
387    pub fn observed_at(&self) -> &str {
388        &self.observed_at
389    }
390}
391
392impl TryFrom<RawTargetSensitivityEvidence> for TargetSensitivityEvidence {
393    type Error = String;
394
395    fn try_from(raw: RawTargetSensitivityEvidence) -> Result<Self, Self::Error> {
396        if raw.signals.len() > 10 {
397            return Err("target sensitivity supports at most 10 signals".into());
398        }
399        if raw.signals.iter().copied().collect::<HashSet<_>>().len() != raw.signals.len() {
400            return Err("target sensitivity signals must be unique".into());
401        }
402        if raw.fields_checked > 100 {
403            return Err("target sensitivity supports at most 100 checked fields".into());
404        }
405        if matches!(
406            raw.assessment,
407            TargetSensitivityAssessment::Sensitive | TargetSensitivityAssessment::NonSensitive
408        ) && (raw.source != TargetSensitivitySource::Accessibility || raw.fields_checked == 0)
409        {
410            return Err(
411                "conclusive target sensitivity requires accessibility evidence for a checked field"
412                    .into(),
413            );
414        }
415        if raw.assessment == TargetSensitivityAssessment::Sensitive && raw.signals.is_empty() {
416            return Err("sensitive target evidence requires at least one signal".into());
417        }
418        if raw.observed_at.trim().is_empty() {
419            return Err("target sensitivity observedAt must not be empty".into());
420        }
421        Ok(Self {
422            assessment: raw.assessment,
423            source: raw.source,
424            signals: raw.signals,
425            fields_checked: raw.fields_checked,
426            observed_at: raw.observed_at,
427        })
428    }
429}
430
431impl From<TargetSensitivityEvidence> for RawTargetSensitivityEvidence {
432    fn from(value: TargetSensitivityEvidence) -> Self {
433        Self {
434            assessment: value.assessment,
435            source: value.source,
436            signals: value.signals,
437            fields_checked: value.fields_checked,
438            observed_at: value.observed_at,
439        }
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    fn evidence(bounds: Option<Bounds>, hash: Option<&str>, ratio: Option<f64>) -> TargetEvidence {
448        TargetEvidence {
449            platform: "darwin".into(),
450            app_id: "com.example.form".into(),
451            pid: None,
452            window_id: None,
453            window_title_digest: None,
454            display_id: None,
455            role: None,
456            label_digest: None,
457            bounds,
458            observation_id: "observation-1".into(),
459            screenshot_hash: hash.map(str::to_string),
460            device_pixel_ratio: ratio,
461            ui_tree_revision: None,
462            confidence: 1.0,
463            captured_at: "2026-11-22T10:00:00Z".into(),
464        }
465    }
466
467    #[test]
468    fn screen_binding_requires_a_matching_ratio() {
469        let points = Bounds::points(960.0, 590.0, 90.0, 40.0, 2.0);
470        assert!(evidence(None, None, None).check_screen_binding().is_ok());
471        assert!(evidence(Some(points.clone()), None, None).check_screen_binding().is_ok());
472        assert!(
473            evidence(Some(points.clone()), Some("sha256:1"), Some(2.0))
474                .check_screen_binding()
475                .is_ok()
476        );
477        let missing = evidence(Some(points.clone()), Some("sha256:1"), None);
478        assert!(missing.check_screen_binding().unwrap_err().contains("devicePixelRatio"));
479        let mismatched = evidence(Some(points), Some("sha256:1"), Some(1.0));
480        assert!(mismatched.check_screen_binding().unwrap_err().contains("device pixel ratio 2"));
481        let inverted =
482            evidence(Some(Bounds::points(0.0, 0.0, -1.0, 4.0, 1.0)), Some("sha256:1"), Some(1.0));
483        assert!(inverted.check_screen_binding().is_err());
484    }
485
486    #[test]
487    fn evidence_without_a_ratio_serializes_as_before() {
488        let value = serde_json::to_value(evidence(None, None, None)).unwrap();
489        assert!(value.get("devicePixelRatio").is_none());
490    }
491}