use std::sync::Arc;
use adk_core::egress::ToolEgress;
use adk_core::webhook::{
WebhookHeaders, WebhookReplayGuard, WebhookSecret, WebhookVerifier, replay_window,
};
use async_trait::async_trait;
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use serde_json::{Value, json};
use super::DEFAULT_MODEL;
use super::OpenAIRealtimeModel;
use crate::config::RealtimeConfig;
use crate::error::{RealtimeError, Result};
use crate::telephony::{
CallAnswerer, CallCapabilities, CallControl, CallTarget, IncomingCall, SipHeader,
};
pub const OPENAI_API_BASE: &str = "https://api.openai.com/v1";
pub const REALTIME_CALL_INCOMING: &str = "realtime.call.incoming";
const PROVIDER: &str = "openai";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum OpenAIWebhookEvent {
IncomingCall(IncomingCall),
Other {
event_type: String,
data: Value,
},
}
#[derive(Deserialize)]
struct Envelope {
#[serde(rename = "type")]
event_type: String,
#[serde(default)]
data: Value,
}
#[derive(Deserialize)]
struct IncomingCallData {
call_id: String,
#[serde(default)]
sip_headers: Vec<SipHeader>,
}
#[derive(Clone)]
pub struct OpenAIWebhookVerifier {
verifier: WebhookVerifier,
replay: Option<Arc<dyn WebhookReplayGuard>>,
}
impl std::fmt::Debug for OpenAIWebhookVerifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenAIWebhookVerifier")
.field("verifier", &self.verifier)
.field("replay_guard", &self.replay.is_some())
.finish()
}
}
impl OpenAIWebhookVerifier {
pub fn new(secret: &str) -> Result<Self> {
Ok(Self::with_verifier(WebhookVerifier::new(Self::secret(secret)?)))
}
pub fn with_verifier(verifier: WebhookVerifier) -> Self {
Self { verifier, replay: None }
}
pub fn secret(secret: &str) -> Result<WebhookSecret> {
let secret = secret.trim();
let key = if secret.starts_with("whsec_") {
WebhookSecret::from_base64(secret)
} else {
WebhookSecret::from_bytes(secret.as_bytes())
};
key.map_err(|error| RealtimeError::config(format!("OpenAI webhook secret: {error}")))
}
pub fn with_replay_guard(mut self, guard: Arc<dyn WebhookReplayGuard>) -> Self {
self.replay = Some(guard);
self
}
pub async fn verify<'a>(
&self,
header: impl Fn(&'static str) -> Option<&'a str>,
body: &[u8],
) -> Result<OpenAIWebhookEvent> {
let rejected = |error: adk_core::webhook::WebhookError| {
RealtimeError::AuthError(format!("OpenAI webhook rejected: {error}"))
};
let headers = WebhookHeaders::from_lookup(header).map_err(rejected)?;
let verified = self.verifier.verify(&headers, body).map_err(rejected)?;
if let Some(guard) = &self.replay {
let window = chrono::Duration::from_std(replay_window(self.verifier.tolerance()))
.unwrap_or(chrono::Duration::MAX);
let keep_until = chrono::Utc::now() + window;
let first = guard.first_seen(&verified.id, keep_until).await.map_err(|error| {
RealtimeError::AuthError(format!(
"OpenAI webhook replay guard unavailable: {}",
error.redacted()
))
})?;
if !first {
return Err(RealtimeError::AuthError(format!(
"OpenAI webhook {} was already delivered",
verified.id
)));
}
}
let envelope: Envelope = serde_json::from_slice(body)
.map_err(|error| RealtimeError::protocol(format!("OpenAI webhook body: {error}")))?;
if envelope.event_type != REALTIME_CALL_INCOMING {
return Ok(OpenAIWebhookEvent::Other {
event_type: envelope.event_type,
data: envelope.data,
});
}
let data: IncomingCallData = serde_json::from_value(envelope.data).map_err(|error| {
RealtimeError::protocol(format!("{REALTIME_CALL_INCOMING} data: {error}"))
})?;
tracing::info!(call.provider = PROVIDER, call.id = %data.call_id, "incoming SIP call");
Ok(OpenAIWebhookEvent::IncomingCall(
IncomingCall::new(PROVIDER, data.call_id).with_sip_headers(data.sip_headers),
))
}
}
#[derive(Clone)]
pub struct OpenAISipClient {
http: reqwest::Client,
api_key: SecretString,
base_url: String,
realtime_url: Option<String>,
model: String,
}
impl std::fmt::Debug for OpenAISipClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenAISipClient")
.field("base_url", &self.base_url)
.field("model", &self.model)
.finish_non_exhaustive()
}
}
impl OpenAISipClient {
pub fn new(api_key: impl Into<String>) -> Self {
Self {
http: reqwest::Client::new(),
api_key: SecretString::from(api_key.into()),
base_url: OPENAI_API_BASE.to_string(),
realtime_url: None,
model: DEFAULT_MODEL.to_string(),
}
}
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = base_url.into().trim_end_matches('/').to_string();
self
}
pub fn with_realtime_url(mut self, url: impl Into<String>) -> Self {
self.realtime_url = Some(url.into());
self
}
pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
self.http = http;
self
}
pub fn model(&self) -> &str {
&self.model
}
pub async fn accept(&self, call_id: &str, config: &RealtimeConfig) -> Result<OpenAISipCall> {
let mut session = crate::openai::protocol::call_session_config(config);
session["model"] = json!(self.model);
self.post(call_id, "accept", Some(session)).await?;
tracing::info!(call.provider = PROVIDER, call.id = %call_id, "SIP call accepted");
Ok(self.call(call_id))
}
pub async fn reject(&self, call_id: &str, status_code: Option<u16>) -> Result<()> {
let body = match status_code {
Some(status) if (300..=699).contains(&status) => Some(json!({ "status_code": status })),
Some(status) => {
return Err(RealtimeError::config(format!(
"SIP status {status} cannot reject a call; use 300 to 699"
)));
}
None => None,
};
self.post(call_id, "reject", body).await?;
tracing::info!(call.provider = PROVIDER, call.id = %call_id, "SIP call rejected");
Ok(())
}
pub async fn refer(&self, call_id: &str, target: &CallTarget) -> Result<()> {
self.post(call_id, "refer", Some(json!({ "target_uri": target.as_uri() }))).await
}
pub async fn hang_up(&self, call_id: &str) -> Result<()> {
self.post(call_id, "hangup", None).await
}
pub fn call(&self, call_id: impl Into<String>) -> OpenAISipCall {
OpenAISipCall { client: self.clone(), call_id: call_id.into() }
}
pub fn realtime_model(&self, call_id: &str) -> OpenAIRealtimeModel {
let model = OpenAIRealtimeModel::new(self.api_key.expose_secret(), &self.model)
.with_call_id(call_id);
match &self.realtime_url {
Some(url) => model.with_base_url(url),
None => model,
}
}
async fn post(&self, call_id: &str, action: &str, body: Option<Value>) -> Result<()> {
let call: String = url::form_urlencoded::byte_serialize(call_id.as_bytes()).collect();
let url = format!("{}/realtime/calls/{call}/{action}", self.base_url);
let mut request = self.http.post(&url).bearer_auth(self.api_key.expose_secret());
if let Some(body) = body {
request = request.json(&body);
}
let response = request.send().await.map_err(|error| {
RealtimeError::connection(format!("OpenAI SIP {action} request failed: {error}"))
})?;
let status = response.status();
if status.is_success() {
return Ok(());
}
let text = response.text().await.unwrap_or_default();
let detail: Value = serde_json::from_str(&text).unwrap_or_default();
let code = detail
.pointer("/error/code")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("http_{}", status.as_u16()));
let message = detail
.pointer("/error/message")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("OpenAI SIP {action} returned {status}"));
tracing::warn!(
call.provider = PROVIDER,
call.id = %call_id,
call.action = action,
http.status = status.as_u16(),
error.code = %code,
"OpenAI SIP request refused"
);
Err(RealtimeError::ServerError { code, message })
}
}
#[async_trait]
impl CallAnswerer for OpenAISipClient {
async fn answer(
&self,
call: &IncomingCall,
config: &RealtimeConfig,
) -> Result<Arc<dyn CallControl>> {
Ok(Arc::new(self.accept(&call.call_id, config).await?))
}
async fn decline(&self, call: &IncomingCall, status: u16) -> Result<()> {
self.reject(&call.call_id, Some(status)).await
}
}
#[derive(Debug, Clone)]
pub struct OpenAISipCall {
client: OpenAISipClient,
call_id: String,
}
#[async_trait]
impl CallControl for OpenAISipCall {
fn call_id(&self) -> &str {
&self.call_id
}
fn provider(&self) -> &str {
PROVIDER
}
fn capabilities(&self) -> CallCapabilities {
CallCapabilities::new(true, false)
}
fn egress(&self) -> ToolEgress {
ToolEgress::for_urls([self.client.base_url.as_str()])
}
async fn transfer(&self, target: &CallTarget) -> Result<()> {
self.client.refer(&self.call_id, target).await
}
async fn hang_up(&self) -> Result<()> {
self.client.hang_up(&self.call_id).await
}
}