1mod 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#[non_exhaustive]
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub enum EgressApproval {
72 #[default]
78 GovernedPath,
79 Explicit,
82}
83
84#[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
106struct 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#[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#[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 pub fn approval(mut self, approval: EgressApproval) -> Self {
181 self.approval = approval;
182 self
183 }
184
185 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 #[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 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 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 pub fn runtime(&self) -> &Arc<VisionRuntime> {
249 &self.inner.runtime
250 }
251
252 pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
255 #[allow(unused_mut)] 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 pub fn tool_names(&self) -> Vec<&'static str> {
270 #[allow(unused_mut)] 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 #[cfg(feature = "stream")]
285 pub fn frame_sources(&self) -> Option<&crate::stream::FrameSources> {
286 self.inner.sources.as_ref()
287 }
288
289 pub fn is_tool(&self, name: &str) -> bool {
291 self.tool_names().contains(&name)
292 }
293
294 pub fn approve_egress(&self, digest: Digest) {
297 lock(&self.inner.approved).insert(digest);
298 }
299
300 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 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 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 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
353struct 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
364pub 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 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 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 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 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 None => EgressAction::Deny,
461 };
462 Some((action, hosts))
463 }
464
465 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 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 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 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 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 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 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 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
657fn 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
682fn call_key(kind: VisionToolKind, args: &Value) -> String {
684 format!("{}\u{1f}{}", kind.name(), canonical_json(args))
685}
686
687fn governed_key(call_id: &str, kind: VisionToolKind, args: &Value) -> String {
689 format!("{call_id}\u{1e}{}", call_key(kind, args))
690}
691
692fn 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}