aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,158 @@
//! Adapts caller-owned, bounded JSON channels to the existing realtime parser and writer.
//!
//! ```text
//! Caller -- incoming JSON --> read loop -- Message::Text --> Core event parser
//! Caller <-- outgoing JSON -- write loop <-- WsCommand ----- Core writer
//! ```
//!
//! Each channel item carries one JSON message of up to 1 MiB. The loops run
//! independently so Core can still receive events while a command waits for
//! space in the caller's queue. Shutdown seals incoming messages and drains accepted
//! input before closing both directions, including a frame awaiting parser capacity.
use super::*;
use akode_protocol::protocol::RealtimeSidebandTransport;
const MAX_MESSAGE_BYTES: usize = 1024 * 1024;
impl RealtimeWebsocketConnection {
/// Uses an already authenticated, caller-owned stream without opening or reconnecting a socket.
pub fn from_sideband(
transport: RealtimeSidebandTransport,
event_parser: RealtimeEventParser,
) -> Self {
let RealtimeSidebandTransport {
mut incoming,
outgoing,
} = transport;
let (tx_command, mut rx_command) = mpsc::channel::<WsCommand>(32);
let (tx_message, rx_message) = async_channel::bounded(32);
let (_, terminal_policy_error) = tokio::sync::watch::channel(None);
let (input_stop, mut input_stopped) = tokio::sync::watch::channel(false);
let transport_input_stop = input_stop.clone();
let transport_task = tokio::spawn(async move {
let read = async {
let mut is_draining = false;
loop {
let text = if is_draining {
// A reserved but unsent permit must not hold shutdown open.
// try_recv() will drain messages already queued and exit when emptied.
incoming.try_recv().ok()
} else {
tokio::select! {
biased;
// Core requested shutdown, or the transport's write loop ended.
_ = input_stopped.changed() => {
incoming.close();
is_draining = true;
continue;
}
// The caller dropped its receiver for Core commands.
// Detect this even when the writer is idle, then drain accepted input.
_ = outgoing.closed() => {
incoming.close();
is_draining = true;
continue;
}
text = incoming.recv() => text,
}
};
let Some(text) = text else {
break;
};
if text.len() > MAX_MESSAGE_BYTES {
break;
}
if tx_message
.send(Ok(Message::Text(text.into())))
.await
.is_err()
{
break;
}
}
};
let write = async {
while let Some(command) = rx_command.recv().await {
// These commands are still called WsCommand for legacy reasons.
match command {
WsCommand::Send {
message: Message::Text(text),
tx_result,
} => {
let result = if text.len() > MAX_MESSAGE_BYTES {
Err(WsError::Io(std::io::Error::other(
"sideband message too large",
)))
} else {
outgoing
.send(text.to_string())
.await
.map_err(|_| WsError::ConnectionClosed)
};
let failed = result.is_err();
// Tell Core's writer whether the caller's channel accepted the command.
let _ = tx_result.send(result);
if failed {
break;
}
}
WsCommand::Close {
frame: _,
tx_result,
} => {
let _ = tx_result.send(Ok(()));
break;
}
WsCommand::Send { tx_result, .. } => {
let _ = tx_result.send(Err(WsError::Io(std::io::Error::other(
"sideband requires JSON text",
))));
break;
}
}
}
};
tokio::pin!(read);
tokio::select! {
_ = &mut read => {},
_ = write => {
transport_input_stop.send_replace(true);
// Preserve the read future: it may already own a frame that
// has not yet fit into the parser queue.
read.await;
},
}
});
Self::new(
WsStream {
tx_command,
transport_task,
sideband_input_stop: Some(input_stop),
terminal_policy_error,
},
rx_message,
event_parser,
RealtimeTranscriptState::default(),
)
}
}
impl RealtimeWebsocketWriter {
/// Seal caller-owned input so its accepted events can drain without waiting for producers.
/// Socket-backed connections are unaffected.
pub fn close_sideband_input(&self) {
if let Some(input_stop) = &self.stream.sideband_input_stop {
input_stop.send_replace(true);
}
}
}
#[cfg(test)]
#[path = "sideband_tests.rs"]
mod tests;

View File

