Skip to main content

adk_vision/toolset/
mod.rs

1//! [`VisionToolset`]: the governed vision tools (spec 3.7 §7.8).
2//!
3//! Every tool is an `adk_core::Tool`, so an agent dispatches it through
4//! `adk_core::authorize_tool_call`, the one governed path: policy, guardrails, confirmation,
5//! the kill switch, the action ledger and the signed audit trail apply as they do to any
6//! tool. On top of that:
7//!
8//! - **Destinations.** A call routed to a remote backend declares the backend's hosts as its
9//!   `ToolEgress`, so the run's egress policy refuses an unlisted host before anything runs.
10//! - **Approve with the image.** [`VisionToolset::evidence_callback`] stages what a remote
11//!   call would send — destination checked, cropped, redacted, the copy stored as an
12//!   artifact — before the call is authorized, and the tool's
13//!   [`approval_evidence`](adk_core::Tool::approval_evidence) hands the governed path that
14//!   exact image. Its digest joins the call's fingerprint, so a decision binds to it and a
15//!   changed image holds the call again (V-I5).
16//! - **The egress rule decides.** [`VisionToolset::egress_policy`] is a `ToolPolicy` that
17//!   applies `.adk/vision.toml` per call: `deny` refuses, `ask` holds for a person, `allow`
18//!   lets the call run. A call held under `ask` and then approved releases exactly the
19//!   digests its evidence named; nothing else leaves.
20//! - **Budgets and audit.** Each backend call opens its hold before any image is released
21//!   and records its units; every call writes `vision.call`, every release
22//!   `vision.egress.released`, every edit `vision.edit` to the run's audit trail.
23//!
24//! | Tool | Does | Effect |
25//! |------|------|--------|
26//! | `vision_detect` | Objects by class or concept | `ReadOnly` |
27//! | `vision_segment` | Masks from concepts, boxes or points | `ReadOnly` |
28//! | `vision_read` | Text, tables and fields of a document page | `ReadOnly` |
29//! | `vision_describe` | An answer about the image, as text or a value matching a schema | `ReadOnly` |
30//! | `vision_crop` | A new image of a region | `Idempotent` |
31//! | `vision_redact` | A new image with regions filled solid black | `Idempotent` |
32//! | `vision_annotate` | A new image with labelled boxes drawn | `Idempotent` |
33//! | `vision_measure` | Maximum length and area in millimetres, from masks under a fiducial's calibration | `ReadOnly` |
34//! | `vision_video` | Frames in time order asked about, captioned in chunks, or tracked by concept | `ReadOnly` |
35//! | `vision_watch` | Lists the registered frame sources, and starts or stops a watch condition on one (feature `stream`, with [`VisionToolsetBuilder::frame_sources`]) | `Idempotent` |
36
37mod answer;
38mod tools;
39#[cfg(feature = "stream")]
40mod watch;
41
42use std::collections::{HashMap, HashSet};
43use std::sync::{Arc, Mutex};
44
45use adk_core::audit_log::AuditActor;
46use adk_core::{
47    Artifacts, BeforeToolCallback, CallbackContext, Content, ImageEvidence, ModelCallScope, Part,
48    PolicyCall, PolicyDecision, ReadonlyContext, Tool, ToolContext, ToolPolicy, ToolPolicyRequest,
49    Toolset,
50};
51use async_trait::async_trait;
52use serde_json::Value;
53
54pub use answer::{ANSWER_ARTIFACT_PREFIX, answer_artifact_name};
55pub use tools::{MAX_VIDEO_FRAMES, VISION_TOOL_NAMES, VisionTool, VisionToolKind};
56#[cfg(feature = "stream")]
57pub use watch::VISION_WATCH_TOOL;
58
59use crate::backend::BackendDescriptor;
60use crate::cx::VisionCx;
61use crate::digest::Digest;
62use crate::egress::{DataClass, EgressAction, ReleaseRequest};
63use crate::error::{Result, VisionError};
64use crate::geometry::BBox;
65use crate::media::{ImageRef, MediaScope, MediaStore, Provenance, SourceImage};
66use crate::runtime::{CallOptions, Route, VisionRuntime};
67
68/// How an `ask` egress rule is satisfied for a call a vision tool makes.
69#[non_exhaustive]
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub enum EgressApproval {
72    /// The governed path asks. [`VisionToolset::egress_policy`], installed on the run, holds
73    /// every call whose rule asks, and [`VisionToolset::evidence_callback`] puts the exact
74    /// egress image on the held call. A call that then executes releases exactly the digests
75    /// its evidence named. A call the policy did not hold, or one without staged evidence,
76    /// is refused, so a run missing either piece fails closed.
77    #[default]
78    GovernedPath,
79    /// Only digests approved through [`VisionToolset::approve_egress`] are released, for
80    /// applications that show the image and record the decision themselves.
81    Explicit,
82}
83
84/// What [`VisionToolset::evidence_callback`] staged for one call: the egress digests and the
85/// evidence an approver sees.
86#[derive(Clone, Debug)]
87struct StagedCall {
88    digests: Vec<Digest>,
89    evidence: Vec<ImageEvidence>,
90}
91
92pub(crate) struct Inner {
93    runtime: Arc<VisionRuntime>,
94    store: MediaStore,
95    approval: EgressApproval,
96    image_class: DataClass,
97    crop_class: DataClass,
98    images: Mutex<HashMap<(MediaScope, Digest), ImageRef>>,
99    staged: Mutex<HashMap<String, StagedCall>>,
100    governed: Mutex<HashMap<String, EgressAction>>,
101    approved: Mutex<HashSet<Digest>>,
102    #[cfg(feature = "stream")]
103    sources: Option<crate::stream::FrameSources>,
104}
105
106/// One planned call: its route, the primary backend's descriptor, the images it names,
107/// the crop the gate sends and the data class it is released as.
108struct Plan {
109    route: Route,
110    descriptor: BackendDescriptor,
111    images: Vec<String>,
112    crop: Option<BBox>,
113    class: DataClass,
114}
115
116impl Plan {
117    fn is_remote(&self) -> bool {
118        self.descriptor.locality.is_remote()
119    }
120}
121
122/// The governed vision tools over a [`VisionRuntime`].
123///
124/// Images are named by their `sha256:` digest, as the tools return them, or by the name of
125/// an artifact in the session; the toolset stores each one it reads in the runtime's media
126/// store, by digest. Install three pieces on the agent and run:
127///
128/// | Piece | Where | Why |
129/// |-------|-------|-----|
130/// | The toolset | `LlmAgentBuilder::toolset` | The tools |
131/// | [`evidence_callback`](Self::evidence_callback) | `LlmAgentBuilder::before_tool_callback` | A held remote call carries its egress image |
132/// | [`egress_policy`](Self::egress_policy) | `RunConfig::tool_policy` or `Runner::builder().tool_policy` | `.adk/vision.toml` decides each remote call: deny, ask or allow |
133///
134/// The `adk-harness` vision pack installs all three.
135///
136/// # Example
137///
138/// ```
139/// use std::sync::Arc;
140/// use adk_artifact::InMemoryArtifactService;
141/// use adk_vision::{DeterministicEditor, MediaStore, VisionRuntime, VisionToolset};
142///
143/// let store = MediaStore::new(Arc::new(InMemoryArtifactService::new()));
144/// let runtime = VisionRuntime::builder()
145///     .editor(Arc::new(DeterministicEditor::new()))
146///     .media_store(store)
147///     .build()
148///     .unwrap();
149/// let toolset = VisionToolset::builder(Arc::new(runtime)).build().unwrap();
150/// // Only the tasks the runtime has a backend for become tools.
151/// assert_eq!(toolset.tool_names(), vec!["vision_crop", "vision_redact", "vision_annotate"]);
152/// ```
153#[derive(Clone)]
154pub struct VisionToolset {
155    inner: Arc<Inner>,
156}
157
158impl std::fmt::Debug for VisionToolset {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.debug_struct("VisionToolset")
161            .field("tools", &self.tool_names())
162            .field("approval", &self.inner.approval)
163            .finish_non_exhaustive()
164    }
165}
166
167/// Builds a [`VisionToolset`].
168#[must_use]
169pub struct VisionToolsetBuilder {
170    runtime: Arc<VisionRuntime>,
171    approval: EgressApproval,
172    image_class: DataClass,
173    crop_class: DataClass,
174    #[cfg(feature = "stream")]
175    sources: Option<crate::stream::FrameSources>,
176}
177
178impl VisionToolsetBuilder {
179    /// How `ask` rules are satisfied; [`EgressApproval::GovernedPath`] by default.
180    pub fn approval(mut self, approval: EgressApproval) -> Self {
181        self.approval = approval;
182        self
183    }
184
185    /// The data classes images are released as: `image` for a whole image and `crop` for a
186    /// call that names a region. `image` and `image_crop` by default. The operator sets
187    /// them, never the model, since the egress rules are written per class.
188    pub fn data_classes(mut self, image: &str, crop: &str) -> Self {
189        self.image_class = DataClass::new(image);
190        self.crop_class = DataClass::new(crop);
191        self
192    }
193
194    /// Offers `vision_watch` over `sources`: an agent lists them and starts or stops watch
195    /// conditions on them (spec 3.7 §7.8).
196    #[cfg(feature = "stream")]
197    pub fn frame_sources(mut self, sources: crate::stream::FrameSources) -> Self {
198        self.sources = Some(sources);
199        self
200    }
201
202    /// Builds the toolset.
203    ///
204    /// # Errors
205    ///
206    /// [`VisionError::InvalidInput`] when the runtime has no media store: the tools keep
207    /// every image they read and make as an artifact.
208    pub fn build(self) -> Result<VisionToolset> {
209        let store = self.runtime.media_store().cloned().ok_or_else(|| {
210            VisionError::InvalidInput(
211                "the vision tools keep images as artifacts; give the runtime a media store \
212                 (VisionRuntimeBuilder::media_store)"
213                    .into(),
214            )
215        })?;
216        Ok(VisionToolset {
217            inner: Arc::new(Inner {
218                runtime: self.runtime,
219                store,
220                approval: self.approval,
221                image_class: self.image_class,
222                crop_class: self.crop_class,
223                images: Mutex::new(HashMap::new()),
224                staged: Mutex::new(HashMap::new()),
225                governed: Mutex::new(HashMap::new()),
226                approved: Mutex::new(HashSet::new()),
227                #[cfg(feature = "stream")]
228                sources: self.sources,
229            }),
230        })
231    }
232}
233
234impl VisionToolset {
235    /// A builder over `runtime`, which needs a media store.
236    pub fn builder(runtime: Arc<VisionRuntime>) -> VisionToolsetBuilder {
237        VisionToolsetBuilder {
238            runtime,
239            approval: EgressApproval::default(),
240            image_class: DataClass::new("image"),
241            crop_class: DataClass::new("image_crop"),
242            #[cfg(feature = "stream")]
243            sources: None,
244        }
245    }
246
247    /// The runtime the tools call.
248    pub fn runtime(&self) -> &Arc<VisionRuntime> {
249        &self.inner.runtime
250    }
251
252    /// The tools, one per task the runtime has a backend for, and `vision_watch` when the
253    /// toolset has frame sources.
254    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
255        #[allow(unused_mut)] // `vision_watch` joins only with feature `stream`.
256        let mut tools: Vec<Arc<dyn Tool>> = VisionToolKind::ALL
257            .iter()
258            .filter(|kind| self.inner.serves(**kind))
259            .map(|kind| Arc::new(VisionTool::new(*kind, self.inner.clone())) as Arc<dyn Tool>)
260            .collect();
261        #[cfg(feature = "stream")]
262        if let Some(sources) = &self.inner.sources {
263            tools.push(Arc::new(watch::VisionWatchTool::new(sources.clone())));
264        }
265        tools
266    }
267
268    /// The names of [`tools`](Self::tools).
269    pub fn tool_names(&self) -> Vec<&'static str> {
270        #[allow(unused_mut)] // `vision_watch` joins only with feature `stream`.
271        let mut names: Vec<&'static str> = VisionToolKind::ALL
272            .iter()
273            .filter(|kind| self.inner.serves(**kind))
274            .map(|kind| kind.name())
275            .collect();
276        #[cfg(feature = "stream")]
277        if self.inner.sources.is_some() {
278            names.push(watch::VISION_WATCH_TOOL);
279        }
280        names
281    }
282
283    /// The frame sources `vision_watch` serves, when the toolset has them.
284    #[cfg(feature = "stream")]
285    pub fn frame_sources(&self) -> Option<&crate::stream::FrameSources> {
286        self.inner.sources.as_ref()
287    }
288
289    /// Whether `name` is one of this toolset's tools.
290    pub fn is_tool(&self, name: &str) -> bool {
291        self.tool_names().contains(&name)
292    }
293
294    /// Approves an egress digest for [`EgressApproval::Explicit`]: the next call whose
295    /// staged image has this digest may release it.
296    pub fn approve_egress(&self, digest: Digest) {
297        lock(&self.inner.approved).insert(digest);
298    }
299
300    /// Whether a call of `tool` with `args` would send an image off the machine: its route's
301    /// primary backend is remote.
302    pub fn is_remote_call(&self, tool: &str, args: &Value) -> bool {
303        VisionToolKind::from_name(tool)
304            .and_then(|kind| self.inner.plan(kind, args).ok())
305            .is_some_and(|plan| plan.is_remote())
306    }
307
308    /// What the egress rules say about a call of `tool` with `args`: `None` for a call that
309    /// stays on the device (or does not parse), else the rule's action for its destination
310    /// and data class. A harness classes the call by it (spec 3.7 X15).
311    pub fn egress_action(&self, tool: &str, args: &Value) -> Option<EgressAction> {
312        let kind = VisionToolKind::from_name(tool)?;
313        let plan = self.inner.plan(kind, args).ok()?;
314        self.inner.egress_action(&plan).map(|(action, _)| action)
315    }
316
317    /// The `BeforeToolCallback` that stages what a remote call would send, so the call is
318    /// held with the exact egress image (spec 3.7 S4).
319    ///
320    /// For a vision tool call routed to a remote backend it resolves the image, runs the
321    /// egress gate's destination, minimise and redact steps, stores the egress copy, and
322    /// keeps the copy's evidence for the tool's `approval_evidence`. It answers no call it
323    /// can stage; a call the gate refuses outright — an unlisted host, a missing redactor, a
324    /// rule that denies — is answered with the refusal, so nobody is asked about an image
325    /// that can never leave.
326    pub fn evidence_callback(&self) -> BeforeToolCallback {
327        let inner = self.inner.clone();
328        Box::new(move |ctx: Arc<dyn CallbackContext>| {
329            let inner = inner.clone();
330            Box::pin(async move { inner.stage_call(ctx).await })
331        })
332    }
333
334    /// The `ToolPolicy` that applies the egress rules to each vision call: `deny` refuses,
335    /// `ask` requires a person's approval, `allow` and on-device calls are allowed. Compose
336    /// it with the run's other policies (`StrictestPolicy`); it decides no other tool.
337    pub fn egress_policy(&self) -> Arc<dyn ToolPolicy> {
338        Arc::new(VisionEgressPolicy { inner: self.inner.clone() })
339    }
340}
341
342#[async_trait]
343impl Toolset for VisionToolset {
344    fn name(&self) -> &str {
345        "vision"
346    }
347
348    async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> adk_core::Result<Vec<Arc<dyn Tool>>> {
349        Ok(VisionToolset::tools(self))
350    }
351}
352
353/// Applies `.adk/vision.toml` to each vision tool call; see [`VisionToolset::egress_policy`].
354struct VisionEgressPolicy {
355    inner: Arc<Inner>,
356}
357
358impl std::fmt::Debug for VisionEgressPolicy {
359    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360        f.debug_struct("VisionEgressPolicy").finish_non_exhaustive()
361    }
362}
363
364/// `policy_ref` of the vision egress policy in audit records.
365pub const VISION_EGRESS_POLICY_REF: &str = "adk-vision-egress";
366
367#[async_trait]
368impl ToolPolicy for VisionEgressPolicy {
369    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
370        self.evaluate_call(request, &PolicyCall::new()).await
371    }
372
373    async fn evaluate_call(
374        &self,
375        request: &ToolPolicyRequest,
376        call: &PolicyCall<'_>,
377    ) -> PolicyDecision {
378        let Some(kind) = VisionToolKind::from_name(&request.tool_name) else {
379            return PolicyDecision::Allow;
380        };
381        if !self.inner.serves(kind) {
382            return PolicyDecision::Allow;
383        }
384        // A call whose arguments do not parse is refused by the tool itself.
385        let Ok(plan) = self.inner.plan(kind, &request.args) else {
386            return PolicyDecision::Allow;
387        };
388        let Some((action, hosts)) = self.inner.egress_action(&plan) else {
389            return PolicyDecision::Allow;
390        };
391        let key = governed_key(call.function_call_id.unwrap_or_default(), kind, &request.args);
392        lock(&self.inner.governed).insert(key, action);
393        match action {
394            EgressAction::Allow => PolicyDecision::Allow,
395            EgressAction::Ask => PolicyDecision::require_approval(format!(
396                "`{}` would send an image to {} as `{}`; the egress rule asks a person first",
397                request.tool_name,
398                hosts.join(", "),
399                plan.class
400            )),
401            EgressAction::Deny => PolicyDecision::deny(format!(
402                "the egress rules deny sending `{}` images to {}",
403                plan.class,
404                hosts.join(", ")
405            )),
406        }
407    }
408
409    fn policy_ref(&self) -> Option<String> {
410        Some(VISION_EGRESS_POLICY_REF.to_string())
411    }
412}
413
414impl Inner {
415    /// Whether the runtime has a backend for `kind`'s task.
416    fn serves(&self, kind: VisionToolKind) -> bool {
417        self.runtime.route(kind.task(), &CallOptions::new()).is_ok()
418    }
419
420    fn plan(&self, kind: VisionToolKind, args: &Value) -> Result<Plan> {
421        let task = kind.task();
422        let mut options = CallOptions::new();
423        if let Some(backend) = args.get("backend").and_then(Value::as_str) {
424            options = options.with_route(Route::to(backend));
425        }
426        let route = self.runtime.route(task, &options)?;
427        let descriptor = self
428            .runtime
429            .descriptor(task, &route.primary)
430            .cloned()
431            .ok_or_else(|| VisionError::BackendNotFound(route.primary.to_string()))?;
432        let images = match kind {
433            VisionToolKind::Video => video_frames(args)?,
434            _ => vec![
435                args.get("image")
436                    .and_then(Value::as_str)
437                    .ok_or_else(|| VisionError::InvalidInput("`image` is required".into()))?
438                    .to_string(),
439            ],
440        };
441        // Edits keep their region as the operation's; only perception crops what it sends.
442        let crop = match kind.is_edit() {
443            true => None,
444            false => args.get("region").map(tools::bbox_arg).transpose()?,
445        };
446        let class = if crop.is_some() { self.crop_class.clone() } else { self.image_class.clone() };
447        Ok(Plan { route, descriptor, images, crop, class })
448    }
449
450    /// The egress rule's action for a remote plan, and the destination hosts; `None` for a
451    /// plan that stays on the device.
452    fn egress_action(&self, plan: &Plan) -> Option<(EgressAction, Vec<String>)> {
453        let hosts = match &plan.descriptor.locality {
454            crate::backend::Locality::Remote { hosts } => hosts.clone(),
455            _ => return None,
456        };
457        let action = match self.runtime.egress_gate() {
458            Some(gate) => gate.decide(&plan.descriptor, &plan.class).0,
459            // Without a gate the runtime refuses every remote call.
460            None => EgressAction::Deny,
461        };
462        Some((action, hosts))
463    }
464
465    /// Resolves an image argument: a `sha256:` digest of an image this session holds, or
466    /// the name of an artifact in the session.
467    async fn resolve(
468        &self,
469        artifacts: Option<&Arc<dyn Artifacts>>,
470        scope: &MediaScope,
471        image: &str,
472    ) -> Result<SourceImage> {
473        if let Some(hex) = image.strip_prefix("sha256:") {
474            let digest = Digest::from_hex(hex)?;
475            let known = lock(&self.images).get(&(scope.clone(), digest)).cloned();
476            if let Some(known) = known {
477                return self.store.load(&known).await;
478            }
479            // The media store names every image it keeps by digest.
480            if let Some(artifacts) = artifacts {
481                for extension in ["png", "jpeg", "webp", "gif"] {
482                    let name = format!("vision-{hex}.{extension}");
483                    if let Ok(part) = artifacts.load(&name).await {
484                        return self.adopt(scope, part, Some(digest), &name).await;
485                    }
486                }
487            }
488            return Err(VisionError::InvalidInput(format!(
489                "this session holds no image with digest {image}; name an artifact or a digest \
490                 an earlier vision tool returned"
491            )));
492        }
493        let artifacts = artifacts.ok_or_else(|| {
494            VisionError::InvalidInput(format!(
495                "`{image}` names an artifact, and this run has no artifact service"
496            ))
497        })?;
498        let part = artifacts.load(image).await.map_err(|err| {
499            VisionError::InvalidInput(format!("artifact `{image}` could not be loaded: {err}"))
500        })?;
501        self.adopt(scope, part, None, image).await
502    }
503
504    async fn adopt(
505        &self,
506        scope: &MediaScope,
507        part: Part,
508        expected: Option<Digest>,
509        name: &str,
510    ) -> Result<SourceImage> {
511        let Part::InlineData { data, .. } = part else {
512            return Err(VisionError::InvalidInput(format!(
513                "artifact `{name}` does not hold an image"
514            )));
515        };
516        if let Some(expected) = expected {
517            let actual = Digest::of(&data);
518            if actual != expected {
519                return Err(VisionError::DigestMismatch { path: name.into(), expected, actual });
520            }
521        }
522        let (image, source) = self.store.put_image(scope, data, Provenance::Upload).await?;
523        self.remember(scope, image);
524        Ok(source)
525    }
526
527    /// The image this toolset stored under `digest` for `scope`.
528    fn known(&self, scope: &MediaScope, digest: &Digest) -> Option<ImageRef> {
529        lock(&self.images).get(&(scope.clone(), *digest)).cloned()
530    }
531
532    fn remember(&self, scope: &MediaScope, image: ImageRef) {
533        lock(&self.images).insert((scope.clone(), image.digest), image);
534    }
535
536    /// Stages a remote call's egress images and keeps their evidence; see
537    /// [`VisionToolset::evidence_callback`].
538    async fn stage_call(&self, ctx: Arc<dyn CallbackContext>) -> adk_core::Result<Option<Content>> {
539        let Some(kind) = ctx.tool_name().and_then(VisionToolKind::from_name) else {
540            return Ok(None);
541        };
542        let args = ctx.tool_input().cloned().unwrap_or(Value::Null);
543        let key = call_key(kind, &args);
544        lock(&self.staged).remove(&key);
545        if !self.serves(kind) {
546            return Ok(None);
547        }
548        let Ok(plan) = self.plan(kind, &args) else {
549            return Ok(None);
550        };
551        let Some(gate) = self.runtime.egress_gate().filter(|_| plan.is_remote()) else {
552            return Ok(None);
553        };
554        let scope = MediaScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id());
555        let cx =
556            VisionCx::current().with_media_scope(scope.clone()).with_acting(ctx.acting_context());
557        let artifacts = ctx.artifacts();
558        let mut staged = StagedCall { digests: Vec::new(), evidence: Vec::new() };
559        for image in &plan.images {
560            let source = match self.resolve(artifacts.as_ref(), &scope, image).await {
561                Ok(source) => source,
562                // The tool reports an image it cannot read when it runs.
563                Err(_) => return Ok(None),
564            };
565            let mut request = ReleaseRequest::new(&source, &plan.descriptor, plan.class.clone());
566            if let Some(crop) = plan.crop {
567                request = request.with_crop(crop);
568            }
569            match gate.stage(&cx, &request).await {
570                Ok(stage) => {
571                    staged.digests.push(stage.digest());
572                    if let Some(evidence) = stage.image_evidence() {
573                        staged.evidence.push(evidence);
574                    }
575                }
576                Err(err) => {
577                    let text = format!("`{}` was not run: {err}", kind.name());
578                    return Ok(Some(Content::new("function").with_text(text)));
579                }
580            }
581        }
582        tracing::debug!(
583            vision.tool = kind.name(),
584            vision.staged = staged.digests.len(),
585            "egress staged for approval"
586        );
587        lock(&self.staged).insert(key, staged);
588        Ok(None)
589    }
590
591    /// The evidence staged for a call with these arguments.
592    fn evidence_for(&self, kind: VisionToolKind, args: &Value) -> Vec<adk_core::Evidence> {
593        lock(&self.staged)
594            .get(&call_key(kind, args))
595            .map(|staged| staged.evidence.iter().cloned().map(adk_core::Evidence::from).collect())
596            .unwrap_or_default()
597    }
598
599    /// The egress digests this call may release, by the approval mode.
600    fn approvals(
601        &self,
602        kind: VisionToolKind,
603        plan: &Plan,
604        call_id: &str,
605        args: &Value,
606    ) -> Result<Vec<Digest>> {
607        let governed = lock(&self.governed).remove(&governed_key(call_id, kind, args));
608        let staged = lock(&self.staged).remove(&call_key(kind, args));
609        let Some((action, hosts)) = self.egress_action(plan) else {
610            return Ok(Vec::new());
611        };
612        if action != EgressAction::Ask {
613            return Ok(Vec::new());
614        }
615        match self.approval {
616            EgressApproval::Explicit => Ok(lock(&self.approved).iter().copied().collect()),
617            EgressApproval::GovernedPath => {
618                let refused = |reason: &str| VisionError::EgressRefused {
619                    host: hosts.join(", "),
620                    reason: reason.to_string(),
621                };
622                if governed != Some(EgressAction::Ask) {
623                    return Err(refused(
624                        "the egress rule asks a person first and this call was not held for \
625                         approval; install VisionToolset::egress_policy on the run",
626                    ));
627                }
628                let Some(staged) = staged.filter(|staged| !staged.evidence.is_empty()) else {
629                    return Err(refused(
630                        "the call was held without the image it would send; install \
631                         VisionToolset::evidence_callback on the agent and give the egress gate \
632                         a media store",
633                    ));
634                };
635                Ok(staged.digests)
636            }
637        }
638    }
639
640    /// The context a tool call runs vision calls under: the run's metering scope, the
641    /// session's media scope, the acting agent and the run's audit trail.
642    fn cx_for(ctx: &dyn ToolContext) -> VisionCx {
643        let scope =
644            ModelCallScope::current().or_else(|| ModelCallScope::for_tool(ctx)).unwrap_or_default();
645        let acting = ctx.acting_context();
646        let mut cx = VisionCx::new()
647            .with_scope(scope)
648            .with_media_scope(MediaScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id()))
649            .with_acting(acting.clone());
650        if let Some(trail) = ctx.run_config().and_then(|config| config.audit.clone()) {
651            cx = cx.with_audit(trail, AuditActor::new(&acting, ctx.invocation_id()));
652        }
653        cx
654    }
655}
656
657/// The frames a `vision_video` call names, oldest first: one to
658/// [`MAX_VIDEO_FRAMES`](tools::MAX_VIDEO_FRAMES).
659fn video_frames(args: &Value) -> Result<Vec<String>> {
660    let frames = args.get("frames").and_then(Value::as_array).ok_or_else(|| {
661        VisionError::InvalidInput("`frames` is required: a list of images".into())
662    })?;
663    if frames.is_empty() || frames.len() > tools::MAX_VIDEO_FRAMES {
664        return Err(VisionError::InvalidInput(format!(
665            "`frames` holds 1 to {} images, not {}; sample fewer frames",
666            tools::MAX_VIDEO_FRAMES,
667            frames.len()
668        )));
669    }
670    frames
671        .iter()
672        .map(|frame| {
673            frame.as_str().map(str::to_string).ok_or_else(|| {
674                VisionError::InvalidInput(format!(
675                    "each frame is a `sha256:` digest or an artifact name, not {frame}"
676                ))
677            })
678        })
679        .collect()
680}
681
682/// The key a call's staged evidence is kept under: the tool and its canonical arguments.
683fn call_key(kind: VisionToolKind, args: &Value) -> String {
684    format!("{}\u{1f}{}", kind.name(), canonical_json(args))
685}
686
687/// The key the egress policy marks a call under: its function call ID and [`call_key`].
688fn governed_key(call_id: &str, kind: VisionToolKind, args: &Value) -> String {
689    format!("{call_id}\u{1e}{}", call_key(kind, args))
690}
691
692/// JSON with every object's keys sorted, so equal arguments give equal keys.
693fn canonical_json(value: &Value) -> String {
694    fn sorted(value: &Value) -> Value {
695        match value {
696            Value::Object(map) => {
697                let mut entries: Vec<(&String, &Value)> = map.iter().collect();
698                entries.sort_by(|a, b| a.0.cmp(b.0));
699                Value::Object(entries.into_iter().map(|(k, v)| (k.clone(), sorted(v))).collect())
700            }
701            Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
702            other => other.clone(),
703        }
704    }
705    sorted(value).to_string()
706}
707
708fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
709    mutex.lock().unwrap_or_else(|e| e.into_inner())
710}