Skip to main content

adk_core/
evidence.rs

1//! Evidence an approver sees with a held call.
2//!
3//! A call that sends, keeps or acts on an image is held with the exact image as
4//! [`Evidence`]: its digest, where it is stored, and an optional overlay of regions. Evidence
5//! travels by reference and digest, never as pixels, so held calls, approval requests and
6//! audit records stay small, and a surface loads the image through the artifact service with
7//! the viewer's own authorisation.
8//!
9//! | Carried by | Set by |
10//! |------------|--------|
11//! | [`GovernedCall::evidence`](crate::GovernedCall::evidence) | [`Tool::approval_evidence`](crate::Tool::approval_evidence) through [`GovernedCall::for_tool`](crate::GovernedCall::for_tool), or [`GovernedCall::with_evidence`](crate::GovernedCall::with_evidence) |
12//! | [`ToolConfirmationRequest::evidence`](crate::ToolConfirmationRequest::evidence) | The governed path, from the call |
13//! | [`ApprovalRequest::evidence`](crate::ApprovalRequest::evidence) | The call's evidence, then any [`ApprovalRoute::evidence`](crate::ApprovalRoute::evidence) |
14//!
15//! The digests of a held call's own evidence are part of its
16//! [fingerprint](crate::ToolConfirmationRequest::fingerprint), so a decision binds to the
17//! exact images the approver saw: a call whose image changed before it ran is a different call
18//! and is held again. A call without evidence keeps the fingerprint it always had.
19//!
20//! # Example
21//!
22//! ```rust
23//! use adk_core::{ArtifactLocator, Evidence, ImageEvidence, ToolConfirmationRequest};
24//! use serde_json::json;
25//!
26//! let crop = ImageEvidence::new(
27//!     "sha256:9f2c0a7e5b1d4c8a6f3e2d1c0b9a8f7e6d5c4b3a2f1e0d9c8b7a6f5e4d3c2b1a",
28//!     ArtifactLocator::new("desk", "ana", "s1", "egress/invoice-7-total.png", 1),
29//!     "image/png",
30//!     640,
31//!     180,
32//! )
33//! .with_regions(json!({ "regions": [{ "label": "total", "shape": { "box": [12, 8, 300, 60] } }] }))
34//! .with_caption("Invoice 7, total field, after redaction");
35//!
36//! let call = ToolConfirmationRequest::new("vision_describe", json!({ "question": "What is the total?" }))
37//!     .with_evidence([Evidence::from(crop)]);
38//! assert_eq!(call.evidence[0].digest(), "sha256:9f2c0a7e5b1d4c8a6f3e2d1c0b9a8f7e6d5c4b3a2f1e0d9c8b7a6f5e4d3c2b1a");
39//! assert_eq!(serde_json::to_value(&call.evidence[0]).unwrap()["kind"], "image");
40//! ```
41
42use serde::{Deserialize, Serialize};
43use serde_json::Value;
44
45/// Where an artifact version lives in an `ArtifactService`: application, user, session,
46/// file name and version.
47///
48/// # Example
49///
50/// ```rust
51/// use adk_core::ArtifactLocator;
52///
53/// let locator = ArtifactLocator::new("desk", "ana", "s1", "egress/crop.png", 3);
54/// assert_eq!(
55///     serde_json::to_value(&locator).unwrap(),
56///     serde_json::json!({
57///         "appName": "desk", "userId": "ana", "sessionId": "s1",
58///         "fileName": "egress/crop.png", "version": 3
59///     })
60/// );
61/// ```
62#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64#[non_exhaustive]
65pub struct ArtifactLocator {
66    /// The application namespace.
67    pub app_name: String,
68    /// The owning user.
69    pub user_id: String,
70    /// The session the artifact belongs to.
71    pub session_id: String,
72    /// The artifact's file name.
73    pub file_name: String,
74    /// The exact version, so the evidence never moves to a later save.
75    pub version: i64,
76}
77
78impl ArtifactLocator {
79    /// The locator of `version` of `file_name` in the given session.
80    pub fn new(
81        app_name: impl Into<String>,
82        user_id: impl Into<String>,
83        session_id: impl Into<String>,
84        file_name: impl Into<String>,
85        version: i64,
86    ) -> Self {
87        Self {
88            app_name: app_name.into(),
89            user_id: user_id.into(),
90            session_id: session_id.into(),
91            file_name: file_name.into(),
92            version,
93        }
94    }
95}
96
97/// One item of evidence held with a call, tagged by `kind` on the wire.
98///
99/// # Example
100///
101/// ```rust
102/// use adk_core::{ArtifactLocator, Evidence, ImageEvidence};
103///
104/// let digest = "sha256:0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf12fe3a8";
105/// let evidence = Evidence::from(ImageEvidence::new(
106///     digest,
107///     ArtifactLocator::new("desk", "ana", "s1", "egress/card.png", 1),
108///     "image/png",
109///     1024,
110///     640,
111/// ));
112/// let json = serde_json::to_value(&evidence).unwrap();
113/// assert_eq!(json["kind"], "image");
114/// assert_eq!(serde_json::from_value::<Evidence>(json).unwrap(), evidence);
115/// assert_eq!(evidence.digest(), digest);
116/// ```
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase", tag = "kind")]
119#[non_exhaustive]
120pub enum Evidence {
121    /// An image the call would send, keep or act on.
122    Image(ImageEvidence),
123}
124
125impl Evidence {
126    /// The content digest of the evidence, such as `sha256:<hex>` of an image's encoded
127    /// bytes. A held call's fingerprint includes it.
128    pub fn digest(&self) -> &str {
129        match self {
130            Self::Image(image) => &image.digest,
131        }
132    }
133}
134
135impl From<ImageEvidence> for Evidence {
136    fn from(image: ImageEvidence) -> Self {
137        Self::Image(image)
138    }
139}
140
141/// An image held as evidence: its digest, its artifact, its format and size, and an optional
142/// overlay of regions and caption.
143///
144/// `regions` is a `RegionSet` in the wire form `adk-vision` publishes
145/// (`adk-vision/schema/region-set.json`), carried as JSON so surfaces can draw it without
146/// depending on `adk-vision`.
147///
148/// # Example
149///
150/// ```rust
151/// use adk_core::{ArtifactLocator, ImageEvidence};
152/// use serde_json::json;
153///
154/// let image = ImageEvidence::new(
155///     "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
156///     ArtifactLocator::new("desk", "ana", "s1", "egress/receipt.png", 2),
157///     "image/png",
158///     800,
159///     1200,
160/// )
161/// .with_caption("Receipt, faces and card number filled");
162/// assert_eq!(image.caption.as_deref(), Some("Receipt, faces and card number filled"));
163/// assert!(serde_json::to_value(&image).unwrap().get("regions").is_none());
164/// ```
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase")]
167#[non_exhaustive]
168pub struct ImageEvidence {
169    /// `sha256:<hex>` of the image's encoded bytes.
170    pub digest: String,
171    /// Where the image is stored.
172    pub artifact: ArtifactLocator,
173    /// `image/png`, `image/jpeg` or `image/webp`.
174    pub mime_type: String,
175    /// Width in pixels.
176    pub width: u32,
177    /// Height in pixels.
178    pub height: u32,
179    /// Regions to draw over the image, as a `RegionSet`.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub regions: Option<Value>,
182    /// One line describing the image for the approver.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub caption: Option<String>,
185}
186
187impl ImageEvidence {
188    /// The image with `digest`, stored at `artifact`, of `mime_type` and `width` × `height`
189    /// pixels.
190    pub fn new(
191        digest: impl Into<String>,
192        artifact: ArtifactLocator,
193        mime_type: impl Into<String>,
194        width: u32,
195        height: u32,
196    ) -> Self {
197        Self {
198            digest: digest.into(),
199            artifact,
200            mime_type: mime_type.into(),
201            width,
202            height,
203            regions: None,
204            caption: None,
205        }
206    }
207
208    /// Draws `regions`, a `RegionSet`, over the image.
209    #[must_use]
210    pub fn with_regions(mut self, regions: Value) -> Self {
211        self.regions = Some(regions);
212        self
213    }
214
215    /// Describes the image for the approver.
216    #[must_use]
217    pub fn with_caption(mut self, caption: impl Into<String>) -> Self {
218        self.caption = Some(caption.into());
219        self
220    }
221}