@@ -0,0 +1,210 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
use std::time::Duration;
use tokio::time::timeout;
fn connection() -> (
RealtimeWebsocketConnection,
mpsc::Sender<String>,
mpsc::Receiver<String>,
) {
let (events, incoming) = mpsc::channel(1);
let (outgoing, commands) = mpsc::channel(1);
(
RealtimeWebsocketConnection::from_sideband(
RealtimeSidebandTransport { incoming, outgoing },
RealtimeEventParser::FramelessBidi,
),
events,
commands,
)
}
/// A blocked command receiver must not prevent receiving a realtime event on the other half.
#[tokio::test]
async fn stalled_output_does_not_block_input() {
let (connection, events, commands) = connection();
let writer = connection.writer();
writer.send_payload("first".into()).await.unwrap();
let blocked = tokio::spawn(async move { writer.send_payload("second".into()).await });
events
.send(r#"{"type":"session.started","session":{"id":"call"}}"#.into())
.await
.unwrap();
assert!(
timeout(Duration::from_secs(1), connection.next_event())
.await
.unwrap()
.unwrap()
.is_some()
);
assert!(!blocked.is_finished());
drop(commands);
assert!(
timeout(Duration::from_secs(1), blocked)
.await
.unwrap()
.unwrap()
.is_err()
);
assert!(
timeout(Duration::from_secs(1), connection.next_event())
.await
.unwrap()
.is_err()
);
}
/// Ending the input stream closes the output too and never attempts reconnection.
#[tokio::test]
async fn input_half_close_ends_attachment() {
let (connection, events, mut commands) = connection();
drop(events);
assert!(
timeout(Duration::from_secs(1), connection.next_event())
.await
.unwrap()
.is_err()
);
assert_eq!(
timeout(Duration::from_secs(1), commands.recv())
.await
.unwrap(),
None
);
assert!(
connection
.writer()
.send_payload("late".into())
.await
.is_err()
);
}
/// A caller dropping its response half releases an idle transport without waiting for another command.
#[tokio::test]
async fn response_half_close_ends_idle_attachment() {
let (_connection, events, commands) = connection();
drop(commands);
timeout(Duration::from_secs(1), events.closed())
.await
.unwrap();
}
/// Oversized payloads fail the transport before entering the parser or caller's outgoing queue.
#[tokio::test]
async fn oversized_payloads_close_both_directions() {
let (input_connection, events, mut commands) = connection();
events
.send("x".repeat(MAX_MESSAGE_BYTES + 1))
.await
.unwrap();
assert!(
timeout(Duration::from_secs(1), input_connection.next_event())
.await
.unwrap()
.is_err()
);
assert_eq!(
timeout(Duration::from_secs(1), commands.recv())
.await
.unwrap(),
None
);
let (output_connection, _events, mut commands) = connection();
assert!(
output_connection
.writer()
.send_payload("x".repeat(MAX_MESSAGE_BYTES + 1))
.await
.is_err()
);
assert_eq!(
timeout(Duration::from_secs(1), commands.recv())
.await
.unwrap(),
None
);
}
/// A final transcript accepted before peer hangup must reach both the parser and transcript tail.
#[tokio::test(flavor = "current_thread")]
async fn queued_transcript_survives_peer_hangup() {
for _ in 0..64 {
let (connection, events, commands) = connection();
events
.try_send(r#"{"type":"input_transcript.added","item":{"text":"last words"}}"#.into())
.unwrap();
drop(events);
drop(commands);
assert_eq!(
timeout(Duration::from_secs(1), connection.next_event())
.await
.unwrap()
.unwrap(),
Some(
akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
akode_protocol::protocol::RealtimeTranscriptDelta {
delta: "last words".into()
}
)
)
);
assert_eq!(
connection.events().take_transcript_tail().await,
vec![akode_protocol::protocol::RealtimeTranscriptEntry {
role: "user".into(),
text: "last words".into()
}]
);
}
}
/// Explicit shutdown preserves a frame blocked on parser capacity and does not wait for an unsent permit.
#[tokio::test]
async fn input_stop_drains_backpressure_without_waiting_for_reserved_permit() {
let (events, incoming) = mpsc::channel(64);
let (outgoing, _commands) = mpsc::channel(1);
let connection = RealtimeWebsocketConnection::from_sideband(
RealtimeSidebandTransport { incoming, outgoing },
RealtimeEventParser::FramelessBidi,
);
let _permit = events.reserve().await.unwrap();
for _ in 0..63 {
events
.try_send(r#"{"type":"input_transcript.added","item":{"text":"tail"}}"#.into())
.unwrap();
}
timeout(Duration::from_secs(1), async {
while events.capacity() < 33 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
connection.writer().close_sideband_input();
for _ in 0..63 {
assert_eq!(
timeout(Duration::from_secs(1), connection.next_event())
.await
.unwrap()
.unwrap(),
Some(
akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
akode_protocol::protocol::RealtimeTranscriptDelta {
delta: "tail".into()
}
)
)
);
}
assert!(
timeout(Duration::from_secs(1), connection.next_event())
.await
.unwrap()
.is_err()
);
assert!(events.is_closed());
}

View File

@@ -0,0 +1,174 @@
//! Verifies fresh handshake credentials and rejection after the selected credentials change.
use super::*;
use crate::AuthError;
use crate::AuthHeadersFuture;
use crate::AuthProvider;
use crate::provider::RetryConfig;
use http::HeaderName;
use http::header::AUTHORIZATION;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicUsize;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use tokio_tungstenite::tungstenite::handshake::server::Response;
struct HandshakeAuth(AtomicUsize);
impl AuthProvider for HandshakeAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), AuthError> {
Err(AuthError::Build(
"authentication requires async header resolution".to_string(),
))
}
fn apply_auth_headers(&self, mut headers: HeaderMap) -> AuthHeadersFuture<'_> {
Box::pin(async move {
let attempt = self.0.fetch_add(1, Ordering::SeqCst) + 1;
headers.remove("x-openai-agent-assertion");
headers.insert(
AUTHORIZATION,
format!("AgentAssertion proof-{attempt}").parse().unwrap(),
);
Ok(headers)
})
}
}
fn client(base_url: String) -> RealtimeWebsocketClient {
RealtimeWebsocketClient::new(
Provider {
name: "test".to_string(),
base_url: base_url.clone(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(5),
},
akode_http_client::HttpClientFactory::new(
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
),
)
.with_webrtc_sideband_base_url(base_url)
}
fn session() -> RealtimeSessionConfig {
RealtimeSessionConfig {
instructions: String::new(),
initial_items: Vec::new(),
delegation_ack_filler: None,
model: None,
session_id: None,
event_parser: RealtimeEventParser::V1,
session_mode: RealtimeSessionMode::Conversational,
output_modality: RealtimeOutputModality::Audio,
voice: RealtimeVoice::Cedar,
}
}
#[tokio::test]
async fn sideband_retry_and_reconnect_replace_cached_auth_headers() -> anyhow::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let base_url = format!("http://{}/v1", listener.local_addr()?);
let server = tokio::spawn(async move {
let mut requests = Vec::new();
for attempt in 0..3 {
let (stream, _) = listener.accept().await.unwrap();
let result = accept_hdr_async(stream, |request: &Request, response: Response| {
requests.push(request.headers().clone());
if attempt == 0 {
Err(http::Response::builder().status(503).body(None).unwrap())
} else {
Ok(response)
}
})
.await;
if attempt == 0 {
assert!(result.is_err());
} else {
let mut stream = result.unwrap();
assert!(matches!(stream.next().await, Some(Ok(Message::Close(_)))));
}
}
requests
});
let client = client(base_url).with_auth(Arc::new(HandshakeAuth(AtomicUsize::new(0))));
let headers = HeaderMap::from_iter([
(
AUTHORIZATION,
HeaderValue::from_static("Bearer stale-credential"),
),
(
HeaderName::from_static("x-openai-agent-assertion"),
HeaderValue::from_static("stale-proof"),
),
(
HeaderName::from_static("x-request-context"),
HeaderValue::from_static("keep"),
),
]);
for _ in 0..2 {
let connection = tokio::time::timeout(
Duration::from_secs(5),
client.connect_existing_call_sideband(
session(),
"rtc_test",
headers.clone(),
HeaderMap::new(),
RealtimeTranscriptState::default(),
),
)
.await??;
connection.close().await?;
}
let requests = tokio::time::timeout(Duration::from_secs(5), server).await??;
assert_eq!(requests.len(), 3);
for (index, headers) in requests.iter().enumerate() {
assert_eq!(
headers[AUTHORIZATION],
format!("AgentAssertion proof-{}", index + 1)
);
assert!(!headers.contains_key("x-openai-agent-assertion"));
assert_eq!(headers["x-request-context"], "keep");
}
Ok(())
}
struct RejectedAuth;
impl AuthProvider for RejectedAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), AuthError> {
Err(AuthError::Build(
"authentication requires async header resolution".to_string(),
))
}
fn apply_auth_headers(&self, _headers: http::HeaderMap) -> AuthHeadersFuture<'_> {
Box::pin(async { Err(AuthError::Build("runtime revoked".to_string())) })
}
}
#[tokio::test]
async fn rejected_auth_prevents_the_websocket_request() -> anyhow::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let client =
client(format!("http://{}/v1", listener.local_addr()?)).with_auth(Arc::new(RejectedAuth));
let result = client
.connect(session(), HeaderMap::new(), HeaderMap::new())
.await;
assert!(result.is_err());
assert!(
tokio::time::timeout(Duration::from_millis(50), listener.accept())
.await
.is_err()
);
Ok(())
}

View File

