1use 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#[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#[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 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 pub fn current() -> Self {
71 Self { scope: ModelCallScope::current().unwrap_or_default(), ..Self::new() }
72 }
73
74 pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
76 self.scope = scope;
77 self
78 }
79
80 pub fn with_governance(mut self, control: GovernanceControl) -> Self {
83 self.scope = self.scope.with_governance(control);
84 self
85 }
86
87 pub fn with_cancellation(mut self, token: CancellationToken) -> Self {
89 self.cancel = token;
90 self
91 }
92
93 pub fn with_acting(mut self, acting: ActingContext) -> Self {
95 self.acting = Some(acting);
96 self
97 }
98
99 pub fn with_media_scope(mut self, scope: MediaScope) -> Self {
101 self.media = Some(scope);
102 self
103 }
104
105 pub fn with_audit(mut self, trail: AuditTrail, actor: AuditActor) -> Self {
109 self.audit = Some(VisionAudit { trail, actor });
110 self
111 }
112
113 pub fn with_span(mut self, span: tracing::Span) -> Self {
115 self.span = span;
116 self
117 }
118
119 pub fn cancellation(&self) -> &CancellationToken {
121 &self.cancel
122 }
123
124 pub fn scope(&self) -> &ModelCallScope {
126 &self.scope
127 }
128
129 pub fn acting(&self) -> Option<&ActingContext> {
131 self.acting.as_ref()
132 }
133
134 pub fn media_scope(&self) -> Option<&MediaScope> {
136 self.media.as_ref()
137 }
138
139 pub fn audit_trail(&self) -> Option<&AuditTrail> {
141 self.audit.as_ref().map(|audit| &audit.trail)
142 }
143
144 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 pub fn span(&self) -> &tracing::Span {
158 &self.span
159 }
160
161 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}