#[cfg(feature = "livekit-sip")]
pub mod livekit;
mod tools;
pub use tools::{EndCallTool, PlaceCallTool, SendDtmfTool, TransferCallTool};
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use adk_core::GovernanceControl;
use adk_core::egress::ToolEgress;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::config::RealtimeConfig;
use crate::error::{RealtimeError, Result};
const MAX_TARGET_LEN: usize = 256;
const MAX_DTMF_TONES: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SipHeader {
pub name: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct IncomingCall {
pub provider: String,
pub call_id: String,
pub sip_headers: Vec<SipHeader>,
pub attributes: BTreeMap<String, String>,
}
impl IncomingCall {
pub fn new(provider: impl Into<String>, call_id: impl Into<String>) -> Self {
Self {
provider: provider.into(),
call_id: call_id.into(),
sip_headers: Vec::new(),
attributes: BTreeMap::new(),
}
}
pub fn with_sip_headers(mut self, headers: Vec<SipHeader>) -> Self {
self.sip_headers = headers;
self
}
pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn header(&self, name: &str) -> Option<&str> {
self.sip_headers
.iter()
.find(|header| header.name.eq_ignore_ascii_case(name))
.map(|header| header.value.as_str())
}
pub fn from(&self) -> Option<&str> {
self.header("From")
}
pub fn to(&self) -> Option<&str> {
self.header("To")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct CallTarget(String);
impl CallTarget {
pub fn parse(uri: &str) -> Result<Self> {
let uri = uri.trim();
if uri.len() > MAX_TARGET_LEN
|| uri.chars().any(|c| c.is_whitespace() || c.is_control() || c == '<' || c == '>')
{
return Err(RealtimeError::config(format!(
"call target must be at most {MAX_TARGET_LEN} bytes with no whitespace, control characters or angle brackets"
)));
}
if let Some(number) = uri.strip_prefix("tel:") {
validate_e164(number)?;
return Ok(Self(uri.to_string()));
}
let address = uri.strip_prefix("sips:").or_else(|| uri.strip_prefix("sip:"));
match address.and_then(|rest| rest.split_once('@')) {
Some((user, host)) if !user.is_empty() && !host.is_empty() => Ok(Self(uri.to_string())),
_ => Err(RealtimeError::config(format!(
"call target '{uri}' must be tel:+<E.164 number>, sip:user@host or sips:user@host"
))),
}
}
pub fn phone(number: &str) -> Result<Self> {
validate_e164(number)?;
Ok(Self(format!("tel:{number}")))
}
pub fn as_uri(&self) -> &str {
&self.0
}
pub fn phone_number(&self) -> Option<&str> {
self.0.strip_prefix("tel:")
}
}
fn validate_e164(number: &str) -> Result<()> {
let digits = number.strip_prefix('+').unwrap_or_default();
let valid = (7..=15).contains(&digits.len())
&& digits.chars().all(|c| c.is_ascii_digit())
&& !digits.starts_with('0');
if valid {
Ok(())
} else {
Err(RealtimeError::config(format!(
"'{number}' is not an E.164 number: '+' then 7 to 15 digits, the first not zero"
)))
}
}
impl FromStr for CallTarget {
type Err = RealtimeError;
fn from_str(uri: &str) -> Result<Self> {
Self::parse(uri)
}
}
impl TryFrom<String> for CallTarget {
type Error = RealtimeError;
fn try_from(uri: String) -> Result<Self> {
Self::parse(&uri)
}
}
impl From<CallTarget> for String {
fn from(target: CallTarget) -> Self {
target.0
}
}
impl fmt::Display for CallTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DtmfTones(String);
impl DtmfTones {
pub fn parse(tones: &str) -> Result<Self> {
let valid = !tones.is_empty()
&& tones.len() <= MAX_DTMF_TONES
&& tones.chars().all(|c| c.is_ascii_digit() || matches!(c, '*' | '#' | 'A'..='D'));
if valid {
Ok(Self(tones.to_string()))
} else {
Err(RealtimeError::config(format!(
"DTMF tones must be 1 to {MAX_DTMF_TONES} of 0-9, *, # and A-D"
)))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct CallCapabilities {
pub transfer: bool,
pub dtmf: bool,
}
impl CallCapabilities {
pub fn new(transfer: bool, dtmf: bool) -> Self {
Self { transfer, dtmf }
}
}
#[async_trait]
pub trait CallControl: fmt::Debug + Send + Sync {
fn call_id(&self) -> &str;
fn provider(&self) -> &str;
fn capabilities(&self) -> CallCapabilities;
fn egress(&self) -> ToolEgress {
ToolEgress::Configured
}
async fn transfer(&self, target: &CallTarget) -> Result<()>;
async fn hang_up(&self) -> Result<()>;
async fn send_dtmf(&self, _tones: &DtmfTones) -> Result<()> {
Err(RealtimeError::provider(format!(
"{} calls do not support sending DTMF",
self.provider()
)))
}
}
#[async_trait]
pub trait CallAnswerer: Send + Sync {
async fn answer(
&self,
call: &IncomingCall,
config: &RealtimeConfig,
) -> Result<Arc<dyn CallControl>>;
async fn decline(&self, call: &IncomingCall, status: u16) -> Result<()>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DialRequest {
pub to: CallTarget,
pub attributes: BTreeMap<String, String>,
}
impl DialRequest {
pub fn new(to: CallTarget) -> Self {
Self { to, attributes: BTreeMap::new() }
}
pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
}
#[async_trait]
pub trait OutboundDialer: fmt::Debug + Send + Sync {
fn provider(&self) -> &str;
fn egress(&self) -> ToolEgress {
ToolEgress::Configured
}
async fn dial(&self, request: &DialRequest) -> Result<Arc<dyn CallControl>>;
}
#[derive(Debug)]
#[must_use = "the call is hung up on a freeze only while the guard is held"]
pub struct CallFreezeGuard {
task: tokio::task::JoinHandle<()>,
}
impl CallFreezeGuard {
pub fn is_finished(&self) -> bool {
self.task.is_finished()
}
}
impl Drop for CallFreezeGuard {
fn drop(&mut self) {
self.task.abort();
}
}
pub fn hang_up_on_freeze(
call: Arc<dyn CallControl>,
controls: impl IntoIterator<Item = GovernanceControl>,
) -> CallFreezeGuard {
let controls: Vec<GovernanceControl> = controls.into_iter().collect();
let task = tokio::spawn(async move {
if controls.is_empty() {
return std::future::pending().await;
}
let refusals = controls.iter().map(|control| Box::pin(control.refused()));
let (refusal, _, _) = futures::future::select_all(refusals).await;
tracing::warn!(
call.provider = call.provider(),
call.id = call.call_id(),
error = %refusal.diagnostics(),
"governance froze; hanging up the call"
);
if let Err(error) = call.hang_up().await {
tracing::error!(
call.provider = call.provider(),
call.id = call.call_id(),
error = %error,
"the call could not be hung up after a freeze"
);
}
});
CallFreezeGuard { task }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn targets_accept_e164_numbers_and_sip_addresses() {
for uri in [
"tel:+14155550100",
"sip:billing@pbx.example.com",
"sips:+14155550100@trunk.example.com:5061",
] {
assert_eq!(CallTarget::parse(uri).unwrap().as_uri(), uri);
}
}
#[test]
fn targets_refuse_header_injection_and_other_schemes() {
for uri in [
"tel:+14155550100\r\nX-Injected: 1",
"tel:+1 415 555 0100",
"<sip:billing@pbx.example.com>",
"tel:14155550100",
"tel:+0123456789",
"tel:+123",
"sip:pbx.example.com",
"sip:@pbx.example.com",
"https://example.com",
"",
] {
assert!(CallTarget::parse(uri).is_err(), "{uri:?} must be refused");
}
assert!(CallTarget::parse(&format!("sip:{}@example.com", "a".repeat(300))).is_err());
}
#[test]
fn targets_round_trip_through_json() {
let target: CallTarget = serde_json::from_str("\"tel:+14155550100\"").unwrap();
assert_eq!(serde_json::to_string(&target).unwrap(), "\"tel:+14155550100\"");
assert!(serde_json::from_str::<CallTarget>("\"tel:911\"").is_err());
}
#[test]
fn dtmf_tones_are_bounded() {
assert!(DtmfTones::parse("0123456789*#ABCD").is_ok());
assert!(DtmfTones::parse("").is_err());
assert!(DtmfTones::parse("1w2").is_err());
assert!(DtmfTones::parse(&"1".repeat(33)).is_err());
}
}