Skip to main content

adk_vision/
cx.rs

1//! [`VisionCx`]: what every vision call carries.
2
3use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditTrail};
4use adk_core::{ActingContext, GovernanceControl, ModelCallScope};
5use tokio_util::sync::CancellationToken;
6
7use crate::error::{Result, VisionError};
8use crate::media::MediaScope;
9
10/// What every vision call carries: cancellation, the metering scope (budget, spend ledger
11/// and kill switches), the acting agent, the media scope new images are stored under, the
12/// audit trail `vision.*` records go to, and the tracing span.
13///
14/// # Example
15///
16/// ```
17/// use adk_core::GovernanceControl;
18/// use adk_vision::VisionCx;
19///
20/// let control = GovernanceControl::new();
21/// let cx = VisionCx::new().with_governance(control.clone());
22/// assert!(cx.check().is_ok());
23/// control.freeze("incident 42");
24/// assert!(cx.check().is_err());
25/// ```
26#[derive(Clone, Debug)]
27pub struct VisionCx {
28    cancel: CancellationToken,
29    scope: ModelCallScope,
30    acting: Option<ActingContext>,
31    media: Option<MediaScope>,
32    audit: Option<VisionAudit>,
33    span: tracing::Span,
34}
35
36/// The audit trail of the run a vision call belongs to, and who acts in it.
37#[derive(Clone)]
38struct VisionAudit {
39    trail: AuditTrail,
40    actor: AuditActor,
41}
42
43impl std::fmt::Debug for VisionAudit {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("VisionAudit").field("actor", &self.actor).finish_non_exhaustive()
46    }
47}
48
49impl Default for VisionCx {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55impl VisionCx {
56    /// A context that meters nothing and is never cancelled.
57    pub fn new() -> Self {
58        Self {
59            cancel: CancellationToken::new(),
60            scope: ModelCallScope::new(),
61            acting: None,
62            media: None,
63            audit: None,
64            span: tracing::Span::current(),
65        }
66    }
67
68    /// A context under the metering scope made current by an enclosing
69    /// [`ModelCallScope::within`], such as the one agents set around every tool call.
70    pub fn current() -> Self {
71        Self { scope: ModelCallScope::current().unwrap_or_default(), ..Self::new() }
72    }
73
74    /// Meters calls under `scope`: its budget, spend ledger and kill switches.
75    pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
76        self.scope = scope;
77        self
78    }
79
80    /// Adds a kill switch: while it is frozen, every call and every release is refused
81    /// (V-I17).
82    pub fn with_governance(mut self, control: GovernanceControl) -> Self {
83        self.scope = self.scope.with_governance(control);
84        self
85    }
86
87    /// Cancels calls when `token` fires.
88    pub fn with_cancellation(mut self, token: CancellationToken) -> Self {
89        self.cancel = token;
90        self
91    }
92
93    /// Names the acting agent.
94    pub fn with_acting(mut self, acting: ActingContext) -> Self {
95        self.acting = Some(acting);
96        self
97    }
98
99    /// Stores new images (edits, egress copies) under `scope`.
100    pub fn with_media_scope(mut self, scope: MediaScope) -> Self {
101        self.media = Some(scope);
102        self
103    }
104
105    /// Writes the call's `vision.*` audit records — egress releases and refusals, perception
106    /// calls and edits (spec 3.7 §9.3) — to `trail`, with `actor` as the acting agent. The
107    /// trail is the run's (`RunConfig::audit`), signed when the run's recorder signs.
108    pub fn with_audit(mut self, trail: AuditTrail, actor: AuditActor) -> Self {
109        self.audit = Some(VisionAudit { trail, actor });
110        self
111    }
112
113    /// Records the call's spans under `span`.
114    pub fn with_span(mut self, span: tracing::Span) -> Self {
115        self.span = span;
116        self
117    }
118
119    /// The cancellation token.
120    pub fn cancellation(&self) -> &CancellationToken {
121        &self.cancel
122    }
123
124    /// The metering scope.
125    pub fn scope(&self) -> &ModelCallScope {
126        &self.scope
127    }
128
129    /// The acting agent, when one is named.
130    pub fn acting(&self) -> Option<&ActingContext> {
131        self.acting.as_ref()
132    }
133
134    /// The media scope, when one is set.
135    pub fn media_scope(&self) -> Option<&MediaScope> {
136        self.media.as_ref()
137    }
138
139    /// The audit trail `vision.*` records go to, when one is set.
140    pub fn audit_trail(&self) -> Option<&AuditTrail> {
141        self.audit.as_ref().map(|audit| &audit.trail)
142    }
143
144    /// Writes `draft` to the audit trail as the acting agent; does nothing without a trail.
145    ///
146    /// # Errors
147    ///
148    /// The trail's error, when its failure mode fails closed.
149    pub(crate) async fn audit(&self, draft: AuditRecordDraft) -> Result<()> {
150        if let Some(audit) = &self.audit {
151            audit.trail.record(draft.actor(audit.actor.clone())).await?;
152        }
153        Ok(())
154    }
155
156    /// The tracing span.
157    pub fn span(&self) -> &tracing::Span {
158        &self.span
159    }
160
161    /// Refuses when the call is cancelled or a kill switch is frozen.
162    ///
163    /// # Errors
164    ///
165    /// [`VisionError::Cancelled`], or the frozen control's `governance.frozen` error.
166    pub fn check(&self) -> Result<()> {
167        if self.cancel.is_cancelled() {
168            return Err(VisionError::Cancelled);
169        }
170        self.scope.check_governance()?;
171        Ok(())
172    }
173}