Skip to main content

adk_vision/stream/
sources.rs

1//! [`FrameSources`]: the named frame sources an agent can watch (spec 3.7 §7.8, §7.10).
2
3use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
7use chrono::{DateTime, Utc};
8use futures::FutureExt;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use tokio::task::JoinHandle;
12use tokio_util::sync::CancellationToken;
13
14use super::FrameSource;
15use super::governor::FrameBudget;
16use super::pipeline::{ObservationSink, StopCause, StreamPipeline, StreamSummary};
17use super::privacy::{NoRedaction, PrivacyHook};
18use super::retention::FrameKeeper;
19use super::watching::StreamWatch;
20use crate::audit::VISION_AUDIT_KIND;
21use crate::cx::VisionCx;
22use crate::error::{Result, VisionError};
23use crate::media::FrameSourceId;
24use crate::runtime::VisionRuntime;
25use crate::traits::{DetectQuery, Sampling, Tracker};
26use crate::watch::{
27    VISION_WATCH_STOPPED, WatchCondition, WatchEvaluator, WatchSink, watch_registered_draft,
28};
29
30/// Makes a fresh tracker for each run of a source, so track identifiers reset with every
31/// source session (V-I8).
32pub type TrackerFactory = Arc<dyn Fn() -> Box<dyn Tracker> + Send + Sync>;
33
34/// One source an operator registers for watching: the frame source and every stage its
35/// stream runs, from the privacy hook to the wake sink.
36///
37/// An agent names the source; it never supplies one. The camera URL and its credentials stay
38/// with the operator, so the source's [`FrameSourceId`] is all a tool call, a record or a
39/// wake carries.
40///
41/// | Part | Required | What it is |
42/// |------|----------|------------|
43/// | Source | yes | The [`FrameSource`]: a camera, a file, a screen, a browser, the web home's camera |
44/// | Privacy | no | The [`PrivacyHook`] every frame passes first ([`with_privacy`](Self::with_privacy)); none by default |
45/// | Keeper | yes | The [`FrameKeeper`] that stores the frame of each event, in the scope the woken agent loads it from |
46/// | Wakes | yes | The [`WatchSink`] events go to, such as the kernel's `VisionWakeSource` |
47/// | Detector | for a watch | The runtime and query each frame is detected with |
48/// | Tracker | no | A [`TrackerFactory`]; without one, regions have no tracks and no condition fires |
49/// | Sampling, budget | no | As [`StreamPipelineBuilder`](super::StreamPipelineBuilder) takes them |
50/// | Observer | no | A sink that sees every observation after the watch, such as the live camera surface |
51///
52/// # Example
53///
54/// ```ignore
55/// let spec = SourceSpec::new(camera, keeper, wake_source)
56///     .describe("Line 1 conveyor, top camera")
57///     .detector(runtime, DetectQuery::Classes(vec!["clock".into()]))
58///     .tracker(Arc::new(|| Box::new(GreedyIouTracker::new(0.3, 4)) as Box<dyn Tracker>))
59///     .sampling(Sampling::at(2.0));
60/// sources.register(spec)?;
61/// ```
62#[must_use]
63pub struct SourceSpec {
64    source: Arc<dyn FrameSource>,
65    privacy: Arc<dyn PrivacyHook>,
66    keeper: Arc<FrameKeeper>,
67    wakes: Arc<dyn WatchSink>,
68    description: Option<String>,
69    detection: Option<(Arc<VisionRuntime>, DetectQuery)>,
70    tracker: Option<TrackerFactory>,
71    sampling: Option<Sampling>,
72    budget: Option<FrameBudget>,
73    observer: Option<Arc<dyn ObservationSink>>,
74}
75
76impl std::fmt::Debug for SourceSpec {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.debug_struct("SourceSpec")
79            .field("source", self.source.id())
80            .field("description", &self.description)
81            .field("sampling", &self.sampling)
82            .field("budget", &self.budget)
83            .finish_non_exhaustive()
84    }
85}
86
87impl SourceSpec {
88    /// A source whose events' frames `keeper` stores and whose events go to `wakes`. Its
89    /// frames are not redacted unless a hook is given with [`with_privacy`](Self::with_privacy).
90    pub fn new(
91        source: Arc<dyn FrameSource>,
92        keeper: Arc<FrameKeeper>,
93        wakes: Arc<dyn WatchSink>,
94    ) -> Self {
95        Self {
96            source,
97            privacy: Arc::new(NoRedaction),
98            keeper,
99            wakes,
100            description: None,
101            detection: None,
102            tracker: None,
103            sampling: None,
104            budget: None,
105            observer: None,
106        }
107    }
108
109    /// Passes every frame through `hook` before any other stage sees it, such as
110    /// `RedactorPrivacy::blur_faces`; a frame the hook fails on is dropped.
111    pub fn with_privacy(mut self, hook: Arc<dyn PrivacyHook>) -> Self {
112        self.privacy = hook;
113        self
114    }
115
116    /// Says what the source shows, for the agent choosing one.
117    pub fn describe(mut self, description: impl Into<String>) -> Self {
118        self.description = Some(description.into());
119        self
120    }
121
122    /// Detects `query` on every frame through `runtime`, metered in frames. A watch
123    /// condition may name only the labels `query` lists.
124    pub fn detector(mut self, runtime: Arc<VisionRuntime>, query: DetectQuery) -> Self {
125        self.detection = Some((runtime, query));
126        self
127    }
128
129    /// Tracks detections with a fresh tracker from `factory` for each run.
130    pub fn tracker(mut self, factory: TrackerFactory) -> Self {
131        self.tracker = Some(factory);
132        self
133    }
134
135    /// Samples the source at `sampling`.
136    pub fn sampling(mut self, sampling: Sampling) -> Self {
137        self.sampling = Some(sampling);
138        self
139    }
140
141    /// Holds the stream to `budget`.
142    pub fn budget(mut self, budget: FrameBudget) -> Self {
143        self.budget = Some(budget);
144        self
145    }
146
147    /// Hands every observation and source event to `observer` after the watch.
148    pub fn observer(mut self, observer: Arc<dyn ObservationSink>) -> Self {
149        self.observer = Some(observer);
150        self
151    }
152
153    fn labels(&self) -> Vec<String> {
154        match &self.detection {
155            Some((_, DetectQuery::Classes(labels) | DetectQuery::Concepts(labels))) => {
156                labels.clone()
157            }
158            None => Vec::new(),
159        }
160    }
161
162    /// Refuses a condition this source can never fire.
163    fn check(&self, condition: &WatchCondition) -> Result<()> {
164        condition.validate()?;
165        let id = &self.source.id().0;
166        if self.detection.is_none() {
167            return Err(VisionError::InvalidInput(format!(
168                "source `{id}` has no detector, so no watch condition can fire on it"
169            )));
170        }
171        let labels = self.labels();
172        let unknown: Vec<&String> = condition
173            .labels
174            .iter()
175            .filter(|wanted| !labels.iter().any(|label| label.eq_ignore_ascii_case(wanted)))
176            .collect();
177        if !unknown.is_empty() {
178            return Err(VisionError::InvalidInput(format!(
179                "source `{id}` detects {labels:?}; the watch condition `{}` names {unknown:?}, \
180                 which it never reports",
181                condition.name
182            )));
183        }
184        Ok(())
185    }
186
187    fn pipeline(&self, watch: Arc<StreamWatch>) -> Result<StreamPipeline> {
188        let mut builder =
189            StreamPipeline::builder(self.source.clone()).with_privacy(self.privacy.clone());
190        if let Some(sampling) = self.sampling {
191            builder = builder.sampling(sampling);
192        }
193        if let Some((runtime, query)) = &self.detection {
194            builder = builder.detector(runtime.clone(), query.clone());
195        }
196        if let Some(factory) = &self.tracker {
197            builder = builder.tracker(factory());
198        }
199        if let Some(budget) = &self.budget {
200            builder = builder.budget(budget.clone());
201        }
202        builder.sink(watch).build()
203    }
204}
205
206/// How a watch request changed a source.
207#[non_exhaustive]
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(rename_all = "camelCase")]
210pub enum WatchChange {
211    /// The condition was registered.
212    Registered,
213    /// The same condition was already registered: nothing changed.
214    Unchanged,
215    /// The condition was removed.
216    Removed,
217    /// No condition of that name was registered: nothing changed.
218    NotWatched,
219}
220
221/// How a source's last stream ended.
222#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct StreamEnd {
225    /// Why it stopped.
226    pub cause: StopCause,
227    /// What it did; empty when it failed before it summarised.
228    pub summary: StreamSummary,
229    /// When the registry saw it end.
230    pub ended_at: DateTime<Utc>,
231}
232
233/// A registered source as an agent sees it: no URL, no credential.
234#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct SourceStatus {
237    /// The source's name.
238    pub source: FrameSourceId,
239    /// What it shows, as the operator described it.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub description: Option<String>,
242    /// The labels its detector reports, which a condition may name.
243    pub labels: Vec<String>,
244    /// Whether its stream is running.
245    pub streaming: bool,
246    /// The registered watch conditions.
247    pub conditions: Vec<WatchCondition>,
248    /// Events delivered by the running stream.
249    pub fired: u64,
250    /// How the last stream ended, when one has.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub last_end: Option<StreamEnd>,
253}
254
255/// The answer to a watch request: what changed, and the source after it.
256#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct WatchOutcome {
259    /// What changed.
260    pub change: WatchChange,
261    /// The source now.
262    pub status: SourceStatus,
263}
264
265struct Running {
266    watch: Arc<StreamWatch>,
267    cancel: CancellationToken,
268    task: JoinHandle<Result<StreamSummary>>,
269}
270
271struct Entry {
272    spec: Arc<SourceSpec>,
273    conditions: Vec<WatchCondition>,
274    running: Option<Running>,
275    last_end: Option<StreamEnd>,
276}
277
278impl Entry {
279    /// Collects a stream that ended on its own.
280    fn reap(&mut self) {
281        let finished = self.running.as_ref().is_some_and(|running| running.task.is_finished());
282        if !finished {
283            return;
284        }
285        if let Some(running) = self.running.take() {
286            let outcome = running.task.now_or_never();
287            self.last_end = Some(end_of(outcome, false));
288        }
289    }
290
291    fn status(&self) -> SourceStatus {
292        SourceStatus {
293            source: self.spec.source.id().clone(),
294            description: self.spec.description.clone(),
295            labels: self.spec.labels(),
296            streaming: self.running.is_some(),
297            conditions: self.conditions.clone(),
298            fired: self.running.as_ref().map_or(0, |running| running.watch.fired()),
299            last_end: self.last_end.clone(),
300        }
301    }
302}
303
304type Joined = std::result::Result<Result<StreamSummary>, tokio::task::JoinError>;
305
306fn end_of(outcome: Option<Joined>, cancelled: bool) -> StreamEnd {
307    let (cause, summary) = match outcome {
308        Some(Ok(Ok(summary))) if cancelled => (StopCause::Cancelled, summary),
309        Some(Ok(Ok(summary))) => (StopCause::Ended, summary),
310        Some(Ok(Err(err))) => (
311            StopCause::Failed { code: err.code().to_string(), message: err.to_string() },
312            StreamSummary::default(),
313        ),
314        Some(Err(err)) => (
315            StopCause::Failed { code: "vision.stream.panicked".into(), message: err.to_string() },
316            StreamSummary::default(),
317        ),
318        None => (StopCause::Cancelled, StreamSummary::default()),
319    };
320    StreamEnd { cause, summary, ended_at: Utc::now() }
321}
322
323/// The frame sources an operator registered, by name, and the watches running on them
324/// (spec 3.7 §7.8, §7.10): the registry behind the `vision_watch` tool.
325///
326/// A source streams only while a watch condition is registered on it. The first condition
327/// starts its [`StreamPipeline`] with a [`StreamWatch`] as the sink; later ones join the
328/// running watch; removing the last one stops the stream. Each stream runs under the
329/// registry's own [`VisionCx`] — its audit trail, metering scope and kill switch — with a
330/// cancellation token of its own, so it outlives the tool call that started it and a freeze
331/// pauses it at its next frame (V-I17). A stream that ends on its own, such as a file's last
332/// frame, keeps its conditions registered; the next registration starts it again.
333///
334/// | Record | Written to | When |
335/// |--------|------------|------|
336/// | `vision.watch.registered` | the caller's trail, else the registry's | a condition is registered |
337/// | `vision.watch.stopped` | the caller's trail, else the registry's | a condition is removed |
338/// | `vision.source.started`, `.stopped`, `.paused`, `.resumed`, `vision.governor.step` | the registry's trail | the stream's life |
339/// | `vision.evidence.kept`, `vision.watch.fired` | the registry's trail | an event's frame is kept and delivered |
340///
341/// # Example
342///
343/// ```
344/// use adk_vision::VisionCx;
345/// use adk_vision::stream::FrameSources;
346///
347/// let sources = FrameSources::new(VisionCx::new());
348/// assert!(sources.statuses().is_empty());
349/// ```
350#[derive(Clone)]
351pub struct FrameSources {
352    inner: Arc<Inner>,
353}
354
355struct Inner {
356    cx: VisionCx,
357    entries: Mutex<BTreeMap<FrameSourceId, Entry>>,
358}
359
360impl std::fmt::Debug for FrameSources {
361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362        f.debug_struct("FrameSources").field("sources", &self.names()).finish_non_exhaustive()
363    }
364}
365
366impl FrameSources {
367    /// A registry whose streams run under `cx`: its audit trail, metering scope and kill
368    /// switch. Cancelling `cx` stops every stream.
369    pub fn new(cx: VisionCx) -> Self {
370        Self { inner: Arc::new(Inner { cx, entries: Mutex::new(BTreeMap::new()) }) }
371    }
372
373    fn entries(&self) -> MutexGuard<'_, BTreeMap<FrameSourceId, Entry>> {
374        self.inner.entries.lock().unwrap_or_else(PoisonError::into_inner)
375    }
376
377    /// Registers a source under its [`FrameSource::id`].
378    ///
379    /// # Errors
380    ///
381    /// [`VisionError::InvalidInput`] when a source of that name is already registered.
382    pub fn register(&self, spec: SourceSpec) -> Result<()> {
383        let id = spec.source.id().clone();
384        let mut entries = self.entries();
385        if entries.contains_key(&id) {
386            return Err(VisionError::InvalidInput(format!(
387                "a frame source named `{}` is already registered",
388                id.0
389            )));
390        }
391        entries.insert(
392            id,
393            Entry { spec: Arc::new(spec), conditions: Vec::new(), running: None, last_end: None },
394        );
395        Ok(())
396    }
397
398    /// The registered sources' names.
399    pub fn names(&self) -> Vec<FrameSourceId> {
400        self.entries().keys().cloned().collect()
401    }
402
403    /// Every source's status.
404    pub fn statuses(&self) -> Vec<SourceStatus> {
405        self.entries()
406            .values_mut()
407            .map(|entry| {
408                entry.reap();
409                entry.status()
410            })
411            .collect()
412    }
413
414    /// One source's status.
415    ///
416    /// # Errors
417    ///
418    /// [`VisionError::InvalidInput`] for a name no source is registered under.
419    pub fn status(&self, source: &FrameSourceId) -> Result<SourceStatus> {
420        let mut entries = self.entries();
421        let entry = entries.get_mut(source).ok_or_else(|| unknown(source))?;
422        entry.reap();
423        Ok(entry.status())
424    }
425
426    async fn audit(&self, cx: &VisionCx, draft: AuditRecordDraft) -> Result<()> {
427        if cx.audit_trail().is_some() {
428            cx.audit(draft).await
429        } else {
430            self.inner.cx.audit(draft).await
431        }
432    }
433
434    /// Registers `condition` on `source`, starting its stream if none runs. Registering the
435    /// same condition again changes nothing; a different condition under a registered name
436    /// is refused.
437    ///
438    /// # Errors
439    ///
440    /// [`VisionError::InvalidInput`] for an unknown source, an invalid condition, one naming
441    /// labels the source's detector never reports, or a name already registered with other
442    /// settings; the stream's build error; the audit trail's error when it fails closed.
443    pub async fn start_watch(
444        &self,
445        cx: &VisionCx,
446        source: &FrameSourceId,
447        condition: WatchCondition,
448    ) -> Result<WatchOutcome> {
449        cx.check()?;
450        let change = {
451            let mut entries = self.entries();
452            let entry = entries.get_mut(source).ok_or_else(|| unknown(source))?;
453            entry.reap();
454            entry.spec.check(&condition)?;
455            let change = match entry.conditions.iter().find(|c| c.name == condition.name) {
456                Some(existing) if *existing == condition => WatchChange::Unchanged,
457                Some(_) => {
458                    return Err(VisionError::InvalidInput(format!(
459                        "a watch named `{}` is already registered on `{}` with other settings; \
460                         stop it first",
461                        condition.name, source.0
462                    )));
463                }
464                None => {
465                    entry.conditions.push(condition.clone());
466                    WatchChange::Registered
467                }
468            };
469            match &entry.running {
470                Some(running) => {
471                    if change == WatchChange::Registered {
472                        running.watch.add_condition(condition.clone())?;
473                    }
474                }
475                None => {
476                    if let Err(err) = self.spawn(entry) {
477                        if change == WatchChange::Registered {
478                            entry.conditions.retain(|c| c.name != condition.name);
479                        }
480                        return Err(err);
481                    }
482                }
483            }
484            change
485        };
486        if change == WatchChange::Registered {
487            self.audit(cx, watch_registered_draft(source, &condition)).await?;
488            tracing::info!(vision.source = %source.0, vision.condition = %condition.name, "watch registered");
489        }
490        Ok(WatchOutcome { change, status: self.status(source)? })
491    }
492
493    /// Starts the entry's stream with its conditions. Called with the registry locked.
494    fn spawn(&self, entry: &mut Entry) -> Result<()> {
495        let evaluator = WatchEvaluator::new(entry.conditions.clone())?;
496        let mut watch =
497            StreamWatch::new(evaluator, entry.spec.keeper.clone(), entry.spec.wakes.clone());
498        if let Some(observer) = &entry.spec.observer {
499            watch = watch.with_observer(observer.clone());
500        }
501        let watch = Arc::new(watch);
502        let pipeline = entry.spec.pipeline(watch.clone())?;
503        let cancel = self.inner.cx.cancellation().child_token();
504        let cx = self.inner.cx.clone().with_cancellation(cancel.clone());
505        let task = tokio::spawn(async move { pipeline.run(&cx).await });
506        entry.running = Some(Running { watch, cancel, task });
507        Ok(())
508    }
509
510    /// Removes the condition named `name` from `source`; removing the last one stops the
511    /// stream and waits for it to finish.
512    ///
513    /// # Errors
514    ///
515    /// [`VisionError::InvalidInput`] for an unknown source; the audit trail's error when it
516    /// fails closed.
517    pub async fn stop_watch(
518        &self,
519        cx: &VisionCx,
520        source: &FrameSourceId,
521        name: &str,
522    ) -> Result<WatchOutcome> {
523        let (removed, stopping) = {
524            let mut entries = self.entries();
525            let entry = entries.get_mut(source).ok_or_else(|| unknown(source))?;
526            entry.reap();
527            let removed = entry
528                .conditions
529                .iter()
530                .position(|c| c.name == name)
531                .map(|index| entry.conditions.remove(index));
532            if removed.is_some()
533                && let Some(running) = &entry.running
534            {
535                running.watch.remove_condition(name);
536            }
537            let stopping = if entry.conditions.is_empty() { entry.running.take() } else { None };
538            (removed, stopping)
539        };
540        if let Some(running) = stopping {
541            running.cancel.cancel();
542            let outcome = running.task.await;
543            let end = end_of(Some(outcome), true);
544            if let Some(entry) = self.entries().get_mut(source) {
545                entry.last_end = Some(end);
546            }
547        }
548        let change = match &removed {
549            Some(condition) => {
550                self.audit(cx, watch_stopped_draft(source, condition)).await?;
551                tracing::info!(vision.source = %source.0, vision.condition = %name, "watch stopped");
552                WatchChange::Removed
553            }
554            None => WatchChange::NotWatched,
555        };
556        Ok(WatchOutcome { change, status: self.status(source)? })
557    }
558
559    /// Stops every stream and waits for each to finish; the conditions stay registered.
560    pub async fn shutdown(&self) {
561        let running: Vec<(FrameSourceId, Running)> = self
562            .entries()
563            .iter_mut()
564            .filter_map(|(id, entry)| entry.running.take().map(|running| (id.clone(), running)))
565            .collect();
566        for (id, running) in running {
567            running.cancel.cancel();
568            let end = end_of(Some(running.task.await), true);
569            if let Some(entry) = self.entries().get_mut(&id) {
570                entry.last_end = Some(end);
571            }
572        }
573    }
574}
575
576fn unknown(source: &FrameSourceId) -> VisionError {
577    VisionError::InvalidInput(format!(
578        "no frame source is registered as `{}`; list the sources with the `list` action",
579        source.0
580    ))
581}
582
583/// The `vision.watch.stopped` audit record of `condition` removed from `source`.
584pub(crate) fn watch_stopped_draft(
585    source: &FrameSourceId,
586    condition: &WatchCondition,
587) -> AuditRecordDraft {
588    AuditRecordDraft::new(
589        AuditRecordKind::Other(VISION_AUDIT_KIND.to_string()),
590        VISION_WATCH_STOPPED,
591    )
592    .outcome(AuditRecordOutcome::Succeeded)
593    .payload_ref(condition.digest().to_string())
594    .ext("source", json!(source))
595    .ext("condition", json!(condition.name))
596    .ext("conditionDigest", json!(condition.digest()))
597}