Skip to main content

adk_surface/voice/
source.rs

1//! Decisions on calls a voice conversation holds go back to that conversation (spec 3.3 §5.6,
2//! §7.3).
3//!
4//! A call the realtime session holds is in the session store like any other held call, so the
5//! source's own resume — a turn of the harness on its text runner — would run it there too.
6//! [`VoiceSource`] sends the decision of a call held by a live voice conversation to that
7//! conversation instead, which resumes it on its realtime session, once.
8
9use std::collections::HashMap;
10use std::sync::{Arc, Mutex};
11use std::time::Duration;
12
13use adk_core::{ApprovalDecision, ApprovalRequest, Event};
14use adk_harness::HarnessMode;
15use adk_kernel::QuietHours;
16use adk_kernel::proc::LedgerEntry;
17use async_trait::async_trait;
18use chrono::{DateTime, Utc};
19use tokio::sync::Notify;
20
21use crate::error::Result;
22use crate::origin::Caller;
23use crate::source::{AgentState, AlwaysAllowOffer, RuleCommit, Source, SpendToday};
24
25/// The voice conversations open in this process, by user and session: where a decision on
26/// one of their held calls is sent (spec 3.3 §5.6).
27///
28/// Cheap to clone; every clone sees the same conversations.
29#[derive(Clone, Default)]
30pub struct LiveVoice {
31    sessions: Arc<Mutex<Conversations>>,
32}
33
34/// The signal that wakes each live conversation, by user and session.
35type Conversations = HashMap<(String, String), Arc<Notify>>;
36
37impl std::fmt::Debug for LiveVoice {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        let open = self.sessions.lock().unwrap_or_else(|e| e.into_inner()).len();
40        f.debug_struct("LiveVoice").field("open", &open).finish()
41    }
42}
43
44impl LiveVoice {
45    /// No conversation open.
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// Whether `user`'s session `session` is a live voice conversation.
51    pub fn is_live(&self, user: &str, session: &str) -> bool {
52        self.sessions
53            .lock()
54            .unwrap_or_else(|e| e.into_inner())
55            .contains_key(&(user.to_string(), session.to_string()))
56    }
57
58    /// Registers a live conversation; it is woken through the returned signal until the
59    /// guard drops.
60    pub(crate) fn register(&self, user: &str, session: &str) -> (Registration, Arc<Notify>) {
61        let wake = Arc::new(Notify::new());
62        let key = (user.to_string(), session.to_string());
63        self.sessions.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone(), wake.clone());
64        (Registration { live: self.clone(), key, wake: wake.clone() }, wake)
65    }
66
67    /// Wakes the live conversation of `user`'s session `session`; `false` when there is none.
68    fn wake(&self, user: &str, session: &str) -> bool {
69        let wake = self
70            .sessions
71            .lock()
72            .unwrap_or_else(|e| e.into_inner())
73            .get(&(user.to_string(), session.to_string()))
74            .cloned();
75        match wake {
76            Some(wake) => {
77                wake.notify_one();
78                true
79            }
80            None => false,
81        }
82    }
83}
84
85/// A live conversation's place in [`LiveVoice`], removed when it drops.
86pub(crate) struct Registration {
87    live: LiveVoice,
88    key: (String, String),
89    wake: Arc<Notify>,
90}
91
92impl Drop for Registration {
93    fn drop(&mut self) {
94        let mut sessions = self.live.sessions.lock().unwrap_or_else(|e| e.into_inner());
95        // A later conversation on the same session registered its own signal: keep it.
96        if sessions.get(&self.key).is_some_and(|wake| Arc::ptr_eq(wake, &self.wake)) {
97            sessions.remove(&self.key);
98        }
99    }
100}
101
102/// The engine's source with voice (spec 3.3 §5.6): it delegates everything to the source it
103/// wraps, except that a decision resolving a call held by a live voice conversation goes to
104/// that conversation, which resumes the call on its realtime session. The wrapped source
105/// never resumes it on the text runner, so the call runs once.
106///
107/// A decision made outside the engine — in Telegram through the kernel, or with
108/// `adk-rust approvals` — never reaches [`Source::resolved`]; a conversation with held calls
109/// also looks for those on every change the source signals.
110///
111/// # Example
112///
113/// ```rust
114/// use std::sync::Arc;
115/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
116/// use adk_session::InMemorySessionService;
117/// use adk_surface::voice::VoiceSource;
118/// use adk_surface::{LocalSource, SurfaceEngine};
119///
120/// let local = LocalSource::builder("adk-rust")
121///     .sessions(Arc::new(InMemorySessionService::new()))
122///     .approvals(Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))))
123///     .build()
124///     .unwrap();
125/// let source = VoiceSource::new(Arc::new(local));
126/// let live = source.live();
127/// let engine = SurfaceEngine::builder(Arc::new(source)).build();
128/// # let _ = (engine, live);
129/// ```
130pub struct VoiceSource {
131    inner: Arc<dyn Source>,
132    live: LiveVoice,
133}
134
135impl std::fmt::Debug for VoiceSource {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        f.debug_struct("VoiceSource")
138            .field("app", &self.inner.app_name())
139            .field("live", &self.live)
140            .finish()
141    }
142}
143
144impl VoiceSource {
145    /// Wraps `inner`.
146    pub fn new(inner: Arc<dyn Source>) -> Self {
147        Self { inner, live: LiveVoice::new() }
148    }
149
150    /// The live conversations this source routes decisions to; give it to the
151    /// [`VoiceHub`](super::VoiceHub).
152    pub fn live(&self) -> LiveVoice {
153        self.live.clone()
154    }
155
156    /// The source it wraps.
157    pub fn inner(&self) -> &Arc<dyn Source> {
158        &self.inner
159    }
160}
161
162#[async_trait]
163impl Source for VoiceSource {
164    fn app_name(&self) -> &str {
165        self.inner.app_name()
166    }
167
168    async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>> {
169        self.inner.transcript(user, session).await
170    }
171
172    async fn changed(&self, max: Duration) {
173        self.inner.changed(max).await;
174    }
175
176    async fn requests(
177        &self,
178        caller: &Caller,
179        session: Option<&str>,
180        open_only: bool,
181    ) -> Result<Vec<ApprovalRequest>> {
182        self.inner.requests(caller, session, open_only).await
183    }
184
185    async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
186        self.inner.request(id).await
187    }
188
189    async fn decide(
190        &self,
191        id: &str,
192        expected_version: u64,
193        decision: ApprovalDecision,
194    ) -> Result<ApprovalRequest> {
195        self.inner.decide(id, expected_version, decision).await
196    }
197
198    async fn resolved(&self, request: &ApprovalRequest) -> Result<()> {
199        if self.live.wake(&request.scope.user_id, &request.scope.session_id) {
200            return Ok(());
201        }
202        self.inner.resolved(request).await
203    }
204
205    async fn resolved_by(&self, caller: &Caller, request: &ApprovalRequest) -> Result<()> {
206        if self.live.wake(&request.scope.user_id, &request.scope.session_id) {
207            return Ok(());
208        }
209        self.inner.resolved_by(caller, request).await
210    }
211
212    async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
213        self.inner.always_allow_offer(request).await
214    }
215
216    async fn prepare_always_allow(
217        &self,
218        caller: &Caller,
219        request: &ApprovalRequest,
220    ) -> Result<Box<dyn RuleCommit>> {
221        self.inner.prepare_always_allow(caller, request).await
222    }
223
224    async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
225        self.inner.agents(user).await
226    }
227
228    fn primary_agent(&self) -> Option<String> {
229        self.inner.primary_agent()
230    }
231
232    fn rates_high(&self, request: &ApprovalRequest) -> bool {
233        self.inner.rates_high(request)
234    }
235
236    fn moves_money(&self, request: &ApprovalRequest) -> bool {
237        self.inner.moves_money(request)
238    }
239
240    async fn busy(&self, user: &str, session: &str) -> Result<bool> {
241        self.inner.busy(user, session).await
242    }
243
244    async fn turn_failures(
245        &self,
246        user: &str,
247        session: &str,
248    ) -> Result<Vec<crate::source::TurnFailure>> {
249        self.inner.turn_failures(user, session).await
250    }
251
252    async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
253        self.inner.waiting_on_decision(user, session).await
254    }
255
256    async fn start_turn(&self, caller: &Caller, session: &str, text: &str) -> Result<()> {
257        self.inner.start_turn(caller, session, text).await
258    }
259
260    async fn request_call(
261        &self,
262        caller: &Caller,
263        session: &str,
264        text: &str,
265        call: adk_core::RequestedCall,
266    ) -> Result<()> {
267        self.inner.request_call(caller, session, text, call).await
268    }
269
270    async fn stop_all(&self, caller: &Caller, reason: &str) -> Result<()> {
271        self.inner.stop_all(caller, reason).await
272    }
273
274    async fn resume_all(&self, caller: &Caller) -> Result<()> {
275        self.inner.resume_all(caller).await
276    }
277
278    async fn stopped(&self) -> Result<bool> {
279        self.inner.stopped().await
280    }
281
282    async fn mode(&self, user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
283        self.inner.mode(user, session).await
284    }
285
286    async fn set_mode(&self, caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
287        self.inner.set_mode(caller, session, mode).await
288    }
289
290    async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
291        self.inner.spend(user).await
292    }
293
294    fn quiet_hours(&self) -> Option<QuietHours> {
295        self.inner.quiet_hours()
296    }
297
298    fn serves_kernel_routes(&self) -> bool {
299        self.inner.serves_kernel_routes()
300    }
301
302    fn keeps_ledger(&self) -> bool {
303        self.inner.keeps_ledger()
304    }
305
306    async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<LedgerEntry>> {
307        self.inner.ledger(since).await
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use adk_core::{ApprovalPolicy, ApprovalScope, ApproverSelector, ToolConfirmationRequest};
314
315    use super::*;
316    use crate::error::SurfaceError;
317    use crate::origin::{Origin, SurfaceKind};
318
319    /// A source that records which sessions it was asked to resume.
320    #[derive(Default)]
321    struct Recording {
322        resumed: Mutex<Vec<String>>,
323    }
324
325    #[async_trait]
326    impl Source for Recording {
327        fn app_name(&self) -> &str {
328            "home"
329        }
330
331        async fn transcript(&self, _user: &str, _session: &str) -> Result<Option<Vec<Event>>> {
332            Ok(None)
333        }
334
335        async fn requests(
336            &self,
337            _caller: &Caller,
338            _session: Option<&str>,
339            _open_only: bool,
340        ) -> Result<Vec<ApprovalRequest>> {
341            Ok(Vec::new())
342        }
343
344        async fn request(&self, _id: &str) -> Result<Option<ApprovalRequest>> {
345            Ok(None)
346        }
347
348        async fn decide(
349            &self,
350            _id: &str,
351            _expected_version: u64,
352            _decision: ApprovalDecision,
353        ) -> Result<ApprovalRequest> {
354            Err(SurfaceError::unsupported("decide"))
355        }
356
357        async fn resolved(&self, request: &ApprovalRequest) -> Result<()> {
358            self.resumed.lock().unwrap().push(request.scope.session_id.clone());
359            Ok(())
360        }
361
362        /// Rates `pay_invoice` as a mounted driver's `financial` tool.
363        fn rates_high(&self, request: &ApprovalRequest) -> bool {
364            request.tool_name == "pay_invoice"
365        }
366
367        fn moves_money(&self, request: &ApprovalRequest) -> bool {
368            request.tool_name == "pay_invoice"
369        }
370    }
371
372    fn decided(session: &str) -> ApprovalRequest {
373        let call = ToolConfirmationRequest {
374            tool_name: "bash".into(),
375            function_call_id: Some("call-1".into()),
376            args: serde_json::json!({ "command": "ls" }),
377            origin: None,
378            acting: None,
379            evidence: Vec::new(),
380        };
381        ApprovalRequest::new(
382            format!("apr-{session}"),
383            ApprovalScope::new("home", "ana", session),
384            &call,
385            ApprovalPolicy::new([ApproverSelector::group("owner")]),
386        )
387    }
388
389    /// The wrapped source's rating of a call reaches the engine through the voice source, so a
390    /// driver's `financial` call stays high risk and money with voice on (spec 3.3 §7.2, spec
391    /// 3.2 K-I9).
392    #[test]
393    fn the_wrapped_source_rates_each_call() {
394        let source = VoiceSource::new(Arc::new(Recording::default()));
395        let mut pay = decided("typed");
396        pay.tool_name = "pay_invoice".into();
397        assert!(source.rates_high(&pay) && source.moves_money(&pay));
398        let list = decided("typed");
399        assert!(!source.rates_high(&list) && !source.moves_money(&list));
400    }
401
402    /// A decision on a live voice conversation's call wakes that conversation, never the
403    /// wrapped source; any other session is the wrapped source's to resume.
404    #[tokio::test]
405    async fn a_live_conversation_is_woken_and_every_other_session_delegated() {
406        let recording = Arc::new(Recording::default());
407        let source = VoiceSource::new(recording.clone());
408        let (registration, wake) = source.live().register("ana", "voice-1");
409        let ana = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
410
411        source.resolved_by(&ana, &decided("voice-1")).await.unwrap();
412        source.resolved(&decided("voice-1")).await.unwrap();
413        assert!(recording.resumed.lock().unwrap().is_empty());
414        tokio::time::timeout(Duration::from_secs(1), wake.notified()).await.unwrap();
415
416        source.resolved_by(&ana, &decided("typed")).await.unwrap();
417        assert_eq!(*recording.resumed.lock().unwrap(), ["typed"]);
418
419        // Once the conversation ends, its session is the wrapped source's again.
420        drop(registration);
421        assert!(!source.live().is_live("ana", "voice-1"));
422        source.resolved(&decided("voice-1")).await.unwrap();
423        assert_eq!(*recording.resumed.lock().unwrap(), ["typed", "voice-1"]);
424    }
425}