@@ -0,0 +1,179 @@
use crate::endpoint::realtime_websocket::methods_frameless_bidi::delegation_context_append_message as frameless_delegation_context_append_message;
use crate::endpoint::realtime_websocket::methods_frameless_bidi::session_context_append_message as frameless_session_context_append_message;
use crate::endpoint::realtime_websocket::methods_frameless_bidi::session_json as frameless_session_json;
use crate::endpoint::realtime_websocket::methods_frameless_bidi::session_update_message as frameless_session_update_message;
use crate::endpoint::realtime_websocket::methods_v1::conversation_handoff_append_message as v1_conversation_handoff_append_message;
use crate::endpoint::realtime_websocket::methods_v1::conversation_item_create_message as v1_conversation_item_create_message;
use crate::endpoint::realtime_websocket::methods_v1::session_update_session as v1_session_update_session;
use crate::endpoint::realtime_websocket::methods_v1::websocket_intent as v1_websocket_intent;
use crate::endpoint::realtime_websocket::methods_v2::conversation_function_call_output_message as v2_conversation_function_call_output_message;
use crate::endpoint::realtime_websocket::methods_v2::conversation_item_create_message as v2_conversation_item_create_message;
use crate::endpoint::realtime_websocket::methods_v2::session_update_session as v2_session_update_session;
use crate::endpoint::realtime_websocket::methods_v2::websocket_intent as v2_websocket_intent;
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionConfig;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use serde_json::Result as JsonResult;
use serde_json::Value;
use serde_json::to_value;
pub(super) const REALTIME_AUDIO_SAMPLE_RATE: u32 = 24_000;
const AGENT_FINAL_MESSAGE_PREFIX: &str = "\"Agent Final Message\":\n\n";
pub(super) fn normalized_session_mode(
wire_adapter: RealtimeWireAdapter,
session_mode: RealtimeSessionMode,
) -> RealtimeSessionMode {
match wire_adapter {
RealtimeWireAdapter::V1 | RealtimeWireAdapter::FramelessBidi => {
RealtimeSessionMode::Conversational
}
RealtimeWireAdapter::RealtimeV2 => session_mode,
}
}
pub(super) fn conversation_item_create_message(
wire_adapter: RealtimeWireAdapter,
text: String,
role: ConversationTextRole,
context_append_channel: Option<RealtimeContextAppendChannel>,
) -> RealtimeOutboundMessage {
match wire_adapter {
RealtimeWireAdapter::V1 => v1_conversation_item_create_message(text, role),
RealtimeWireAdapter::FramelessBidi => {
frameless_session_context_append_message(text, context_append_channel)
}
RealtimeWireAdapter::RealtimeV2 => v2_conversation_item_create_message(text, role),
}
}
pub(super) fn conversation_handoff_append_message(
wire_adapter: RealtimeWireAdapter,
handoff_id: String,
output_text: String,
context_append_channel: Option<RealtimeContextAppendChannel>,
) -> RealtimeOutboundMessage {
match wire_adapter {
RealtimeWireAdapter::V1 => v1_conversation_handoff_append_message(handoff_id, output_text),
RealtimeWireAdapter::FramelessBidi => frameless_delegation_context_append_message(
handoff_id,
output_text,
context_append_channel,
),
RealtimeWireAdapter::RealtimeV2 => {
unreachable!("realtime v2 does not send conversation handoff output")
}
}
}
pub(super) fn standalone_handoff_message(
wire_adapter: RealtimeWireAdapter,
handoff_id: String,
output_text: String,
context_append_channel: Option<RealtimeContextAppendChannel>,
) -> RealtimeOutboundMessage {
match wire_adapter {
RealtimeWireAdapter::V1 => v1_conversation_handoff_append_message(handoff_id, output_text),
RealtimeWireAdapter::FramelessBidi => {
frameless_session_context_append_message(output_text, context_append_channel)
}
RealtimeWireAdapter::RealtimeV2 => {
unreachable!("realtime v2 does not send standalone handoff output")
}
}
}
pub(super) fn conversation_function_call_output_message(
wire_adapter: RealtimeWireAdapter,
call_id: String,
output_text: String,
context_append_channel: Option<RealtimeContextAppendChannel>,
) -> RealtimeOutboundMessage {
match wire_adapter {
RealtimeWireAdapter::V1 => v1_conversation_handoff_append_message(
call_id,
format!("{AGENT_FINAL_MESSAGE_PREFIX}{output_text}"),
),
RealtimeWireAdapter::FramelessBidi => frameless_delegation_context_append_message(
call_id,
output_text,
context_append_channel,
),
RealtimeWireAdapter::RealtimeV2 => {
v2_conversation_function_call_output_message(call_id, output_text)
}
}
}
pub(super) fn session_update_message(
wire_adapter: RealtimeWireAdapter,
instructions: String,
initial_items: Vec<ConversationTextParams>,
session_mode: RealtimeSessionMode,
output_modality: RealtimeOutputModality,
voice: RealtimeVoice,
delegation_ack_filler: Option<bool>,
) -> RealtimeOutboundMessage {
let session_mode = normalized_session_mode(wire_adapter, session_mode);
match wire_adapter {
RealtimeWireAdapter::V1 => RealtimeOutboundMessage::SessionUpdate {
session: v1_session_update_session(instructions, voice),
},
RealtimeWireAdapter::FramelessBidi => frameless_session_update_message(
instructions,
initial_items,
voice,
delegation_ack_filler,
),
RealtimeWireAdapter::RealtimeV2 => RealtimeOutboundMessage::SessionUpdate {
session: v2_session_update_session(instructions, session_mode, output_modality, voice),
},
}
}
pub fn session_update_session_json(config: RealtimeSessionConfig) -> JsonResult<Value> {
match config.event_parser {
RealtimeWireAdapter::V1 | RealtimeWireAdapter::RealtimeV2 => {
let mut session = match config.event_parser {
RealtimeWireAdapter::V1 => {
v1_session_update_session(config.instructions, config.voice)
}
RealtimeWireAdapter::RealtimeV2 => v2_session_update_session(
config.instructions,
config.session_mode,
config.output_modality,
config.voice,
),
RealtimeWireAdapter::FramelessBidi => unreachable!(),
};
session.id = config.session_id;
session.model = config.model;
to_value(session)
}
RealtimeWireAdapter::FramelessBidi => Ok(frameless_session_json(
config.model,
config.instructions,
config.initial_items,
config.voice,
config.delegation_ack_filler,
)),
}
}
pub(super) fn websocket_intent(wire_adapter: RealtimeWireAdapter) -> Option<&'static str> {
match wire_adapter {
RealtimeWireAdapter::V1 => v1_websocket_intent(),
RealtimeWireAdapter::FramelessBidi => None,
RealtimeWireAdapter::RealtimeV2 => v2_websocket_intent(),
}
}
#[cfg(test)]
#[path = "methods_common_tests.rs"]
mod tests;

View File

@@ -0,0 +1,150 @@
use super::conversation_function_call_output_message;
use super::conversation_handoff_append_message;
use super::session_update_message;
use super::standalone_handoff_message;
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use serde_json::to_value;
#[test]
fn frameless_session_update_encodes_explicit_delegation_ack_filler() {
for delegation_ack_filler in [false, true] {
let message = session_update_message(
RealtimeWireAdapter::FramelessBidi,
"instructions".to_string(),
Vec::new(),
RealtimeSessionMode::Conversational,
RealtimeOutputModality::Audio,
RealtimeVoice::Marin,
Some(delegation_ack_filler),
);
assert_eq!(
to_value(message).expect("frameless session update should serialize"),
json!({
"type": "session.update",
"session": {
"instructions": "instructions",
"audio": {
"output": {
"voice": "marin",
},
},
"delegation": {
"type": "client",
"ack_filler": delegation_ack_filler,
},
},
})
);
}
}
#[test]
fn context_append_channel_only_encodes_for_frameless_handoff_output() {
let legacy = conversation_handoff_append_message(
RealtimeWireAdapter::V1,
"handoff-123".to_string(),
"The result".to_string(),
Some(RealtimeContextAppendChannel::Commentary),
);
let frameless = conversation_handoff_append_message(
RealtimeWireAdapter::FramelessBidi,
"handoff-123".to_string(),
"The result".to_string(),
Some(RealtimeContextAppendChannel::Commentary),
);
assert_eq!(
to_value(legacy).expect("legacy handoff should serialize"),
json!({
"type": "conversation.handoff.append",
"handoff_id": "handoff-123",
"output_text": "The result",
})
);
assert_eq!(
to_value(frameless).expect("frameless handoff should serialize"),
json!({
"type": "delegation.context.append",
"delegation_item_id": "handoff-123",
"channel": "commentary",
"content": [{"type": "input_text", "text": "The result"}],
})
);
}
#[test]
fn standalone_handoff_uses_session_context_for_frameless() {
let legacy = standalone_handoff_message(
RealtimeWireAdapter::V1,
"codex".to_string(),
"Speak this".to_string(),
Some(RealtimeContextAppendChannel::Speakable),
);
let frameless = standalone_handoff_message(
RealtimeWireAdapter::FramelessBidi,
"codex".to_string(),
"Speak this".to_string(),
Some(RealtimeContextAppendChannel::Speakable),
);
assert_eq!(
to_value(legacy).expect("legacy standalone handoff should serialize"),
json!({
"type": "conversation.handoff.append",
"handoff_id": "codex",
"output_text": "Speak this",
})
);
assert_eq!(
to_value(frameless).expect("frameless standalone handoff should serialize"),
json!({
"type": "session.context.append",
"channel": "speakable",
"content": [{"type": "input_text", "text": "Speak this"}],
})
);
}
#[test]
fn completed_handoff_only_prefixes_v1_payload_text() {
for wire_adapter in [RealtimeWireAdapter::V1, RealtimeWireAdapter::FramelessBidi] {
let encoded = to_value(conversation_function_call_output_message(
wire_adapter,
"handoff-123".to_string(),
"Done".to_string(),
Some(RealtimeContextAppendChannel::Speakable),
))
.expect("handoff output should serialize");
let text = match wire_adapter {
RealtimeWireAdapter::V1 => &encoded["output_text"],
RealtimeWireAdapter::FramelessBidi => &encoded["content"][0]["text"],
RealtimeWireAdapter::RealtimeV2 => unreachable!(),
};
assert_eq!(
text,
&Value::String(match wire_adapter {
RealtimeWireAdapter::V1 => "\"Agent Final Message\":\n\nDone".to_string(),
RealtimeWireAdapter::FramelessBidi => "Done".to_string(),
RealtimeWireAdapter::RealtimeV2 => unreachable!(),
})
);
assert_eq!(
encoded.get("channel").cloned(),
match wire_adapter {
RealtimeWireAdapter::V1 => None,
RealtimeWireAdapter::FramelessBidi => {
Some(Value::String("speakable".to_string()))
}
RealtimeWireAdapter::RealtimeV2 => unreachable!(),
}
);
}
}

View File

