mod answer;
mod tools;
#[cfg(feature = "stream")]
mod watch;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use adk_core::audit_log::AuditActor;
use adk_core::{
Artifacts, BeforeToolCallback, CallbackContext, Content, ImageEvidence, ModelCallScope, Part,
PolicyCall, PolicyDecision, ReadonlyContext, Tool, ToolContext, ToolPolicy, ToolPolicyRequest,
Toolset,
};
use async_trait::async_trait;
use serde_json::Value;
pub use answer::{ANSWER_ARTIFACT_PREFIX, answer_artifact_name};
pub use tools::{MAX_VIDEO_FRAMES, VISION_TOOL_NAMES, VisionTool, VisionToolKind};
#[cfg(feature = "stream")]
pub use watch::VISION_WATCH_TOOL;
use crate::backend::BackendDescriptor;
use crate::cx::VisionCx;
use crate::digest::Digest;
use crate::egress::{DataClass, EgressAction, ReleaseRequest};
use crate::error::{Result, VisionError};
use crate::geometry::BBox;
use crate::media::{ImageRef, MediaScope, MediaStore, Provenance, SourceImage};
use crate::runtime::{CallOptions, Route, VisionRuntime};
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EgressApproval {
#[default]
GovernedPath,
Explicit,
}
#[derive(Clone, Debug)]
struct StagedCall {
digests: Vec<Digest>,
evidence: Vec<ImageEvidence>,
}
pub(crate) struct Inner {
runtime: Arc<VisionRuntime>,
store: MediaStore,
approval: EgressApproval,
image_class: DataClass,
crop_class: DataClass,
images: Mutex<HashMap<(MediaScope, Digest), ImageRef>>,
staged: Mutex<HashMap<String, StagedCall>>,
governed: Mutex<HashMap<String, EgressAction>>,
approved: Mutex<HashSet<Digest>>,
#[cfg(feature = "stream")]
sources: Option<crate::stream::FrameSources>,
}
struct Plan {
route: Route,
descriptor: BackendDescriptor,
images: Vec<String>,
crop: Option<BBox>,
class: DataClass,
}
impl Plan {
fn is_remote(&self) -> bool {
self.descriptor.locality.is_remote()
}
}
#[derive(Clone)]
pub struct VisionToolset {
inner: Arc<Inner>,
}
impl std::fmt::Debug for VisionToolset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VisionToolset")
.field("tools", &self.tool_names())
.field("approval", &self.inner.approval)
.finish_non_exhaustive()
}
}
#[must_use]
pub struct VisionToolsetBuilder {
runtime: Arc<VisionRuntime>,
approval: EgressApproval,
image_class: DataClass,
crop_class: DataClass,
#[cfg(feature = "stream")]
sources: Option<crate::stream::FrameSources>,
}
impl VisionToolsetBuilder {
pub fn approval(mut self, approval: EgressApproval) -> Self {
self.approval = approval;
self
}
pub fn data_classes(mut self, image: &str, crop: &str) -> Self {
self.image_class = DataClass::new(image);
self.crop_class = DataClass::new(crop);
self
}
#[cfg(feature = "stream")]
pub fn frame_sources(mut self, sources: crate::stream::FrameSources) -> Self {
self.sources = Some(sources);
self
}
pub fn build(self) -> Result<VisionToolset> {
let store = self.runtime.media_store().cloned().ok_or_else(|| {
VisionError::InvalidInput(
"the vision tools keep images as artifacts; give the runtime a media store \
(VisionRuntimeBuilder::media_store)"
.into(),
)
})?;
Ok(VisionToolset {
inner: Arc::new(Inner {
runtime: self.runtime,
store,
approval: self.approval,
image_class: self.image_class,
crop_class: self.crop_class,
images: Mutex::new(HashMap::new()),
staged: Mutex::new(HashMap::new()),
governed: Mutex::new(HashMap::new()),
approved: Mutex::new(HashSet::new()),
#[cfg(feature = "stream")]
sources: self.sources,
}),
})
}
}
impl VisionToolset {
pub fn builder(runtime: Arc<VisionRuntime>) -> VisionToolsetBuilder {
VisionToolsetBuilder {
runtime,
approval: EgressApproval::default(),
image_class: DataClass::new("image"),
crop_class: DataClass::new("image_crop"),
#[cfg(feature = "stream")]
sources: None,
}
}
pub fn runtime(&self) -> &Arc<VisionRuntime> {
&self.inner.runtime
}
pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
#[allow(unused_mut)] let mut tools: Vec<Arc<dyn Tool>> = VisionToolKind::ALL
.iter()
.filter(|kind| self.inner.serves(**kind))
.map(|kind| Arc::new(VisionTool::new(*kind, self.inner.clone())) as Arc<dyn Tool>)
.collect();
#[cfg(feature = "stream")]
if let Some(sources) = &self.inner.sources {
tools.push(Arc::new(watch::VisionWatchTool::new(sources.clone())));
}
tools
}
pub fn tool_names(&self) -> Vec<&'static str> {
#[allow(unused_mut)] let mut names: Vec<&'static str> = VisionToolKind::ALL
.iter()
.filter(|kind| self.inner.serves(**kind))
.map(|kind| kind.name())
.collect();
#[cfg(feature = "stream")]
if self.inner.sources.is_some() {
names.push(watch::VISION_WATCH_TOOL);
}
names
}
#[cfg(feature = "stream")]
pub fn frame_sources(&self) -> Option<&crate::stream::FrameSources> {
self.inner.sources.as_ref()
}
pub fn is_tool(&self, name: &str) -> bool {
self.tool_names().contains(&name)
}
pub fn approve_egress(&self, digest: Digest) {
lock(&self.inner.approved).insert(digest);
}
pub fn is_remote_call(&self, tool: &str, args: &Value) -> bool {
VisionToolKind::from_name(tool)
.and_then(|kind| self.inner.plan(kind, args).ok())
.is_some_and(|plan| plan.is_remote())
}
pub fn egress_action(&self, tool: &str, args: &Value) -> Option<EgressAction> {
let kind = VisionToolKind::from_name(tool)?;
let plan = self.inner.plan(kind, args).ok()?;
self.inner.egress_action(&plan).map(|(action, _)| action)
}
pub fn evidence_callback(&self) -> BeforeToolCallback {
let inner = self.inner.clone();
Box::new(move |ctx: Arc<dyn CallbackContext>| {
let inner = inner.clone();
Box::pin(async move { inner.stage_call(ctx).await })
})
}
pub fn egress_policy(&self) -> Arc<dyn ToolPolicy> {
Arc::new(VisionEgressPolicy { inner: self.inner.clone() })
}
}
#[async_trait]
impl Toolset for VisionToolset {
fn name(&self) -> &str {
"vision"
}
async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> adk_core::Result<Vec<Arc<dyn Tool>>> {
Ok(VisionToolset::tools(self))
}
}
struct VisionEgressPolicy {
inner: Arc<Inner>,
}
impl std::fmt::Debug for VisionEgressPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VisionEgressPolicy").finish_non_exhaustive()
}
}
pub const VISION_EGRESS_POLICY_REF: &str = "adk-vision-egress";
#[async_trait]
impl ToolPolicy for VisionEgressPolicy {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
self.evaluate_call(request, &PolicyCall::new()).await
}
async fn evaluate_call(
&self,
request: &ToolPolicyRequest,
call: &PolicyCall<'_>,
) -> PolicyDecision {
let Some(kind) = VisionToolKind::from_name(&request.tool_name) else {
return PolicyDecision::Allow;
};
if !self.inner.serves(kind) {
return PolicyDecision::Allow;
}
let Ok(plan) = self.inner.plan(kind, &request.args) else {
return PolicyDecision::Allow;
};
let Some((action, hosts)) = self.inner.egress_action(&plan) else {
return PolicyDecision::Allow;
};
let key = governed_key(call.function_call_id.unwrap_or_default(), kind, &request.args);
lock(&self.inner.governed).insert(key, action);
match action {
EgressAction::Allow => PolicyDecision::Allow,
EgressAction::Ask => PolicyDecision::require_approval(format!(
"`{}` would send an image to {} as `{}`; the egress rule asks a person first",
request.tool_name,
hosts.join(", "),
plan.class
)),
EgressAction::Deny => PolicyDecision::deny(format!(
"the egress rules deny sending `{}` images to {}",
plan.class,
hosts.join(", ")
)),
}
}
fn policy_ref(&self) -> Option<String> {
Some(VISION_EGRESS_POLICY_REF.to_string())
}
}
impl Inner {
fn serves(&self, kind: VisionToolKind) -> bool {
self.runtime.route(kind.task(), &CallOptions::new()).is_ok()
}
fn plan(&self, kind: VisionToolKind, args: &Value) -> Result<Plan> {
let task = kind.task();
let mut options = CallOptions::new();
if let Some(backend) = args.get("backend").and_then(Value::as_str) {
options = options.with_route(Route::to(backend));
}
let route = self.runtime.route(task, &options)?;
let descriptor = self
.runtime
.descriptor(task, &route.primary)
.cloned()
.ok_or_else(|| VisionError::BackendNotFound(route.primary.to_string()))?;
let images = match kind {
VisionToolKind::Video => video_frames(args)?,
_ => vec![
args.get("image")
.and_then(Value::as_str)
.ok_or_else(|| VisionError::InvalidInput("`image` is required".into()))?
.to_string(),
],
};
let crop = match kind.is_edit() {
true => None,
false => args.get("region").map(tools::bbox_arg).transpose()?,
};
let class = if crop.is_some() { self.crop_class.clone() } else { self.image_class.clone() };
Ok(Plan { route, descriptor, images, crop, class })
}
fn egress_action(&self, plan: &Plan) -> Option<(EgressAction, Vec<String>)> {
let hosts = match &plan.descriptor.locality {
crate::backend::Locality::Remote { hosts } => hosts.clone(),
_ => return None,
};
let action = match self.runtime.egress_gate() {
Some(gate) => gate.decide(&plan.descriptor, &plan.class).0,
None => EgressAction::Deny,
};
Some((action, hosts))
}
async fn resolve(
&self,
artifacts: Option<&Arc<dyn Artifacts>>,
scope: &MediaScope,
image: &str,
) -> Result<SourceImage> {
if let Some(hex) = image.strip_prefix("sha256:") {
let digest = Digest::from_hex(hex)?;
let known = lock(&self.images).get(&(scope.clone(), digest)).cloned();
if let Some(known) = known {
return self.store.load(&known).await;
}
if let Some(artifacts) = artifacts {
for extension in ["png", "jpeg", "webp", "gif"] {
let name = format!("vision-{hex}.{extension}");
if let Ok(part) = artifacts.load(&name).await {
return self.adopt(scope, part, Some(digest), &name).await;
}
}
}
return Err(VisionError::InvalidInput(format!(
"this session holds no image with digest {image}; name an artifact or a digest \
an earlier vision tool returned"
)));
}
let artifacts = artifacts.ok_or_else(|| {
VisionError::InvalidInput(format!(
"`{image}` names an artifact, and this run has no artifact service"
))
})?;
let part = artifacts.load(image).await.map_err(|err| {
VisionError::InvalidInput(format!("artifact `{image}` could not be loaded: {err}"))
})?;
self.adopt(scope, part, None, image).await
}
async fn adopt(
&self,
scope: &MediaScope,
part: Part,
expected: Option<Digest>,
name: &str,
) -> Result<SourceImage> {
let Part::InlineData { data, .. } = part else {
return Err(VisionError::InvalidInput(format!(
"artifact `{name}` does not hold an image"
)));
};
if let Some(expected) = expected {
let actual = Digest::of(&data);
if actual != expected {
return Err(VisionError::DigestMismatch { path: name.into(), expected, actual });
}
}
let (image, source) = self.store.put_image(scope, data, Provenance::Upload).await?;
self.remember(scope, image);
Ok(source)
}
fn known(&self, scope: &MediaScope, digest: &Digest) -> Option<ImageRef> {
lock(&self.images).get(&(scope.clone(), *digest)).cloned()
}
fn remember(&self, scope: &MediaScope, image: ImageRef) {
lock(&self.images).insert((scope.clone(), image.digest), image);
}
async fn stage_call(&self, ctx: Arc<dyn CallbackContext>) -> adk_core::Result<Option<Content>> {
let Some(kind) = ctx.tool_name().and_then(VisionToolKind::from_name) else {
return Ok(None);
};
let args = ctx.tool_input().cloned().unwrap_or(Value::Null);
let key = call_key(kind, &args);
lock(&self.staged).remove(&key);
if !self.serves(kind) {
return Ok(None);
}
let Ok(plan) = self.plan(kind, &args) else {
return Ok(None);
};
let Some(gate) = self.runtime.egress_gate().filter(|_| plan.is_remote()) else {
return Ok(None);
};
let scope = MediaScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id());
let cx =
VisionCx::current().with_media_scope(scope.clone()).with_acting(ctx.acting_context());
let artifacts = ctx.artifacts();
let mut staged = StagedCall { digests: Vec::new(), evidence: Vec::new() };
for image in &plan.images {
let source = match self.resolve(artifacts.as_ref(), &scope, image).await {
Ok(source) => source,
Err(_) => return Ok(None),
};
let mut request = ReleaseRequest::new(&source, &plan.descriptor, plan.class.clone());
if let Some(crop) = plan.crop {
request = request.with_crop(crop);
}
match gate.stage(&cx, &request).await {
Ok(stage) => {
staged.digests.push(stage.digest());
if let Some(evidence) = stage.image_evidence() {
staged.evidence.push(evidence);
}
}
Err(err) => {
let text = format!("`{}` was not run: {err}", kind.name());
return Ok(Some(Content::new("function").with_text(text)));
}
}
}
tracing::debug!(
vision.tool = kind.name(),
vision.staged = staged.digests.len(),
"egress staged for approval"
);
lock(&self.staged).insert(key, staged);
Ok(None)
}
fn evidence_for(&self, kind: VisionToolKind, args: &Value) -> Vec<adk_core::Evidence> {
lock(&self.staged)
.get(&call_key(kind, args))
.map(|staged| staged.evidence.iter().cloned().map(adk_core::Evidence::from).collect())
.unwrap_or_default()
}
fn approvals(
&self,
kind: VisionToolKind,
plan: &Plan,
call_id: &str,
args: &Value,
) -> Result<Vec<Digest>> {
let governed = lock(&self.governed).remove(&governed_key(call_id, kind, args));
let staged = lock(&self.staged).remove(&call_key(kind, args));
let Some((action, hosts)) = self.egress_action(plan) else {
return Ok(Vec::new());
};
if action != EgressAction::Ask {
return Ok(Vec::new());
}
match self.approval {
EgressApproval::Explicit => Ok(lock(&self.approved).iter().copied().collect()),
EgressApproval::GovernedPath => {
let refused = |reason: &str| VisionError::EgressRefused {
host: hosts.join(", "),
reason: reason.to_string(),
};
if governed != Some(EgressAction::Ask) {
return Err(refused(
"the egress rule asks a person first and this call was not held for \
approval; install VisionToolset::egress_policy on the run",
));
}
let Some(staged) = staged.filter(|staged| !staged.evidence.is_empty()) else {
return Err(refused(
"the call was held without the image it would send; install \
VisionToolset::evidence_callback on the agent and give the egress gate \
a media store",
));
};
Ok(staged.digests)
}
}
}
fn cx_for(ctx: &dyn ToolContext) -> VisionCx {
let scope =
ModelCallScope::current().or_else(|| ModelCallScope::for_tool(ctx)).unwrap_or_default();
let acting = ctx.acting_context();
let mut cx = VisionCx::new()
.with_scope(scope)
.with_media_scope(MediaScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id()))
.with_acting(acting.clone());
if let Some(trail) = ctx.run_config().and_then(|config| config.audit.clone()) {
cx = cx.with_audit(trail, AuditActor::new(&acting, ctx.invocation_id()));
}
cx
}
}
fn video_frames(args: &Value) -> Result<Vec<String>> {
let frames = args.get("frames").and_then(Value::as_array).ok_or_else(|| {
VisionError::InvalidInput("`frames` is required: a list of images".into())
})?;
if frames.is_empty() || frames.len() > tools::MAX_VIDEO_FRAMES {
return Err(VisionError::InvalidInput(format!(
"`frames` holds 1 to {} images, not {}; sample fewer frames",
tools::MAX_VIDEO_FRAMES,
frames.len()
)));
}
frames
.iter()
.map(|frame| {
frame.as_str().map(str::to_string).ok_or_else(|| {
VisionError::InvalidInput(format!(
"each frame is a `sha256:` digest or an artifact name, not {frame}"
))
})
})
.collect()
}
fn call_key(kind: VisionToolKind, args: &Value) -> String {
format!("{}\u{1f}{}", kind.name(), canonical_json(args))
}
fn governed_key(call_id: &str, kind: VisionToolKind, args: &Value) -> String {
format!("{call_id}\u{1e}{}", call_key(kind, args))
}
fn canonical_json(value: &Value) -> String {
fn sorted(value: &Value) -> Value {
match value {
Value::Object(map) => {
let mut entries: Vec<(&String, &Value)> = map.iter().collect();
entries.sort_by(|a, b| a.0.cmp(b.0));
Value::Object(entries.into_iter().map(|(k, v)| (k.clone(), sorted(v))).collect())
}
Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
other => other.clone(),
}
}
sorted(value).to_string()
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|e| e.into_inner())
}