mod message;
mod reasoning;
mod step;
mod subagent;
mod tool;
use std::collections::BTreeSet;
use std::num::NonZeroUsize;
use crate::{Event, RunErrorEvent, SubagentRunId};
use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
use futures_core::Stream;
use futures_util::StreamExt as _;
use crate::server::cancel::CancellationToken;
use crate::server::error::{Error, Result, Rule, VerificationError};
use crate::server::transform::TransformerChain;
use crate::server::verify::Verifier;
pub use message::MessageHandle;
pub use reasoning::ReasoningHandle;
pub use step::StepGuard;
pub use subagent::SubagentHandle;
pub use tool::ToolCallHandle;
pub(crate) struct EventSink {
tx: UnboundedSender<Event>,
chain: TransformerChain,
verifier: Verifier,
cancel: CancellationToken,
terminated: bool,
attribution: Option<SubagentRunId>,
active_subagents: BTreeSet<SubagentRunId>,
event_buffer_capacity: Option<NonZeroUsize>,
overflowed: bool,
}
impl std::fmt::Debug for EventSink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EventSink")
.field("transformers", &self.chain.len())
.field("cancelled", &self.cancel.is_cancelled())
.field("attribution", &self.attribution)
.finish()
}
}
impl EventSink {
pub(crate) fn new(
tx: UnboundedSender<Event>,
chain: TransformerChain,
cancel: CancellationToken,
) -> Self {
Self {
tx,
chain,
verifier: Verifier::new(),
cancel,
terminated: false,
attribution: None,
active_subagents: BTreeSet::new(),
event_buffer_capacity: None,
overflowed: false,
}
}
pub(crate) fn with_event_buffer_capacity(mut self, capacity: Option<NonZeroUsize>) -> Self {
self.event_buffer_capacity = capacity;
self
}
pub(crate) fn emit(&mut self, event: Event) -> Result<()> {
if self.cancel.is_cancelled() {
return Err(Error::Cancelled);
}
self.emit_forced(event)
}
pub(crate) fn emit_forced(&mut self, mut event: Event) -> Result<()> {
if self.overflowed {
return Err(Error::EventBufferFull {
capacity: self
.event_buffer_capacity
.expect("overflow requires a limit")
.get(),
});
}
if matches!(event, Event::RunFinished(_)) {
if let Some(id) = self.active_subagents.first() {
return Err(VerificationError::new(
event.event_type(),
Rule::OpenAtFinish,
format!("subagent '{id}' requires an explicit finish, fail or suspend"),
)
.into());
}
}
let lifecycle = match &event {
Event::SubagentStarted(started) => Some((started.subagent_run_id.clone(), true)),
Event::SubagentFinished(finished) => Some((finished.subagent_run_id.clone(), false)),
Event::SubagentError(error) => Some((error.subagent_run_id.clone(), false)),
_ => None,
};
if let Some(id) = &self.attribution {
if event.event_type().is_attributable() && event.subagent_run_id().is_none() {
event.set_subagent_run_id(id.clone());
}
}
if self.chain.is_empty() {
self.send(event)?;
} else {
for event in self.chain.transform(event) {
self.send(event)?;
}
}
if let Some((id, opened)) = lifecycle {
if opened {
self.active_subagents.insert(id);
} else {
self.active_subagents.remove(&id);
}
}
Ok(())
}
pub(crate) fn attribution(&self) -> Option<&SubagentRunId> {
self.attribution.as_ref()
}
pub(crate) fn set_attribution(
&mut self,
attribution: Option<SubagentRunId>,
) -> Option<SubagentRunId> {
std::mem::replace(&mut self.attribution, attribution)
}
fn send(&mut self, event: Event) -> Result<()> {
if self.tx.is_closed() {
return Err(Error::Disconnected);
}
if let Some(capacity) = self.event_buffer_capacity {
if self.tx.len() >= capacity.get() {
let error = Error::EventBufferFull {
capacity: capacity.get(),
};
let terminal =
Event::from(RunErrorEvent::new(error.to_string()).with_code(error.code()));
self.verifier.observe(&terminal)?;
self.tx
.unbounded_send(terminal)
.map_err(|_| Error::Disconnected)?;
self.terminated = true;
self.overflowed = true;
self.tx.close_channel();
return Err(error);
}
}
self.verifier.observe(&event)?;
self.terminated |= matches!(event, Event::RunFinished(_) | Event::RunError(_));
self.tx
.unbounded_send(event)
.map_err(|_| Error::Disconnected)
}
pub(crate) fn is_terminated(&self) -> bool {
self.terminated
}
pub(crate) fn cancel_token(&self) -> &CancellationToken {
&self.cancel
}
}
#[derive(Debug)]
pub struct EventReceiver {
rx: UnboundedReceiver<Event>,
}
impl EventReceiver {
pub(crate) fn new(rx: UnboundedReceiver<Event>) -> Self {
Self { rx }
}
pub fn drain(&mut self) -> Vec<Event> {
let mut events = Vec::new();
while let Ok(event) = self.rx.try_recv() {
events.push(event);
}
events
}
pub fn close(&mut self) {
self.rx.close();
}
}
impl Stream for EventReceiver {
type Item = Event;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Event>> {
self.rx.poll_next_unpin(cx)
}
}