@@ -0,0 +1,129 @@
use crate::endpoint::realtime_websocket::protocol::FramelessContentType;
use crate::endpoint::realtime_websocket::protocol::FramelessInputTextContent;
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use serde_json::Value;
use serde_json::json;
const CONTEXT_APPEND_MAX_BYTES: usize = 500;
pub(super) fn delegation_context_append_message(
delegation_item_id: String,
text: String,
channel: Option<RealtimeContextAppendChannel>,
) -> RealtimeOutboundMessage {
RealtimeOutboundMessage::DelegationContextAppend {
delegation_item_id,
channel,
content: input_text_content(text),
}
}
pub(super) fn session_context_append_message(
text: String,
channel: Option<RealtimeContextAppendChannel>,
) -> RealtimeOutboundMessage {
RealtimeOutboundMessage::SessionContextAppend {
channel,
content: input_text_content(text),
}
}
pub(super) fn session_update_message(
instructions: String,
initial_items: Vec<ConversationTextParams>,
voice: RealtimeVoice,
delegation_ack_filler: Option<bool>,
) -> RealtimeOutboundMessage {
RealtimeOutboundMessage::FramelessSessionUpdate {
session: session_json(
/*model*/ None,
instructions,
initial_items,
voice,
delegation_ack_filler,
),
}
}
pub(super) fn session_json(
model: Option<String>,
instructions: String,
initial_items: Vec<ConversationTextParams>,
voice: RealtimeVoice,
delegation_ack_filler: Option<bool>,
) -> Value {
let mut session = json!({
"instructions": instructions,
"audio": {
"output": {
"voice": voice,
},
},
"delegation": {
"type": "client",
},
});
if let Some(model) = model {
session["model"] = Value::String(model);
}
if let Some(delegation_ack_filler) = delegation_ack_filler {
session["delegation"]["ack_filler"] = Value::Bool(delegation_ack_filler);
}
if !initial_items.is_empty() {
session["initial_items"] = Value::Array(
initial_items
.into_iter()
.map(|item| {
let content_type = match item.role {
ConversationTextRole::User | ConversationTextRole::Developer => {
"input_text"
}
ConversationTextRole::Assistant => "output_text",
};
json!({
"type": "message",
"role": item.role,
"content": [{
"type": content_type,
"text": item.text,
}],
})
})
.collect(),
);
}
session
}
fn input_text_content(text: String) -> Vec<FramelessInputTextContent> {
vec![FramelessInputTextContent {
r#type: FramelessContentType::InputText,
text,
}]
}
pub(super) fn context_append_chunks(text: &str) -> Vec<String> {
if text.len() <= CONTEXT_APPEND_MAX_BYTES {
return vec![text.to_string()];
}
let mut chunks = Vec::new();
let mut start = 0;
while start < text.len() {
let mut end = (start + CONTEXT_APPEND_MAX_BYTES).min(text.len());
while end > start && !text.is_char_boundary(end) {
end -= 1;
}
chunks.push(text[start..end].to_string());
start = end;
}
chunks
}
#[cfg(test)]
#[path = "methods_frameless_bidi_tests.rs"]
mod tests;

View File

@@ -0,0 +1,102 @@
use super::CONTEXT_APPEND_MAX_BYTES;
use super::context_append_chunks;
use super::session_json;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn context_append_chunks_preserve_text_within_wire_limit() {
for text in ["a".repeat(1_201), "🙂".repeat(200)] {
let chunks = context_append_chunks(&text);
assert_eq!(chunks.concat(), text);
assert!(
chunks
.iter()
.all(|chunk| chunk.len() <= CONTEXT_APPEND_MAX_BYTES)
);
}
}
#[test]
fn session_json_omits_initial_items_when_empty() {
let session = session_json(
Some("gpt-live".to_string()),
"instructions".to_string(),
Vec::new(),
RealtimeVoice::Marin,
/*delegation_ack_filler*/ None,
);
assert_eq!(
session,
json!({
"model": "gpt-live",
"instructions": "instructions",
"audio": {
"output": {
"voice": "marin",
},
},
"delegation": {
"type": "client",
},
})
);
}
#[test]
fn session_json_encodes_role_bearing_initial_items() {
let session = session_json(
Some("gpt-live".to_string()),
"instructions".to_string(),
vec![
ConversationTextParams {
text: "Remember this.".to_string(),
role: ConversationTextRole::Developer,
},
ConversationTextParams {
text: "What do you remember?".to_string(),
role: ConversationTextRole::User,
},
ConversationTextParams {
text: "I remember.".to_string(),
role: ConversationTextRole::Assistant,
},
],
RealtimeVoice::Marin,
/*delegation_ack_filler*/ None,
);
assert_eq!(
session["initial_items"],
json!([
{
"type": "message",
"role": "developer",
"content": [{
"type": "input_text",
"text": "Remember this.",
}],
},
{
"type": "message",
"role": "user",
"content": [{
"type": "input_text",
"text": "What do you remember?",
}],
},
{
"type": "message",
"role": "assistant",
"content": [{
"type": "output_text",
"text": "I remember.",
}],
},
])
);
}

View File

@@ -0,0 +1,83 @@
use crate::endpoint::realtime_websocket::methods_common::REALTIME_AUDIO_SAMPLE_RATE;
use crate::endpoint::realtime_websocket::protocol::AudioFormatType;
use crate::endpoint::realtime_websocket::protocol::ConversationContentType;
use crate::endpoint::realtime_websocket::protocol::ConversationItemContent;
use crate::endpoint::realtime_websocket::protocol::ConversationItemPayload;
use crate::endpoint::realtime_websocket::protocol::ConversationItemType;
use crate::endpoint::realtime_websocket::protocol::ConversationMessageItem;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::SessionAudio;
use crate::endpoint::realtime_websocket::protocol::SessionAudioFormat;
use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use akode_protocol::protocol::ConversationTextRole;
pub(super) fn conversation_item_create_message(
text: String,
role: ConversationTextRole,
) -> RealtimeOutboundMessage {
let content_type = match role {
ConversationTextRole::Assistant => ConversationContentType::OutputText,
ConversationTextRole::User | ConversationTextRole::Developer => {
ConversationContentType::InputText
}
};
RealtimeOutboundMessage::ConversationItemCreate {
item: ConversationItemPayload::Message(ConversationMessageItem {
r#type: ConversationItemType::Message,
role,
content: vec![ConversationItemContent {
r#type: content_type,
text,
}],
}),
}
}
pub(super) fn conversation_handoff_append_message(
handoff_id: String,
output_text: String,
) -> RealtimeOutboundMessage {
RealtimeOutboundMessage::ConversationHandoffAppend {
handoff_id,
output_text,
}
}
pub(super) fn session_update_session(
instructions: String,
voice: RealtimeVoice,
) -> SessionUpdateSession {
SessionUpdateSession {
id: None,
r#type: SessionType::Quicksilver,
model: None,
instructions: Some(instructions),
output_modalities: None,
audio: SessionAudio {
input: SessionAudioInput {
format: SessionAudioFormat {
r#type: AudioFormatType::AudioPcm,
rate: REALTIME_AUDIO_SAMPLE_RATE,
},
noise_reduction: None,
transcription: None,
turn_detection: None,
},
output: Some(SessionAudioOutput {
format: None,
voice,
}),
},
tools: None,
tool_choice: None,
}
}
pub(super) fn websocket_intent() -> Option<&'static str> {
Some("quicksilver")
}

View File

