#[cfg(test)]
mod tests;
use super::protection::{Protection, follows_published, protection};
use crate::secret::{ESCAPE_MARKERS, Inventory, StreamRedactor};
use bytes::Bytes;
use futures_util::StreamExt;
use rig_core::{
http_client::{
HttpClientExt, LazyBody, MultipartForm, Request, Response, Result as HttpResult,
StreamingResponse, framing::SseFramer,
},
message::{AssistantContent, ReasoningContent},
streaming::{Item, StreamEvent},
};
use serde::Deserialize;
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
time::Duration,
};
pub const CADENCE: Duration = Duration::from_millis(100);
const FRAME_BYTES: usize = 256 * 1024;
const PENDING_BYTES: usize = 64 * 1024;
const LIVE_DISPLAY_BYTES: usize = 1024 * 1024;
const READY_BYTES: usize = PENDING_BYTES / 2;
const FRAME_SLICE: usize = 4096;
const SUMMARY_PARTS: usize = 256;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Block {
Attempt,
Opaque(String),
Text(usize),
Summary { item: String, index: usize },
}
impl Block {
pub fn text(part: usize) -> Self {
Self::Text(part)
}
pub fn summary(item: &str, index: usize) -> Self {
Self::Summary {
item: item.to_owned(),
index,
}
}
}
impl std::fmt::Display for Block {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Attempt => f.write_str("attempt"),
Self::Opaque(block) => f.write_str(block),
Self::Text(part) => write!(f, "text-{part}"),
Self::Summary { item, index } => write!(f, "summary-{item}-{index}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DeliveryKind {
Text,
Summary,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryState {
Delta,
Complete,
Interrupted,
}
#[derive(Debug, Clone)]
pub struct Delivery {
pub turn: usize,
pub attempt: usize,
pub block: Block,
pub kind: DeliveryKind,
pub text: String,
pub state: DeliveryState,
}
struct Pending {
text: String,
state: DeliveryState,
}
struct Summary {
item: Option<crate::names::ItemId>,
index: usize,
text: String,
}
#[derive(Default)]
struct Buffer {
managed: bool,
inventory: Inventory,
scrubber: Option<StreamRedactor>,
pending: Vec<((DeliveryKind, Block), Pending)>,
summaries: BTreeMap<Block, Summary>,
live: Live,
published: Published,
finalized: Published,
}
#[derive(Default)]
struct Published {
ordered: String,
text: String,
summary: String,
has_escapes: bool,
}
impl Published {
fn append(&mut self, kind: DeliveryKind, text: &str) {
self.has_escapes |= text.contains(ESCAPE_MARKERS);
self.ordered.push_str(text);
match kind {
DeliveryKind::Text => &mut self.text,
DeliveryKind::Summary => &mut self.summary,
}
.push_str(text);
}
fn overlap_tail<'a>(&self, inventory: &Inventory, published: &'a str) -> &'a str {
if self.has_escapes {
published
} else {
inventory.overlap_tail(published)
}
}
fn overlaps_delta(&self, inventory: &Inventory, kind: DeliveryKind, text: &str) -> bool {
if inventory.is_empty() {
return false;
}
let same_kind = match kind {
DeliveryKind::Text => &self.text,
DeliveryKind::Summary => &self.summary,
};
let overlaps = |published| {
let tail = self.overlap_tail(inventory, published);
inventory.contains(&format!("{tail}{text}"))
};
overlaps(&self.ordered) || (same_kind.len() != self.ordered.len() && overlaps(same_kind))
}
}
#[derive(Default)]
enum Live {
#[default]
New,
First((DeliveryKind, Block)),
Second((DeliveryKind, Block)),
Deferred,
}
impl Buffer {
fn update_inventory(&mut self, current: Inventory) {
if !self.managed {
return;
}
let mut inventory = self.inventory.clone();
inventory.merge(current);
if inventory != self.inventory {
if let Some(stream) = &mut self.scrubber {
stream.update(&inventory.stream());
}
self.inventory = inventory;
}
}
fn scrub_delta(&mut self, key: &(DeliveryKind, Block), text: &str) -> String {
if matches!(self.live, Live::Deferred) {
return String::new();
}
let stream = self.scrubber.get_or_insert_with(|| self.inventory.stream());
match &self.live {
Live::New => self.live = Live::First(key.clone()),
Live::First(previous) | Live::Second(previous) if previous == key => {}
Live::First(previous) if previous.0 != key.0 && !stream.has_pending() => {
self.live = Live::Second(key.clone());
}
_ => {
self.live = Live::Deferred;
return String::new();
}
}
let text = if !self.inventory.is_empty()
&& let Some((prefix, _)) = text.split_once(ESCAPE_MARKERS)
{
self.live = Live::Deferred;
prefix
} else {
text
};
let clean = stream.push(text);
if clean.is_empty() {
return clean;
}
if self.published.ordered.len().saturating_add(clean.len()) > LIVE_DISPLAY_BYTES
|| self
.published
.overlaps_delta(&self.inventory, key.0, &clean)
{
self.live = Live::Deferred;
return String::new();
}
self.published.append(key.0, &clean);
clean
}
fn skip_delta(&mut self, text: &str) {
if matches!(self.live, Live::Deferred) {
return;
}
let stream = self.scrubber.get_or_insert_with(|| self.inventory.stream());
if stream.has_pending() || text.contains(ESCAPE_MARKERS) {
self.live = Live::Deferred;
} else {
let _ = stream.push(text);
if stream.has_pending() {
self.live = Live::Deferred;
}
}
}
fn protect_completions(&mut self, events: &mut [Delivery]) {
if !self.managed {
return;
}
let mut complete = events
.iter_mut()
.filter(|event| event.state == DeliveryState::Complete)
.collect::<Vec<_>>();
if complete.is_empty() {
return;
}
let kinds = [DeliveryKind::Text, DeliveryKind::Summary];
for kind in kinds {
self.inventory.scrub_joined(
&mut complete
.iter_mut()
.filter(|event| event.kind == kind)
.map(|event| &mut event.text)
.collect::<Vec<_>>(),
);
}
self.inventory.scrub_joined(
&mut complete
.iter_mut()
.map(|event| &mut event.text)
.collect::<Vec<_>>(),
);
let unsafe_after = |published: &str, finalized: &str, kind: Option<DeliveryKind>| {
if self.inventory.is_empty() {
return false;
}
let tail = self.published.overlap_tail(&self.inventory, published);
let mut following = String::new();
for event in &complete {
if kind.is_none_or(|kind| event.kind == kind) {
following.push_str(&event.text);
}
}
self.inventory.contains(&format!("{tail}{following}"))
|| (!finalized.is_empty()
&& self
.inventory
.contains(&format!("{tail}{finalized}{following}")))
};
if unsafe_after(&self.published.ordered, &self.finalized.ordered, None)
|| unsafe_after(
&self.published.text,
&self.finalized.text,
Some(DeliveryKind::Text),
)
|| unsafe_after(
&self.published.summary,
&self.finalized.summary,
Some(DeliveryKind::Summary),
)
{
for event in &mut complete {
event.text.clear();
}
}
for event in complete {
self.finalized.append(event.kind, &event.text);
}
}
}
#[derive(Clone, Default)]
pub struct Sink(Arc<Mutex<Buffer>>);
tokio::task_local! { static ACTIVE: Sink; }
pub(super) fn register(inventory: Inventory) {
let _ = ACTIVE.try_with(|sink| sink.0.lock().unwrap().update_inventory(inventory));
}
impl Sink {
pub(super) fn with_inventory(inventory: Inventory) -> Self {
Self(Arc::new(Mutex::new(Buffer {
managed: true,
inventory,
..Buffer::default()
})))
}
pub async fn scope<F: std::future::Future>(&self, future: F) -> F::Output {
ACTIVE.scope(self.clone(), future).await
}
fn push(&self, kind: DeliveryKind, block: Block, text: &str) {
if text.is_empty() {
return;
}
let mut buffer = self.0.lock().unwrap();
let key = (kind, block);
if buffer
.pending
.iter()
.map(|(_, entry)| entry.text.len())
.sum::<usize>()
.saturating_add(text.len())
> PENDING_BYTES
{
buffer.live = Live::Deferred;
return;
}
if let Some((last_key, last)) = buffer.pending.last_mut()
&& *last_key == key
&& last.state == DeliveryState::Delta
{
last.text.push_str(text);
} else if buffer.pending.len() < SUMMARY_PARTS {
buffer.pending.push((
key,
Pending {
text: text.to_owned(),
state: DeliveryState::Delta,
},
));
} else {
buffer.live = Live::Deferred;
}
}
fn complete(&self, kind: DeliveryKind, block: Block, text: String) {
let mut buffer = self.0.lock().unwrap();
let key = (kind, block);
let position = buffer
.pending
.iter()
.position(|(pending, _)| *pending == key);
buffer.pending.retain(|(pending, _)| *pending != key);
let position = position.unwrap_or(buffer.pending.len());
buffer.pending.insert(
position,
(
key,
Pending {
text,
state: DeliveryState::Complete,
},
),
);
}
pub fn ready(&self) -> bool {
self.0
.lock()
.unwrap()
.pending
.iter()
.map(|(_, entry)| entry.text.len())
.sum::<usize>()
>= READY_BYTES
}
pub fn delta(&self, kind: DeliveryKind, block: Block, text: &str) {
self.push(kind, block, text);
}
pub fn finished(&self, kind: DeliveryKind, block: Block, text: String) {
self.complete(kind, block, text);
}
pub fn take(&self, turn: usize, attempt: usize) -> Vec<Delivery> {
self.take_using(turn, attempt, Inventory::default)
}
pub(super) fn take_using(
&self,
turn: usize,
attempt: usize,
current: impl FnOnce() -> Inventory,
) -> Vec<Delivery> {
if self.0.lock().unwrap().pending.is_empty() {
return Vec::new();
}
let inventory = current();
let mut buffer = self.0.lock().unwrap();
buffer.update_inventory(inventory);
let mut events = std::mem::take(&mut buffer.pending)
.into_iter()
.filter_map(|((kind, block), entry)| {
let Some(public) = public_block(&block, &buffer.inventory) else {
if entry.state == DeliveryState::Delta {
buffer.skip_delta(&entry.text);
}
return None;
};
let text = match entry.state {
DeliveryState::Complete if buffer.managed => {
buffer.live = Live::Deferred;
entry.text
}
DeliveryState::Delta if buffer.managed => {
let text = buffer.scrub_delta(&(kind, block), &entry.text);
if text.is_empty() {
return None;
}
text
}
_ => entry.text,
};
Some(Delivery {
turn,
attempt,
block: public,
kind,
text,
state: entry.state,
})
})
.collect::<Vec<_>>();
buffer.protect_completions(&mut events);
events
}
fn summary(
&self,
item: Option<crate::names::ItemId>,
output: Option<usize>,
index: usize,
text: String,
after_wire_text: bool,
) {
if after_wire_text {
self.0.lock().unwrap().live = Live::Deferred;
}
let Some(identity) = item
.as_ref()
.map(|id| format!("item-{id}"))
.or_else(|| output.map(|index| format!("slot-{index}")))
else {
return;
};
let block = Block::summary(&identity, index);
{
let mut buffer = self.0.lock().unwrap();
let observed = buffer
.summaries
.values()
.map(|entry| entry.text.len())
.sum::<usize>();
if buffer.summaries.len() < SUMMARY_PARTS
&& observed.saturating_add(text.len()) <= PENDING_BYTES
{
buffer
.summaries
.entry(block.clone())
.or_insert(Summary {
item,
index,
text: String::new(),
})
.text
.push_str(&text);
}
}
self.push(DeliveryKind::Summary, block, &text);
}
fn summary_block(&self, part: usize, id: Option<&String>, index: usize, text: &str) -> Block {
self.0
.lock()
.unwrap()
.summaries
.iter()
.find(|(_, entry)| {
entry.index == index
&& (id.is_some_and(|id| entry.item.as_ref().is_some_and(|item| item == id))
|| entry.text == text)
})
.map(|(block, _)| block.clone())
.unwrap_or_else(|| Block::summary(&format!("final-{part}"), index))
}
pub(super) fn normalized(&self, item: &Item<StreamEvent>) {
if let Item::Event(StreamEvent::Text { part, text }) = item {
self.push(DeliveryKind::Text, Block::text(part.index()), text);
#[cfg(test)]
super::tests::delivery::text_buffered(text);
}
}
pub(super) fn output_overlaps(
&self,
choice: &[AssistantContent],
inventory: &Inventory,
) -> bool {
if inventory.is_empty() {
return false;
}
let buffer = self.0.lock().unwrap();
let published = &buffer.published;
let ordered = published.overlap_tail(inventory, &published.ordered);
let text = published.overlap_tail(inventory, &published.text);
let summary = published.overlap_tail(inventory, &published.summary);
let finalized = &buffer.finalized;
follows_published(choice, inventory, ordered, text, summary)
|| (!finalized.ordered.is_empty()
&& follows_published(
choice,
inventory,
&format!("{ordered}{}", finalized.ordered),
&format!("{text}{}", finalized.text),
&format!("{summary}{}", finalized.summary),
))
}
pub(super) fn final_response(&self, choice: &[AssistantContent], inventory: &Inventory) {
self.0.lock().unwrap().update_inventory(inventory.clone());
let crossed = match protection(choice, inventory) {
Protection::RejectCall => return,
Protection::WithholdDisplay => true,
Protection::WithholdReasoning | Protection::ScrubSeparately => false,
};
let visible = |text: &str| {
if crossed {
String::new()
} else {
text.to_owned()
}
};
for (part, content) in choice.iter().enumerate() {
match content {
AssistantContent::Text(text) => {
self.complete(DeliveryKind::Text, Block::text(part), visible(&text.text));
}
AssistantContent::Reasoning(sealed) => {
let Some(reasoning) = sealed.open(sealed.issuer()) else {
continue;
};
for (index, text) in reasoning
.content
.iter()
.filter_map(|part| match part {
ReasoningContent::Summary(text) => Some(text),
_ => None,
})
.enumerate()
{
let block = self.summary_block(part, reasoning.id.as_ref(), index, text);
self.complete(DeliveryKind::Summary, block, visible(text));
}
}
_ => {}
}
}
}
}
fn public_block(block: &Block, inventory: &Inventory) -> Option<Block> {
if inventory.is_empty() {
return Some(block.clone());
}
let clean = match block {
Block::Opaque(name) => Block::Opaque(inventory.scrub(name)),
Block::Summary { item, index } => {
if inventory.contains(&index.to_string()) {
return None;
}
Block::summary(&inventory.scrub(item), *index)
}
Block::Text(index) if inventory.contains(&index.to_string()) => return None,
block => block.clone(),
};
(!inventory.contains(&clean.to_string())).then_some(clean)
}
#[derive(Clone)]
pub(crate) struct Tap(rig_reqwest::ReqwestClient);
impl Tap {
pub fn new(client: reqwest::Client) -> Self {
Self(rig_reqwest::ReqwestClient::from(client))
}
}
impl HttpClientExt for Tap {
fn send<T, U>(
&self,
request: Request<T>,
) -> impl std::future::Future<Output = HttpResult<Response<LazyBody<U>>>> + Send + 'static
where
T: Into<Bytes> + Send,
U: From<Bytes> + Send + 'static,
{
self.0.send(request)
}
fn send_multipart<U>(
&self,
request: Request<MultipartForm>,
) -> impl std::future::Future<Output = HttpResult<Response<LazyBody<U>>>> + Send + 'static
where
U: From<Bytes> + Send + 'static,
{
self.0.send_multipart(request)
}
async fn send_streaming<T>(&self, request: Request<T>) -> HttpResult<StreamingResponse>
where
T: Into<Bytes> + Send,
{
let sink = ACTIVE.try_with(Clone::clone).ok();
let response = self.0.send_streaming(request).await?;
let (parts, body) = response.into_parts();
let mut observer = Observer::default();
let stream = body.inspect(move |chunk| {
if let (Some(sink), Ok(bytes)) = (&sink, chunk) {
observer.push(bytes, sink);
}
});
Ok(Response::from_parts(parts, Box::pin(stream)))
}
}
#[derive(Default)]
struct Observer {
framer: SseFramer,
discarding: bool,
previous: u8,
saw_text: bool,
}
#[derive(Deserialize)]
#[serde(tag = "type")]
enum DisplayFrame {
#[serde(
rename = "response.output_text.delta",
alias = "response.refusal.delta"
)]
Text,
#[serde(rename = "response.reasoning_summary_text.delta")]
Summary {
output_index: Option<usize>,
item_id: Option<crate::names::ItemId>,
summary_index: Option<usize>,
delta: String,
},
#[serde(other)]
Other,
}
impl Observer {
fn push(&mut self, bytes: &[u8], sink: &Sink) {
for chunk in bytes.chunks(FRAME_SLICE) {
if self.discarding {
let mut resume = None;
for (index, &byte) in chunk.iter().enumerate() {
if byte == b'\n' && self.previous == b'\n' {
self.discarding = false;
self.framer = SseFramer::new();
resume = Some(index + 1);
break;
}
if byte != b'\r' {
self.previous = byte;
}
}
if let Some(index) = resume {
self.push(&chunk[index..], sink);
}
continue;
}
for frame in self.framer.push(chunk) {
match serde_json::from_str(&frame.data) {
Ok(DisplayFrame::Text) => self.saw_text = true,
Ok(DisplayFrame::Summary {
output_index,
item_id,
summary_index,
delta,
}) => sink.summary(
item_id,
output_index,
summary_index.unwrap_or(0),
delta,
self.saw_text,
),
_ => {}
}
}
if self.framer.pending() > FRAME_BYTES {
sink.0.lock().unwrap().live = Live::Deferred;
self.framer = SseFramer::new();
self.discarding = true;
self.previous = chunk.last().copied().unwrap_or_default();
}
}
}
}