use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
use serde_json::{Map, Value};
pub type JsonObject = Map<String, Value>;
pub fn new_message_id() -> String {
format!("m_{}", uuid::Uuid::new_v4().simple())
}
pub fn new_response_id() -> String {
format!("r_{}", uuid::Uuid::new_v4().simple())
}
pub fn new_item_id() -> String {
format!("it_{}", uuid::Uuid::new_v4().simple())
}
pub fn new_timestamp() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let secs = now.as_secs() as i64;
let (year, month, day) = civil_from_days(secs.div_euclid(86_400));
let of_day = secs.rem_euclid(86_400);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
of_day / 3600,
of_day % 3600 / 60,
of_day % 60,
now.subsec_millis()
)
}
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
const MAX_MODEL_DEBUG_LENGTH: usize = 1024;
const MAX_FIELD_DEBUG_LENGTH: usize = 128;
const REDACTED: &str = "<redacted>";
const SAFE_DEBUG_FIELDS: &[&str] = &[
"admission_timeout_ms",
"code",
"count",
"first_output_ms",
"id",
"idle_ms",
"in_reply_to",
"item_id",
"item_ids",
"max_duration_ms",
"mode",
"no_input_timeout_ms",
"protocol_version",
"reconnect",
"response_id",
"response_timeouts",
"retriable",
"stage",
"ts",
"type",
];
fn truncate(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
let keep: String = text.chars().take(max.saturating_sub(3)).collect();
format!("{keep}...")
}
#[doc(hidden)]
pub fn debug_field<T: Serialize + ?Sized>(name: &str, value: &T) -> String {
let rendered = serde_json::to_value(value).unwrap_or(Value::Null);
let shown = if !rendered.is_null() && !SAFE_DEBUG_FIELDS.contains(&name) {
REDACTED.to_string()
} else {
truncate(&rendered.to_string(), MAX_FIELD_DEBUG_LENGTH)
};
format!("{name}={shown}")
}
#[doc(hidden)]
pub fn debug_finish(name: &str, fields: &[String], f: &mut fmt::Formatter<'_>) -> fmt::Result {
let rendered = format!("{name}({})", fields.join(", "));
if rendered.chars().count() <= MAX_MODEL_DEBUG_LENGTH {
return f.write_str(&rendered);
}
let keep: String = rendered.chars().take(MAX_MODEL_DEBUG_LENGTH - 4).collect();
write!(f, "{keep}...)")
}
macro_rules! redacted_debug {
($ty:ident { $($field:ident),* $(,)? }) => {
impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let fields = [$(debug_field(stringify!($field), &self.$field)),*];
debug_finish(stringify!($ty), &fields, f)
}
}
};
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseTimeouts {
pub first_output_ms: u64,
pub idle_ms: u64,
pub max_duration_ms: u64,
}
redacted_debug!(ResponseTimeouts {
first_output_ms,
idle_ms,
max_duration_ms
});
#[derive(Clone, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum InputContentPart {
#[serde(rename = "input_text")]
InputText {
text: String,
},
#[serde(rename = "input_data")]
InputData {
data: JsonObject,
},
}
impl fmt::Debug for InputContentPart {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InputText { text } => debug_finish(
"InputTextPart",
&[debug_field("text", text), "type=\"input_text\"".into()],
f,
),
Self::InputData { data } => debug_finish(
"InputDataPart",
&[debug_field("data", data), "type=\"input_data\"".into()],
f,
),
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct SessionDisconnected {
pub code: u16,
pub reason: Option<String>,
}
redacted_debug!(SessionDisconnected { code, reason });
#[derive(Clone, PartialEq, Serialize)]
pub struct SessionStart {
pub id: String,
pub ts: String,
pub protocol_version: String,
pub reconnect: bool,
pub response_timeouts: ResponseTimeouts,
#[serde(skip_serializing_if = "Option::is_none")]
pub greeting: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub no_input_timeout_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub caller: Option<JsonObject>,
}
redacted_debug!(SessionStart {
id,
ts,
protocol_version,
reconnect,
response_timeouts,
greeting,
no_input_timeout_ms,
caller
});
#[derive(Clone, PartialEq, Serialize)]
pub struct UserMessage {
pub id: String,
pub ts: String,
pub item_id: String,
pub content: Vec<InputContentPart>,
}
redacted_debug!(UserMessage {
id,
ts,
item_id,
content
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct UserNoInput {
pub id: String,
pub ts: String,
pub item_id: String,
pub count: u64,
}
redacted_debug!(UserNoInput {
id,
ts,
item_id,
count
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct UserSpeechStarted {
pub id: String,
pub ts: String,
}
redacted_debug!(UserSpeechStarted { id, ts });
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct UserBargeIn {
pub id: String,
pub ts: String,
pub response_id: String,
pub heard_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_id: Option<String>,
}
redacted_debug!(UserBargeIn {
id,
ts,
response_id,
heard_text,
item_id
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseAccepted {
pub id: String,
pub ts: String,
pub response_id: String,
}
redacted_debug!(ResponseAccepted {
id,
ts,
response_id
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseDropped {
pub id: String,
pub ts: String,
pub response_id: String,
pub reason: String,
}
redacted_debug!(ResponseDropped {
id,
ts,
response_id,
reason
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseCancelled {
pub id: String,
pub ts: String,
pub response_id: String,
pub heard_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_id: Option<String>,
}
redacted_debug!(ResponseCancelled {
id,
ts,
response_id,
heard_text,
item_id
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseTimeout {
pub id: String,
pub ts: String,
pub stage: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub response_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_ids: Option<Vec<String>>,
}
redacted_debug!(ResponseTimeout {
id,
ts,
stage,
response_id,
item_ids
});
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct SessionEnd {
pub id: String,
pub ts: String,
pub reason: String,
}
redacted_debug!(SessionEnd { id, ts, reason });
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum InboundVoiceMessage {
#[serde(rename = "session.start")]
SessionStart(SessionStart),
#[serde(rename = "user.message")]
UserMessage(UserMessage),
#[serde(rename = "user.no_input")]
UserNoInput(UserNoInput),
#[serde(rename = "user.speech_started")]
UserSpeechStarted(UserSpeechStarted),
#[serde(rename = "user.barge_in")]
UserBargeIn(UserBargeIn),
#[serde(rename = "response.accepted")]
ResponseAccepted(ResponseAccepted),
#[serde(rename = "response.dropped")]
ResponseDropped(ResponseDropped),
#[serde(rename = "response.cancelled")]
ResponseCancelled(ResponseCancelled),
#[serde(rename = "response.timeout")]
ResponseTimeout(ResponseTimeout),
#[serde(rename = "session.end")]
SessionEnd(SessionEnd),
}
impl InboundVoiceMessage {
pub fn message_type(&self) -> &'static str {
match self {
Self::SessionStart(_) => "session.start",
Self::UserMessage(_) => "user.message",
Self::UserNoInput(_) => "user.no_input",
Self::UserSpeechStarted(_) => "user.speech_started",
Self::UserBargeIn(_) => "user.barge_in",
Self::ResponseAccepted(_) => "response.accepted",
Self::ResponseDropped(_) => "response.dropped",
Self::ResponseCancelled(_) => "response.cancelled",
Self::ResponseTimeout(_) => "response.timeout",
Self::SessionEnd(_) => "session.end",
}
}
pub fn id(&self) -> &str {
match self {
Self::SessionStart(m) => &m.id,
Self::UserMessage(m) => &m.id,
Self::UserNoInput(m) => &m.id,
Self::UserSpeechStarted(m) => &m.id,
Self::UserBargeIn(m) => &m.id,
Self::ResponseAccepted(m) => &m.id,
Self::ResponseDropped(m) => &m.id,
Self::ResponseCancelled(m) => &m.id,
Self::ResponseTimeout(m) => &m.id,
Self::SessionEnd(m) => &m.id,
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct SessionReady {
pub id: String,
pub ts: String,
}
redacted_debug!(SessionReady { id, ts });
impl SessionReady {
pub fn new() -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
}
}
}
impl Default for SessionReady {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct SessionRejected {
pub id: String,
pub ts: String,
pub code: String,
pub retriable: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
redacted_debug!(SessionRejected {
id,
ts,
code,
retriable,
message
});
impl SessionRejected {
pub fn new(code: impl Into<String>, retriable: bool) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
code: code.into(),
retriable,
message: None,
}
}
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = Some(message.into());
self
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseCreated {
pub id: String,
pub ts: String,
pub response_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub in_reply_to: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub admission_timeout_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supersede_key: Option<String>,
}
redacted_debug!(ResponseCreated {
id,
ts,
response_id,
in_reply_to,
admission_timeout_ms,
supersede_key
});
impl ResponseCreated {
pub fn reply<I, S>(response_id: impl Into<String>, in_reply_to: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
in_reply_to: Some(in_reply_to.into_iter().map(Into::into).collect()),
..Self::proactive(response_id)
}
}
pub fn proactive(response_id: impl Into<String>) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
response_id: response_id.into(),
in_reply_to: None,
admission_timeout_ms: None,
supersede_key: None,
}
}
pub fn with_admission_timeout_ms(mut self, timeout: u64) -> Self {
self.admission_timeout_ms = Some(timeout);
self
}
pub fn with_supersede_key(mut self, key: impl Into<String>) -> Self {
self.supersede_key = Some(key.into());
self
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseNone {
pub id: String,
pub ts: String,
pub in_reply_to: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
redacted_debug!(ResponseNone {
id,
ts,
in_reply_to,
reason
});
impl ResponseNone {
pub fn new<I, S>(in_reply_to: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
id: new_message_id(),
ts: new_timestamp(),
in_reply_to: in_reply_to.into_iter().map(Into::into).collect(),
reason: None,
}
}
pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
}
#[derive(Clone, PartialEq, Serialize)]
pub struct ResponseOutputTextDelta {
pub id: String,
pub ts: String,
pub response_id: String,
pub item_id: String,
pub delta: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub voice: Option<JsonObject>,
}
redacted_debug!(ResponseOutputTextDelta {
id,
ts,
response_id,
item_id,
delta,
voice
});
impl ResponseOutputTextDelta {
pub fn new(
response_id: impl Into<String>,
item_id: impl Into<String>,
delta: impl Into<String>,
) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
response_id: response_id.into(),
item_id: item_id.into(),
delta: delta.into(),
voice: None,
}
}
pub fn with_voice(mut self, voice: JsonObject) -> Self {
self.voice = Some(voice);
self
}
}
#[derive(Clone, PartialEq, Serialize)]
pub struct ResponseOutputTextDone {
pub id: String,
pub ts: String,
pub response_id: String,
pub item_id: String,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub voice: Option<JsonObject>,
}
redacted_debug!(ResponseOutputTextDone {
id,
ts,
response_id,
item_id,
text,
voice
});
impl ResponseOutputTextDone {
pub fn new(
response_id: impl Into<String>,
item_id: impl Into<String>,
text: impl Into<String>,
) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
response_id: response_id.into(),
item_id: item_id.into(),
text: text.into(),
voice: None,
}
}
pub fn with_voice(mut self, voice: JsonObject) -> Self {
self.voice = Some(voice);
self
}
}
#[derive(Clone, PartialEq, Serialize)]
pub struct ResponseOutputDataDone {
pub id: String,
pub ts: String,
pub response_id: String,
pub item_id: String,
pub data: JsonObject,
}
redacted_debug!(ResponseOutputDataDone {
id,
ts,
response_id,
item_id,
data
});
impl ResponseOutputDataDone {
pub fn new(
response_id: impl Into<String>,
item_id: impl Into<String>,
data: JsonObject,
) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
response_id: response_id.into(),
item_id: item_id.into(),
data,
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseDone {
pub id: String,
pub ts: String,
pub response_id: String,
}
redacted_debug!(ResponseDone {
id,
ts,
response_id
});
impl ResponseDone {
pub fn new(response_id: impl Into<String>) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
response_id: response_id.into(),
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ResponseCancel {
pub id: String,
pub ts: String,
pub response_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
redacted_debug!(ResponseCancel {
id,
ts,
response_id,
reason
});
impl ResponseCancel {
pub fn new(response_id: impl Into<String>) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
response_id: response_id.into(),
reason: None,
}
}
pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum EndCallMode {
#[default]
Drain,
Immediate,
}
impl EndCallMode {
pub fn as_str(self) -> &'static str {
match self {
Self::Drain => "drain",
Self::Immediate => "immediate",
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct EndCall {
pub id: String,
pub ts: String,
pub reason: String,
pub mode: EndCallMode,
}
redacted_debug!(EndCall {
id,
ts,
reason,
mode
});
impl EndCall {
pub fn new(reason: impl Into<String>) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
reason: reason.into(),
mode: EndCallMode::Drain,
}
}
pub fn with_mode(mut self, mode: EndCallMode) -> Self {
self.mode = mode;
self
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct AgentError {
pub id: String,
pub ts: String,
pub code: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub response_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_id: Option<String>,
}
redacted_debug!(AgentError {
id,
ts,
code,
message,
response_id,
item_id
});
impl AgentError {
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
id: new_message_id(),
ts: new_timestamp(),
code: code.into(),
message: message.into(),
response_id: None,
item_id: None,
}
}
pub fn with_response_id(mut self, response_id: impl Into<String>) -> Self {
self.response_id = Some(response_id.into());
self
}
pub fn with_item_id(mut self, item_id: impl Into<String>) -> Self {
self.item_id = Some(item_id.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum OutboundVoiceMessage {
#[serde(rename = "session.ready")]
SessionReady(SessionReady),
#[serde(rename = "session.rejected")]
SessionRejected(SessionRejected),
#[serde(rename = "response.created")]
ResponseCreated(ResponseCreated),
#[serde(rename = "response.none")]
ResponseNone(ResponseNone),
#[serde(rename = "response.output_data.done")]
ResponseOutputDataDone(ResponseOutputDataDone),
#[serde(rename = "response.output_text.delta")]
ResponseOutputTextDelta(ResponseOutputTextDelta),
#[serde(rename = "response.output_text.done")]
ResponseOutputTextDone(ResponseOutputTextDone),
#[serde(rename = "response.done")]
ResponseDone(ResponseDone),
#[serde(rename = "response.cancel")]
ResponseCancel(ResponseCancel),
#[serde(rename = "end_call")]
EndCall(EndCall),
#[serde(rename = "error")]
Error(AgentError),
}
impl OutboundVoiceMessage {
pub fn message_type(&self) -> &'static str {
match self {
Self::SessionReady(_) => "session.ready",
Self::SessionRejected(_) => "session.rejected",
Self::ResponseCreated(_) => "response.created",
Self::ResponseNone(_) => "response.none",
Self::ResponseOutputDataDone(_) => "response.output_data.done",
Self::ResponseOutputTextDelta(_) => "response.output_text.delta",
Self::ResponseOutputTextDone(_) => "response.output_text.done",
Self::ResponseDone(_) => "response.done",
Self::ResponseCancel(_) => "response.cancel",
Self::EndCall(_) => "end_call",
Self::Error(_) => "error",
}
}
}
macro_rules! outbound_from {
($($variant:ident($ty:ident)),* $(,)?) => {
$(impl From<$ty> for OutboundVoiceMessage {
fn from(message: $ty) -> Self {
Self::$variant(message)
}
})*
};
}
outbound_from!(
SessionReady(SessionReady),
SessionRejected(SessionRejected),
ResponseCreated(ResponseCreated),
ResponseNone(ResponseNone),
ResponseOutputDataDone(ResponseOutputDataDone),
ResponseOutputTextDelta(ResponseOutputTextDelta),
ResponseOutputTextDone(ResponseOutputTextDone),
ResponseDone(ResponseDone),
ResponseCancel(ResponseCancel),
EndCall(EndCall),
Error(AgentError),
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dates_are_proleptic_gregorian() {
assert_eq!(civil_from_days(0), (1970, 1, 1));
assert_eq!(civil_from_days(19_723), (2024, 1, 1));
assert_eq!(civil_from_days(19_782), (2024, 2, 29));
assert_eq!(civil_from_days(-1), (1969, 12, 31));
}
}