@@ -0,0 +1,180 @@
use crate::endpoint::realtime_websocket::methods_common::REALTIME_AUDIO_SAMPLE_RATE;
use crate::endpoint::realtime_websocket::protocol::AudioFormatType;
use crate::endpoint::realtime_websocket::protocol::ConversationContentType;
use crate::endpoint::realtime_websocket::protocol::ConversationFunctionCallOutputItem;
use crate::endpoint::realtime_websocket::protocol::ConversationItemContent;
use crate::endpoint::realtime_websocket::protocol::ConversationItemPayload;
use crate::endpoint::realtime_websocket::protocol::ConversationItemType;
use crate::endpoint::realtime_websocket::protocol::ConversationMessageItem;
use crate::endpoint::realtime_websocket::protocol::NoiseReductionType;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::SessionAudio;
use crate::endpoint::realtime_websocket::protocol::SessionAudioFormat;
use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutputFormat;
use crate::endpoint::realtime_websocket::protocol::SessionFunctionTool;
use crate::endpoint::realtime_websocket::protocol::SessionInputAudioTranscription;
use crate::endpoint::realtime_websocket::protocol::SessionNoiseReduction;
use crate::endpoint::realtime_websocket::protocol::SessionToolType;
use crate::endpoint::realtime_websocket::protocol::SessionTurnDetection;
use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use crate::endpoint::realtime_websocket::protocol::TurnDetectionType;
use akode_protocol::protocol::ConversationTextRole;
use serde_json::json;
const REALTIME_V2_OUTPUT_MODALITY_AUDIO: &str = "audio";
const REALTIME_V2_OUTPUT_MODALITY_TEXT: &str = "text";
const REALTIME_V2_TOOL_CHOICE: &str = "auto";
const REALTIME_V2_BACKGROUND_AGENT_TOOL_NAME: &str = "background_agent";
const REALTIME_V2_BACKGROUND_AGENT_TOOL_DESCRIPTION: &str = "Send a user request to the background agent. Use this as the default action. Do not rephrase the user's ask or rewrite it in your own words; pass along the user's own words. If the background agent is idle, this starts a new task and returns the final result to the user. If the background agent is already working on a task, this sends the request as guidance to steer that previous task. If the user asks to do something next, later, after this, or once current work finishes, call this tool so the work is actually queued instead of merely promising to do it later.";
const REALTIME_V2_SILENCE_TOOL_NAME: &str = "remain_silent";
const REALTIME_V2_SILENCE_TOOL_DESCRIPTION: &str = "Call this when the best response is to say nothing. Use it instead of speaking after hidden system/control messages, after background agent updates in silent modes, or whenever acknowledging aloud would be distracting. This tool has no user-visible effect.";
const REALTIME_V2_INPUT_TRANSCRIPTION_MODEL: &str = "gpt-4o-mini-transcribe";
pub(super) fn conversation_item_create_message(
text: String,
role: ConversationTextRole,
) -> RealtimeOutboundMessage {
let content_type = match role {
ConversationTextRole::Assistant => ConversationContentType::OutputText,
ConversationTextRole::User | ConversationTextRole::Developer => {
ConversationContentType::InputText
}
};
RealtimeOutboundMessage::ConversationItemCreate {
item: ConversationItemPayload::Message(ConversationMessageItem {
r#type: ConversationItemType::Message,
role,
content: vec![ConversationItemContent {
r#type: content_type,
text,
}],
}),
}
}
pub(super) fn conversation_function_call_output_message(
call_id: String,
output_text: String,
) -> RealtimeOutboundMessage {
RealtimeOutboundMessage::ConversationItemCreate {
item: ConversationItemPayload::FunctionCallOutput(ConversationFunctionCallOutputItem {
r#type: ConversationItemType::FunctionCallOutput,
call_id,
output: output_text,
}),
}
}
pub(super) fn session_update_session(
instructions: String,
session_mode: RealtimeSessionMode,
output_modality: RealtimeOutputModality,
voice: RealtimeVoice,
) -> SessionUpdateSession {
match session_mode {
RealtimeSessionMode::Conversational => SessionUpdateSession {
id: None,
r#type: SessionType::Realtime,
model: None,
instructions: Some(instructions),
output_modalities: Some(vec![output_modality_value(output_modality).to_string()]),
audio: SessionAudio {
input: SessionAudioInput {
format: SessionAudioFormat {
r#type: AudioFormatType::AudioPcm,
rate: REALTIME_AUDIO_SAMPLE_RATE,
},
noise_reduction: Some(SessionNoiseReduction {
r#type: NoiseReductionType::NearField,
}),
transcription: Some(SessionInputAudioTranscription {
model: REALTIME_V2_INPUT_TRANSCRIPTION_MODEL.to_string(),
}),
turn_detection: Some(SessionTurnDetection {
r#type: TurnDetectionType::ServerVad,
interrupt_response: true,
create_response: true,
silence_duration_ms: 500,
}),
},
output: Some(SessionAudioOutput {
format: Some(SessionAudioOutputFormat {
r#type: AudioFormatType::AudioPcm,
rate: REALTIME_AUDIO_SAMPLE_RATE,
}),
voice,
}),
},
tools: Some(vec![
SessionFunctionTool {
r#type: SessionToolType::Function,
name: REALTIME_V2_BACKGROUND_AGENT_TOOL_NAME.to_string(),
description: REALTIME_V2_BACKGROUND_AGENT_TOOL_DESCRIPTION.to_string(),
parameters: json!({
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "The user request to delegate to the background agent."
}
},
"required": ["prompt"],
"additionalProperties": false
}),
},
SessionFunctionTool {
r#type: SessionToolType::Function,
name: REALTIME_V2_SILENCE_TOOL_NAME.to_string(),
description: REALTIME_V2_SILENCE_TOOL_DESCRIPTION.to_string(),
parameters: json!({
"type": "object",
"properties": {},
"additionalProperties": false
}),
},
]),
tool_choice: Some(REALTIME_V2_TOOL_CHOICE.to_string()),
},
RealtimeSessionMode::Transcription => SessionUpdateSession {
id: None,
r#type: SessionType::Transcription,
model: None,
instructions: None,
output_modalities: None,
audio: SessionAudio {
input: SessionAudioInput {
format: SessionAudioFormat {
r#type: AudioFormatType::AudioPcm,
rate: REALTIME_AUDIO_SAMPLE_RATE,
},
noise_reduction: None,
transcription: Some(SessionInputAudioTranscription {
model: REALTIME_V2_INPUT_TRANSCRIPTION_MODEL.to_string(),
}),
turn_detection: None,
},
output: None,
},
tools: None,
tool_choice: None,
},
}
}
fn output_modality_value(output_modality: RealtimeOutputModality) -> &'static str {
match output_modality {
RealtimeOutputModality::Text => REALTIME_V2_OUTPUT_MODALITY_TEXT,
RealtimeOutputModality::Audio => REALTIME_V2_OUTPUT_MODALITY_AUDIO,
}
}
pub(super) fn websocket_intent() -> Option<&'static str> {
None
}

View File

@@ -0,0 +1,22 @@
pub(crate) mod methods;
mod methods_common;
mod methods_frameless_bidi;
mod methods_v1;
mod methods_v2;
pub(crate) mod protocol;
mod protocol_common;
mod protocol_frameless_bidi;
mod protocol_v1;
mod protocol_v2;
pub use methods::RealtimeTranscriptState;
pub use methods::RealtimeWebsocketClient;
pub use methods::RealtimeWebsocketConnection;
pub use methods::RealtimeWebsocketEvents;
pub use methods::RealtimeWebsocketWriter;
pub use methods_common::session_update_session_json;
pub use protocol::RealtimeContextAppendChannel;
pub use protocol::RealtimeEventParser;
pub use protocol::RealtimeOutputModality;
pub use protocol::RealtimeSessionConfig;
pub use protocol::RealtimeSessionMode;

View File

