use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "web")]
use std::sync::Mutex;
use std::time::Duration;
use adk_core::{ErrorCategory, RequestContext};
use adk_harness::{Harness, VoiceConfig, VoiceSurface};
use adk_realtime::BoxedModel;
use adk_session::{CreateRequest, GetRequest};
use serde_json::{Value, json};
#[cfg(feature = "web")]
use tokio::time::Instant;
use super::VoiceError;
use super::session::{self, Conversation, VoiceLink};
use super::source::LiveVoice;
use super::visual::{FramePolicy, VisualInputs};
use super::wire::{VoiceModel, VoiceModels};
use crate::engine::{DEFAULT_POLL_INTERVAL, SurfaceEngine};
use crate::origin::{Caller, Origin, SurfaceKind};
const VOICE_SESSION_KEY: &str = "surfaceVoice";
#[cfg(feature = "web")]
pub(crate) const TICKET_LIFETIME: Duration = Duration::from_secs(30);
const NEVER_DECIDE: &str = "Decisions on waiting calls are shown on the person's screen. \
The app applies the person's own spoken words to the decision on screen: they say \
\"allow once\" or \"deny\". \"Yes\" and \"no\" decide nothing, so when a call waits, ask \
them to say \"allow once\" or \"deny\". Never approve or deny a call yourself, never say \
that a call was approved, and never repeat a call that is waiting.";
struct Offered {
info: VoiceModel,
model: BoxedModel,
frames: FramePolicy,
compress: bool,
}
#[cfg(feature = "web")]
#[derive(Debug, Clone)]
pub(crate) struct Ticket {
pub(crate) caller: Caller,
pub(crate) model: String,
pub(crate) session_id: String,
expires: Instant,
}
#[cfg(feature = "web")]
#[derive(Default)]
pub(crate) struct Tickets {
open: Mutex<HashMap<String, Ticket>>,
}
#[cfg(feature = "web")]
impl Tickets {
pub(crate) fn issue(&self, caller: &Caller, model: &str, session_id: &str) -> String {
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let now = Instant::now();
let mut open = self.open.lock().unwrap_or_else(|e| e.into_inner());
open.retain(|_, ticket| ticket.expires > now);
open.insert(
token.clone(),
Ticket {
caller: caller.clone(),
model: model.to_string(),
session_id: session_id.to_string(),
expires: now + TICKET_LIFETIME,
},
);
token
}
pub(crate) fn redeem(&self, token: &str) -> Option<Ticket> {
let ticket = self.open.lock().unwrap_or_else(|e| e.into_inner()).remove(token)?;
(ticket.expires > Instant::now()).then_some(ticket)
}
}
struct Hub {
engine: SurfaceEngine,
harness: Arc<Harness>,
live: LiveVoice,
models: Vec<Offered>,
agent: String,
instruction: Option<String>,
poll: Duration,
#[cfg(feature = "web")]
tickets: Tickets,
#[cfg(feature = "verb-ui")]
verbs: Option<crate::verbs::VerbGate>,
}
pub struct VoiceHubBuilder {
engine: SurfaceEngine,
harness: Arc<Harness>,
live: LiveVoice,
models: Vec<Offered>,
agent: Option<String>,
instruction: Option<String>,
poll: Duration,
#[cfg(feature = "verb-ui")]
verbs: Option<crate::verbs::VerbGate>,
}
impl std::fmt::Debug for VoiceHubBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VoiceHubBuilder")
.field("models", &self.models.iter().map(|m| &m.info.id).collect::<Vec<_>>())
.finish_non_exhaustive()
}
}
impl VoiceHubBuilder {
#[must_use]
pub fn model(mut self, info: VoiceModel, model: BoxedModel, frames: FramePolicy) -> Self {
self.models.push(Offered { info, model, frames, compress: false });
self
}
#[must_use]
pub fn context_window_compression(mut self, id: &str) -> Self {
for offered in self.models.iter_mut().filter(|offered| offered.info.id == id) {
offered.compress = true;
}
self
}
#[must_use]
pub fn agent_name(mut self, name: impl Into<String>) -> Self {
self.agent = Some(name.into());
self
}
#[must_use]
pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
self.instruction = Some(instruction.into());
self
}
#[must_use]
pub fn poll_interval(mut self, poll: Duration) -> Self {
self.poll = poll;
self
}
#[cfg(feature = "verb-ui")]
#[must_use]
pub fn verbs(mut self, gate: crate::verbs::VerbGate) -> Self {
self.verbs = Some(gate);
self
}
pub fn build(self) -> VoiceHub {
let agent = self
.agent
.unwrap_or_else(|| crate::project::humanize(&self.harness.agent().info().name));
VoiceHub {
inner: Arc::new(Hub {
engine: self.engine,
harness: self.harness,
live: self.live,
models: self.models,
agent,
instruction: self.instruction,
poll: self.poll,
#[cfg(feature = "web")]
tickets: Tickets::default(),
#[cfg(feature = "verb-ui")]
verbs: self.verbs,
}),
}
}
}
#[derive(Clone)]
pub struct VoiceHub {
inner: Arc<Hub>,
}
impl std::fmt::Debug for VoiceHub {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VoiceHub")
.field("agent", &self.inner.agent)
.field("models", &self.inner.models.iter().map(|m| &m.info.id).collect::<Vec<_>>())
.finish_non_exhaustive()
}
}
impl VoiceHub {
pub fn builder(
engine: SurfaceEngine,
harness: Arc<Harness>,
live: LiveVoice,
) -> VoiceHubBuilder {
VoiceHubBuilder {
engine,
harness,
live,
models: Vec::new(),
agent: None,
instruction: None,
poll: DEFAULT_POLL_INTERVAL,
#[cfg(feature = "verb-ui")]
verbs: None,
}
}
pub fn engine(&self) -> &SurfaceEngine {
&self.inner.engine
}
pub fn models(&self) -> VoiceModels {
VoiceModels {
agent: self.inner.agent.clone(),
agent_name: self
.inner
.engine
.source()
.primary_agent()
.unwrap_or_else(|| self.inner.harness.agent().info().name.clone()),
models: self.inner.models.iter().map(|offered| offered.info.clone()).collect(),
}
}
fn offered(&self, model: &str) -> Result<&Offered, VoiceError> {
self.inner
.models
.iter()
.find(|offered| offered.info.id == model)
.ok_or_else(|| VoiceError::UnknownModel(model.to_string()))
}
pub async fn session_for(
&self,
caller: &Caller,
session_id: Option<&str>,
) -> Result<String, VoiceError> {
let sessions = self.inner.harness.runner().session_service();
let app = self.inner.engine.source().app_name().to_string();
if let Some(session_id) = session_id {
let found = sessions
.get(GetRequest {
app_name: app,
user_id: caller.user_id().to_string(),
session_id: session_id.to_string(),
num_recent_events: Some(0),
after: None,
})
.await;
return match found {
Ok(session)
if session.state().get(VOICE_SESSION_KEY) == Some(Value::Bool(true)) =>
{
Ok(session_id.to_string())
}
Ok(_) => Err(VoiceError::NotYourSession(session_id.to_string())),
Err(error)
if matches!(
error.category,
ErrorCategory::NotFound | ErrorCategory::InvalidInput
) =>
{
Err(VoiceError::NotYourSession(session_id.to_string()))
}
Err(error) => Err(VoiceError::Harness(error.to_string())),
};
}
let session_id = format!("voice-{}", uuid::Uuid::new_v4().simple());
sessions
.create(CreateRequest {
app_name: app,
user_id: caller.user_id().to_string(),
session_id: Some(session_id.clone()),
state: HashMap::from([(VOICE_SESSION_KEY.to_string(), json!(true))]),
})
.await
.map_err(|error| VoiceError::Harness(error.to_string()))?;
Ok(session_id)
}
pub async fn open(
&self,
caller: &Caller,
model: &str,
session_id: Option<&str>,
) -> Result<VoiceLink, VoiceError> {
let offered = self.offered(model)?;
let session_id = self.session_for(caller, session_id).await?;
self.connect(caller, offered, session_id, false).await
}
pub async fn open_in_thread(
&self,
caller: &Caller,
model: &str,
) -> Result<VoiceLink, VoiceError> {
let offered = self.offered(model)?;
let session_id = self.session_for(caller, None).await?;
self.connect(caller, offered, session_id, true).await
}
async fn connect(
&self,
caller: &Caller,
offered: &Offered,
session_id: String,
own_only: bool,
) -> Result<VoiceLink, VoiceError> {
let hub = &self.inner;
let user = caller.user_id().to_string();
let instruction = match &hub.instruction {
Some(extra) => format!("{NEVER_DECIDE}\n\n{extra}"),
None => NEVER_DECIDE.to_string(),
};
let context = RequestContext {
user_id: user.clone(),
scopes: caller.groups.clone(),
metadata: Default::default(),
};
let app = hub.engine.source().app_name();
let tools = hub.harness.agent().voice_tools(app, &user, &session_id).await;
let mut config = VoiceConfig::new(app)
.with_instruction(instruction)
.with_request_context(context)
.with_governance(hub.harness.runner().governance().clone())
.with_tools(tools);
if offered.compress {
config = config.with_context_window_compression();
}
let surface = VoiceSurface::open(
Arc::clone(hub.harness.agent()),
Arc::clone(&offered.model),
Arc::clone(hub.harness.runner().session_service()),
user.clone(),
session_id.clone(),
config,
)
.map_err(|error| VoiceError::Harness(error.to_string()))?;
surface
.runner()
.connect()
.await
.map_err(|error| VoiceError::Provider(error.to_string()))?;
let (registration, wake) = hub.live.register(&user, &session_id);
let speaker = Caller {
surface: SurfaceKind::Voice,
origin: Origin::Voice,
presence_confirmed: false,
paired_local: false,
..caller.clone()
};
let viewer = Caller {
surface: SurfaceKind::Voice,
presence_confirmed: false,
paired_local: false,
..caller.clone()
};
Ok(session::start(Conversation {
engine: hub.engine.clone(),
surface: Arc::new(surface),
registration,
wake,
speaker,
viewer,
session_id,
input_rate: offered.info.input_rate,
output_rate: offered.info.output_rate,
visual: VisualInputs::new(offered.frames),
poll: hub.poll,
own_only,
#[cfg(feature = "verb-ui")]
verbs: hub.verbs.clone(),
}))
}
#[cfg(feature = "web")]
pub(crate) fn issue(&self, caller: &Caller, model: &str, session_id: &str) -> String {
self.inner.tickets.issue(caller, model, session_id)
}
#[cfg(feature = "web")]
pub(crate) fn redeem(&self, token: &str) -> Option<Ticket> {
self.inner.tickets.redeem(token)
}
#[cfg(feature = "web")]
pub(crate) async fn open_ticket(&self, ticket: &Ticket) -> Result<VoiceLink, VoiceError> {
let offered = self.offered(&ticket.model)?;
self.connect(&ticket.caller, offered, ticket.session_id.clone(), false).await
}
}
#[cfg(all(test, feature = "web"))]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn a_ticket_works_once_for_thirty_seconds() {
let tickets = Tickets::default();
let ana = Caller::human("ana", SurfaceKind::Voice, Origin::Pointer);
let once = tickets.issue(&ana, "gemini", "voice-1");
assert_eq!(once.len(), 64);
let ticket = tickets.redeem(&once).expect("a fresh ticket works");
assert_eq!(
(ticket.caller, ticket.model.as_str(), ticket.session_id.as_str()),
(ana.clone(), "gemini", "voice-1")
);
assert!(tickets.redeem(&once).is_none(), "a ticket works once");
let late = tickets.issue(&ana, "gemini", "voice-1");
tokio::time::advance(TICKET_LIFETIME - Duration::from_millis(1)).await;
let early = tickets.issue(&ana, "gemini", "voice-1");
tokio::time::advance(Duration::from_millis(2)).await;
assert!(tickets.redeem(&late).is_none(), "a ticket expires after thirty seconds");
assert!(tickets.redeem(&early).is_some());
assert!(tickets.redeem("made-up").is_none());
}
}