@@ -0,0 +1,272 @@
use crate::endpoint::realtime_websocket::protocol_frameless_bidi::parse_frameless_bidi_event;
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
use crate::endpoint::realtime_websocket::protocol_v2::parse_realtime_event_v2;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
pub use akode_protocol::protocol::RealtimeAudioFrame;
pub use akode_protocol::protocol::RealtimeEvent;
pub use akode_protocol::protocol::RealtimeOutputModality;
pub use akode_protocol::protocol::RealtimeTranscriptEntry;
pub use akode_protocol::protocol::RealtimeVoice;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RealtimeEventParser {
V1,
FramelessBidi,
RealtimeV2,
}
pub type RealtimeWireAdapter = RealtimeEventParser;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RealtimeSessionMode {
Conversational,
Transcription,
}
/// Selects the semantic stream used for Frameless Bidi context appends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RealtimeContextAppendChannel {
Speakable,
Commentary,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RealtimeSessionConfig {
pub instructions: String,
pub initial_items: Vec<ConversationTextParams>,
pub delegation_ack_filler: Option<bool>,
pub model: Option<String>,
pub session_id: Option<String>,
pub event_parser: RealtimeEventParser,
pub session_mode: RealtimeSessionMode,
pub output_modality: RealtimeOutputModality,
pub voice: RealtimeVoice,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub(super) enum RealtimeOutboundMessage {
#[serde(rename = "input_audio_buffer.append")]
InputAudioBufferAppend { audio: String },
#[serde(rename = "conversation.handoff.append")]
ConversationHandoffAppend {
handoff_id: String,
output_text: String,
},
#[serde(rename = "input_audio.append")]
InputAudioAppend { audio: String },
#[serde(rename = "delegation.context.append")]
DelegationContextAppend {
delegation_item_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
channel: Option<RealtimeContextAppendChannel>,
content: Vec<FramelessInputTextContent>,
},
#[serde(rename = "session.context.append")]
SessionContextAppend {
#[serde(skip_serializing_if = "Option::is_none")]
channel: Option<RealtimeContextAppendChannel>,
content: Vec<FramelessInputTextContent>,
},
#[serde(rename = "session.close")]
SessionClose,
#[serde(rename = "response.create")]
ResponseCreate,
#[serde(rename = "session.update")]
SessionUpdate { session: SessionUpdateSession },
#[serde(rename = "session.update")]
FramelessSessionUpdate { session: Value },
#[serde(rename = "conversation.item.create")]
ConversationItemCreate { item: ConversationItemPayload },
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct FramelessInputTextContent {
#[serde(rename = "type")]
pub(super) r#type: FramelessContentType,
pub(super) text: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum FramelessContentType {
InputText,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionUpdateSession {
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) id: Option<String>,
#[serde(rename = "type")]
pub(super) r#type: SessionType,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) instructions: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) output_modalities: Option<Vec<String>>,
pub(super) audio: SessionAudio,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) tools: Option<Vec<SessionFunctionTool>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) tool_choice: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SessionType {
Quicksilver,
Realtime,
Transcription,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudio {
pub(super) input: SessionAudioInput,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) output: Option<SessionAudioOutput>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioInput {
pub(super) format: SessionAudioFormat,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) noise_reduction: Option<SessionNoiseReduction>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) transcription: Option<SessionInputAudioTranscription>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) turn_detection: Option<SessionTurnDetection>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionInputAudioTranscription {
pub(super) model: String,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioFormat {
#[serde(rename = "type")]
pub(super) r#type: AudioFormatType,
pub(super) rate: u32,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub(super) enum AudioFormatType {
#[serde(rename = "audio/pcm")]
AudioPcm,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) format: Option<SessionAudioOutputFormat>,
pub(super) voice: RealtimeVoice,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionNoiseReduction {
#[serde(rename = "type")]
pub(super) r#type: NoiseReductionType,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum NoiseReductionType {
NearField,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionTurnDetection {
#[serde(rename = "type")]
pub(super) r#type: TurnDetectionType,
pub(super) interrupt_response: bool,
pub(super) create_response: bool,
pub(super) silence_duration_ms: u32,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum TurnDetectionType {
ServerVad,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioOutputFormat {
#[serde(rename = "type")]
pub(super) r#type: AudioFormatType,
pub(super) rate: u32,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationMessageItem {
#[serde(rename = "type")]
pub(super) r#type: ConversationItemType,
pub(super) role: ConversationTextRole,
pub(super) content: Vec<ConversationItemContent>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum ConversationItemType {
Message,
FunctionCallOutput,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub(super) enum ConversationItemPayload {
Message(ConversationMessageItem),
FunctionCallOutput(ConversationFunctionCallOutputItem),
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationFunctionCallOutputItem {
#[serde(rename = "type")]
pub(super) r#type: ConversationItemType,
pub(super) call_id: String,
pub(super) output: String,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationItemContent {
#[serde(rename = "type")]
pub(super) r#type: ConversationContentType,
pub(super) text: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum ConversationContentType {
InputText,
OutputText,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionFunctionTool {
#[serde(rename = "type")]
pub(super) r#type: SessionToolType,
pub(super) name: String,
pub(super) description: String,
pub(super) parameters: Value,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SessionToolType {
Function,
}
pub(super) fn parse_realtime_event(
payload: &str,
event_parser: RealtimeEventParser,
) -> Option<RealtimeEvent> {
match event_parser {
RealtimeEventParser::V1 => parse_realtime_event_v1(payload),
RealtimeEventParser::FramelessBidi => parse_frameless_bidi_event(payload),
RealtimeEventParser::RealtimeV2 => parse_realtime_event_v2(payload),
}
}

View File

@@ -0,0 +1,83 @@
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_protocol::protocol::RealtimeTranscriptDone;
use serde_json::Value;
use tracing::debug;
pub(super) fn parse_realtime_payload(payload: &str, parser_name: &str) -> Option<(Value, String)> {
let parsed: Value = match serde_json::from_str(payload) {
Ok(message) => message,
Err(err) => {
debug!("failed to parse {parser_name} event: {err}, data: {payload}");
return None;
}
};
let message_type = match parsed.get("type").and_then(Value::as_str) {
Some(message_type) => message_type.to_string(),
None => {
debug!("received {parser_name} event without type field: {payload}");
return None;
}
};
Some((parsed, message_type))
}
pub(super) fn parse_session_updated_event(parsed: &Value) -> Option<RealtimeEvent> {
let session_id = parsed
.get("session")
.and_then(Value::as_object)
.and_then(|session| session.get("id"))
.and_then(Value::as_str)
.map(str::to_string)?;
let instructions = parsed
.get("session")
.and_then(Value::as_object)
.and_then(|session| session.get("instructions"))
.and_then(Value::as_str)
.map(str::to_string);
Some(RealtimeEvent::SessionUpdated {
realtime_session_id: session_id,
instructions,
})
}
pub(super) fn parse_transcript_delta_event(
parsed: &Value,
field: &str,
) -> Option<RealtimeTranscriptDelta> {
parsed
.get(field)
.and_then(Value::as_str)
.map(str::to_string)
.map(|delta| RealtimeTranscriptDelta { delta })
}
pub(super) fn parse_transcript_done_event(
parsed: &Value,
field: &str,
) -> Option<RealtimeTranscriptDone> {
parsed
.get(field)
.and_then(Value::as_str)
.map(str::to_string)
.map(|text| RealtimeTranscriptDone { text })
}
pub(super) fn parse_error_event(parsed: &Value) -> Option<RealtimeEvent> {
parsed
.get("message")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
parsed
.get("error")
.and_then(Value::as_object)
.and_then(|error| error.get("message"))
.and_then(Value::as_str)
.map(str::to_string)
})
.or_else(|| parsed.get("error").map(ToString::to_string))
.map(RealtimeEvent::Error)
}

View File

@@ -0,0 +1,99 @@
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use akode_protocol::protocol::RealtimeAudioFrame;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_protocol::protocol::RealtimeTranscriptDone;
use serde_json::Value;
use tracing::debug;
const DEFAULT_AUDIO_SAMPLE_RATE: u32 = 24_000;
const DEFAULT_AUDIO_CHANNELS: u16 = 1;
pub(super) fn parse_frameless_bidi_event(payload: &str) -> Option<RealtimeEvent> {
let (parsed, message_type) = parse_realtime_payload(payload, "frameless bidi")?;
match message_type.as_str() {
"session.started" | "session.updated" => parse_session_updated_event(&parsed),
"output_audio.delta" => parse_output_audio_delta(&parsed),
"input_transcript.added" => {
parse_transcript_item(&parsed).map(RealtimeEvent::InputTranscriptDelta)
}
"output_transcript.added" => {
parse_transcript_item(&parsed).map(RealtimeEvent::OutputTranscriptDelta)
}
"turn.done" => parse_turn_done(&parsed),
"delegation.created" => parse_delegation_created(&parsed),
"error" => parse_error_event(&parsed),
_ => {
debug!(
"received unsupported frameless bidi event type: {message_type}, data: {payload}"
);
None
}
}
}
fn parse_output_audio_delta(parsed: &Value) -> Option<RealtimeEvent> {
Some(RealtimeEvent::AudioOut(RealtimeAudioFrame {
data: parsed.get("audio").and_then(Value::as_str)?.to_string(),
sample_rate: DEFAULT_AUDIO_SAMPLE_RATE,
num_channels: DEFAULT_AUDIO_CHANNELS,
samples_per_channel: None,
item_id: None,
}))
}
fn parse_transcript_item(parsed: &Value) -> Option<RealtimeTranscriptDelta> {
parsed
.get("item")
.and_then(Value::as_object)
.and_then(|item| item.get("text"))
.and_then(Value::as_str)
.map(str::to_string)
.map(|delta| RealtimeTranscriptDelta { delta })
}
fn parse_turn_done(parsed: &Value) -> Option<RealtimeEvent> {
let turn = parsed.get("turn")?.as_object()?;
let role = turn.get("role").and_then(Value::as_str)?;
let text = turn
.get("transcript")
.and_then(Value::as_str)
.map(str::to_string)?;
let done = RealtimeTranscriptDone { text };
match role {
"user" => Some(RealtimeEvent::InputTranscriptDone(done)),
"assistant" => Some(RealtimeEvent::OutputTranscriptDone(done)),
_ => None,
}
}
fn parse_delegation_created(parsed: &Value) -> Option<RealtimeEvent> {
let item = parsed.get("item")?.as_object()?;
if item.get("type").and_then(Value::as_str) != Some("delegation")
|| item.get("target").and_then(Value::as_str) != Some("client")
{
return None;
}
let item_id = item.get("id").and_then(Value::as_str)?.to_string();
let input_transcript = item
.get("content")
.and_then(Value::as_array)?
.iter()
.filter(|content| content.get("type").and_then(Value::as_str) == Some("input_text"))
.filter_map(|content| content.get("text").and_then(Value::as_str))
.collect::<String>();
Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
handoff_id: item_id.clone(),
item_id,
input_transcript,
active_transcript: Vec::new(),
}))
}
#[cfg(test)]
#[path = "protocol_frameless_bidi_tests.rs"]
mod tests;

View File

@@ -0,0 +1,64 @@
use super::parse_frameless_bidi_event;
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
#[test]
fn legacy_and_frameless_delegations_decode_to_the_same_handoff() {
let expected = Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
handoff_id: "handoff-123".to_string(),
item_id: "handoff-123".to_string(),
input_transcript: "check the weather".to_string(),
active_transcript: Vec::new(),
}));
let legacy = r#"{
"type": "conversation.handoff.requested",
"handoff_id": "handoff-123",
"item_id": "handoff-123",
"input_transcript": "check the weather"
}"#;
let frameless = r#"{
"type": "delegation.created",
"offset_ms": 1000,
"item": {
"id": "handoff-123",
"type": "delegation",
"target": "client",
"content": [{"type": "input_text", "text": "check the weather"}]
}
}"#;
assert_eq!(parse_realtime_event_v1(legacy), expected);
assert_eq!(parse_frameless_bidi_event(frameless), expected);
}
#[test]
fn frameless_transcript_and_audio_events_reuse_existing_internal_events() {
let input = r#"{
"type": "input_transcript.added",
"item": {"id": "input-1", "type": "input_transcript", "text": "hello"}
}"#;
let done = r#"{
"type": "turn.done",
"turn": {"id": "turn-1", "role": "user", "transcript": "hello"}
}"#;
let audio = r#"{
"type": "output_audio.delta",
"audio": "AAE=",
"start_ms": 0,
"end_ms": 100
}"#;
assert!(matches!(
parse_frameless_bidi_event(input),
Some(RealtimeEvent::InputTranscriptDelta(_))
));
assert!(matches!(
parse_frameless_bidi_event(done),
Some(RealtimeEvent::InputTranscriptDone(_))
));
assert!(matches!(
parse_frameless_bidi_event(audio),
Some(RealtimeEvent::AudioOut(_))
));
}

View File

@@ -0,0 +1,99 @@
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
use akode_protocol::protocol::RealtimeAudioFrame;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
use serde_json::Value;
use tracing::debug;
pub(super) fn parse_realtime_event_v1(payload: &str) -> Option<RealtimeEvent> {
let (parsed, message_type) = parse_realtime_payload(payload, "realtime v1")?;
match message_type.as_str() {
"session.updated" => parse_session_updated_event(&parsed),
"conversation.output_audio.delta" => {
let data = parsed
.get("delta")
.and_then(Value::as_str)
.or_else(|| parsed.get("data").and_then(Value::as_str))
.map(str::to_string)?;
let sample_rate = parsed
.get("sample_rate")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())?;
let num_channels = parsed
.get("channels")
.or_else(|| parsed.get("num_channels"))
.and_then(Value::as_u64)
.and_then(|value| u16::try_from(value).ok())?;
Some(RealtimeEvent::AudioOut(RealtimeAudioFrame {
data,
sample_rate,
num_channels,
samples_per_channel: parsed
.get("samples_per_channel")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok()),
item_id: None,
}))
}
"conversation.input_transcript.delta"
| "conversation.item.input_audio_transcription.delta" => {
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::InputTranscriptDelta)
}
"conversation.input_transcript.turn_marked"
| "conversation.item.input_audio_transcription.completed" => {
parse_transcript_done_event(&parsed, "transcript")
.map(RealtimeEvent::InputTranscriptDone)
}
"conversation.output_transcript.delta"
| "response.output_text.delta"
| "response.output_audio_transcript.delta" => {
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::OutputTranscriptDelta)
}
"response.output_audio_transcript.done" => {
parse_transcript_done_event(&parsed, "transcript")
.map(RealtimeEvent::OutputTranscriptDone)
}
"conversation.item.added" => parsed
.get("item")
.cloned()
.map(RealtimeEvent::ConversationItemAdded),
"conversation.item.done" => parse_conversation_item_done_event(&parsed),
"conversation.handoff.requested" => {
let handoff_id = parsed
.get("handoff_id")
.and_then(Value::as_str)
.map(str::to_string)?;
let item_id = parsed
.get("item_id")
.and_then(Value::as_str)
.map(str::to_string)?;
let input_transcript = parsed
.get("input_transcript")
.and_then(Value::as_str)
.map(str::to_string)?;
Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
handoff_id,
item_id,
input_transcript,
active_transcript: Vec::new(),
}))
}
"error" => parse_error_event(&parsed),
_ => {
debug!("received unsupported realtime v1 event type: {message_type}, data: {payload}");
None
}
}
}
fn parse_conversation_item_done_event(parsed: &Value) -> Option<RealtimeEvent> {
let item = parsed.get("item")?.as_object()?;
item.get("id")
.and_then(Value::as_str)
.map(str::to_string)
.map(|item_id| RealtimeEvent::ConversationItemDone { item_id })
}

View File

@@ -0,0 +1,210 @@
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
use akode_protocol::protocol::RealtimeAudioFrame;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
use akode_protocol::protocol::RealtimeNoopRequested;
use akode_protocol::protocol::RealtimeResponseCancelled;
use akode_protocol::protocol::RealtimeResponseCreated;
use akode_protocol::protocol::RealtimeResponseDone;
use serde_json::Map as JsonMap;
use serde_json::Value;
use tracing::debug;
const BACKGROUND_AGENT_TOOL_NAME: &str = "background_agent";
const SILENCE_TOOL_NAME: &str = "remain_silent";
const DEFAULT_AUDIO_SAMPLE_RATE: u32 = 24_000;
const DEFAULT_AUDIO_CHANNELS: u16 = 1;
const TOOL_ARGUMENT_KEYS: [&str; 5] = ["input_transcript", "input", "text", "prompt", "query"];
pub(super) fn parse_realtime_event_v2(payload: &str) -> Option<RealtimeEvent> {
let (parsed, message_type) = parse_realtime_payload(payload, "realtime v2")?;
match message_type.as_str() {
"session.updated" => parse_session_updated_event(&parsed),
"response.output_audio.delta" | "response.audio.delta" => {
parse_output_audio_delta_event(&parsed)
}
"conversation.item.input_audio_transcription.delta" => {
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::InputTranscriptDelta)
}
"conversation.item.input_audio_transcription.completed" => {
parse_transcript_done_event(&parsed, "transcript")
.map(RealtimeEvent::InputTranscriptDone)
}
"response.output_text.delta" | "response.output_audio_transcript.delta" => {
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::OutputTranscriptDelta)
}
"response.output_text.done" => {
parse_transcript_done_event(&parsed, "text").map(RealtimeEvent::OutputTranscriptDone)
}
"response.output_audio_transcript.done" => {
parse_transcript_done_event(&parsed, "transcript")
.map(RealtimeEvent::OutputTranscriptDone)
}
"input_audio_buffer.speech_started" => Some(RealtimeEvent::InputAudioSpeechStarted(
RealtimeInputAudioSpeechStarted {
item_id: parsed
.get("item_id")
.and_then(Value::as_str)
.map(str::to_string),
},
)),
"conversation.item.added" | "conversation.item.created" => parsed
.get("item")
.cloned()
.map(RealtimeEvent::ConversationItemAdded),
"conversation.item.done" => parse_conversation_item_done_event(&parsed),
"response.created" => Some(RealtimeEvent::ResponseCreated(RealtimeResponseCreated {
response_id: parse_response_event_response_id(&parsed),
})),
"response.cancelled" => Some(RealtimeEvent::ResponseCancelled(
RealtimeResponseCancelled {
response_id: parse_response_event_response_id(&parsed),
},
)),
"response.done" => Some(RealtimeEvent::ResponseDone(RealtimeResponseDone {
response_id: parse_response_event_response_id(&parsed),
})),
"error" => parse_error_event(&parsed),
_ => {
debug!("received unsupported realtime v2 event type: {message_type}, data: {payload}");
None
}
}
}
fn parse_response_event_response_id(parsed: &Value) -> Option<String> {
parsed
.get("response")
.and_then(Value::as_object)
.and_then(|response| response.get("id"))
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
parsed
.get("response_id")
.and_then(Value::as_str)
.map(str::to_string)
})
}
fn parse_output_audio_delta_event(parsed: &Value) -> Option<RealtimeEvent> {
let data = parsed
.get("delta")
.and_then(Value::as_str)
.map(str::to_string)?;
let sample_rate = parsed
.get("sample_rate")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())
.unwrap_or(DEFAULT_AUDIO_SAMPLE_RATE);
let num_channels = parsed
.get("channels")
.or_else(|| parsed.get("num_channels"))
.and_then(Value::as_u64)
.and_then(|value| u16::try_from(value).ok())
.unwrap_or(DEFAULT_AUDIO_CHANNELS);
Some(RealtimeEvent::AudioOut(RealtimeAudioFrame {
data,
sample_rate,
num_channels,
samples_per_channel: parsed
.get("samples_per_channel")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok()),
item_id: parsed
.get("item_id")
.and_then(Value::as_str)
.map(str::to_string),
}))
}
fn parse_conversation_item_done_event(parsed: &Value) -> Option<RealtimeEvent> {
let item = parsed.get("item")?.as_object()?;
if let Some(handoff) = parse_handoff_requested_event(item) {
return Some(handoff);
}
if let Some(noop) = parse_noop_requested_event(item) {
return Some(noop);
}
item.get("id")
.and_then(Value::as_str)
.map(str::to_string)
.map(|item_id| RealtimeEvent::ConversationItemDone { item_id })
}
fn parse_handoff_requested_event(item: &JsonMap<String, Value>) -> Option<RealtimeEvent> {
let item_type = item.get("type").and_then(Value::as_str);
let item_name = item.get("name").and_then(Value::as_str);
if item_type != Some("function_call") || item_name != Some(BACKGROUND_AGENT_TOOL_NAME) {
return None;
}
let call_id = item
.get("call_id")
.and_then(Value::as_str)
.or_else(|| item.get("id").and_then(Value::as_str))?;
let item_id = item
.get("id")
.and_then(Value::as_str)
.unwrap_or(call_id)
.to_string();
let arguments = item.get("arguments").and_then(Value::as_str).unwrap_or("");
Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
handoff_id: call_id.to_string(),
item_id,
input_transcript: extract_input_transcript(arguments),
active_transcript: Vec::new(),
}))
}
fn parse_noop_requested_event(item: &JsonMap<String, Value>) -> Option<RealtimeEvent> {
let item_type = item.get("type").and_then(Value::as_str);
let item_name = item.get("name").and_then(Value::as_str);
if item_type != Some("function_call") || item_name != Some(SILENCE_TOOL_NAME) {
return None;
}
let call_id = item
.get("call_id")
.and_then(Value::as_str)
.or_else(|| item.get("id").and_then(Value::as_str))?;
let item_id = item
.get("id")
.and_then(Value::as_str)
.unwrap_or(call_id)
.to_string();
Some(RealtimeEvent::NoopRequested(RealtimeNoopRequested {
call_id: call_id.to_string(),
item_id,
}))
}
fn extract_input_transcript(arguments: &str) -> String {
if arguments.is_empty() {
return String::new();
}
if let Ok(arguments_json) = serde_json::from_str::<Value>(arguments)
&& let Some(arguments_object) = arguments_json.as_object()
{
for key in TOOL_ARGUMENT_KEYS {
if let Some(value) = arguments_object.get(key).and_then(Value::as_str) {
let trimmed = value.trim();
if !trimmed.is_empty() {
return trimmed.to_string();
}
}
}
}
arguments.to_string()
}

View File

@@ -0,0 +1,131 @@
//! V3 transcript reconciliation across interleaved speakers, reconnects, and turn boundaries.
use super::*;
use akode_protocol::protocol::RealtimeTranscriptDone;
use pretty_assertions::assert_eq;
fn events(transcript_state: RealtimeTranscriptState) -> RealtimeWebsocketEvents {
let (_, rx_message) = async_channel::unbounded();
RealtimeWebsocketEvents {
rx_message,
pending_events: Arc::new(Mutex::new(VecDeque::new())),
transcript_state,
event_parser: RealtimeEventParser::FramelessBidi,
is_closed: Arc::new(AtomicBool::new(false)),
}
}
fn entry(role: &str, text: &str) -> RealtimeTranscriptEntry {
RealtimeTranscriptEntry {
role: role.to_string(),
text: text.to_string(),
}
}
async fn observe(events: &RealtimeWebsocketEvents, mut event: RealtimeEvent) {
let original = event.clone();
events.update_active_transcript(&mut event).await;
assert_eq!(
event, original,
"live transcript events must pass through unchanged"
);
}
#[tokio::test]
async fn interleaved_transcripts_reconcile_across_reconnect_in_either_completion_order() {
for assistant_finishes_first in [false, true] {
let state = RealtimeTranscriptState::default();
let first = events(state.clone());
for event in [
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
delta: "What can ".into(),
}),
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
delta: "A bunch ".into(),
}),
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
delta: "you do?".into(),
}),
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
delta: "of stuff".into(),
}),
] {
observe(&first, event).await;
}
let reconnected = events(state);
let user = RealtimeEvent::InputTranscriptDone(RealtimeTranscriptDone {
text: "What can you do?".into(),
});
let assistant = RealtimeEvent::OutputTranscriptDone(RealtimeTranscriptDone {
text: "A bunch of stuff, including coding.".into(),
});
let finals = if assistant_finishes_first {
[assistant, user]
} else {
[user, assistant]
};
for event in finals {
observe(&reconnected, event).await;
}
assert_eq!(
reconnected.take_transcript_tail().await,
vec![
entry("user", "What can you do?"),
entry("assistant", "A bunch of stuff, including coding."),
]
);
assert_eq!(reconnected.take_transcript_tail().await, vec![]);
}
}
#[tokio::test]
async fn completed_utterances_keep_repeated_speech_and_final_only_turns_distinct() {
let events = events(RealtimeTranscriptState::default());
for role in ["user", "assistant"] {
for with_delta in [true, true, false] {
if with_delta {
let delta = RealtimeTranscriptDelta {
delta: "Again".into(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDelta(delta)
} else {
RealtimeEvent::OutputTranscriptDelta(delta)
},
)
.await;
}
let done = RealtimeTranscriptDone {
text: "Again.".into(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDone(done)
} else {
RealtimeEvent::OutputTranscriptDone(done)
},
)
.await;
// An empty delta must not reopen the utterance we just completed.
let empty = RealtimeTranscriptDelta {
delta: String::new(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDelta(empty)
} else {
RealtimeEvent::OutputTranscriptDelta(empty)
},
)
.await;
}
assert_eq!(
events.take_transcript_tail().await,
vec![entry(role, "Again."); 3]
);
}
}