use std::future::Future;
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::{
Event, EventType, RunAgentInput, RunErrorEvent, RunFinishedEvent, RunId, RunOutcome,
RunStartedEvent, ThreadId, TokenUsage,
};
use futures_channel::mpsc;
use futures_core::Stream;
use futures_util::StreamExt as _;
use crate::server::agent::Agent;
use crate::server::cancel::CancellationToken;
use crate::server::context::{RunContext, Terminal, decode_state};
use crate::server::emit::{EventReceiver, EventSink};
use crate::server::error::{Error, Result, Rule, VerificationError};
use crate::server::transform::{StreamTransformer, TransformerChain};
pub fn run<A: Agent>(agent: A, input: RunAgentInput) -> impl Stream<Item = Event> + Send {
Runner::new(agent).run(input)
}
pub struct Runner<A> {
agent: A,
chain: TransformerChain,
cancel: CancellationToken,
echo_input: bool,
event_buffer_capacity: Option<NonZeroUsize>,
}
impl<A> std::fmt::Debug for Runner<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Runner")
.field("agent", &std::any::type_name::<A>())
.field("chain", &self.chain)
.field("cancel", &self.cancel)
.field("echo_input", &self.echo_input)
.field("event_buffer_capacity", &self.event_buffer_capacity)
.finish()
}
}
impl<A> Runner<A> {
pub fn new(agent: A) -> Self {
Self {
agent,
chain: TransformerChain::new(),
cancel: CancellationToken::new(),
echo_input: false,
event_buffer_capacity: None,
}
}
#[must_use]
pub fn transformer(mut self, transformer: impl StreamTransformer + 'static) -> Self {
self.chain.push(transformer);
self
}
#[must_use]
pub fn transformers(mut self, chain: TransformerChain) -> Self {
self.chain = chain;
self
}
#[must_use]
pub fn cancellation(mut self, token: CancellationToken) -> Self {
self.cancel = token;
self
}
pub fn cancellation_token(&self) -> CancellationToken {
self.cancel.clone()
}
#[must_use]
pub fn echo_input(mut self, echo: bool) -> Self {
self.echo_input = echo;
self
}
#[must_use]
pub fn event_buffer_capacity(mut self, capacity: NonZeroUsize) -> Self {
self.event_buffer_capacity = Some(capacity);
self
}
}
impl<A: Agent> Runner<A> {
pub fn run(self, input: RunAgentInput) -> impl Stream<Item = Event> + Send {
let (driver, events) = self.into_parts(input);
RunStream {
driver: Some(Box::pin(driver)),
events,
}
}
pub fn into_parts(
self,
input: RunAgentInput,
) -> (impl Future<Output = ()> + Send, EventReceiver) {
let echo_input = self.echo_input;
let (agent, sink, events) = self.split(&input.run_id);
let opening = Opening::Start { echo_input };
(drive(agent, input, sink, opening), events)
}
pub fn continue_run(
self,
input: RunAgentInput,
sent: &[Event],
) -> Result<(impl Future<Output = ()> + Send + use<A>, EventReceiver)> {
let (agent, mut sink, events) = self.split(&input.run_id);
sink.seed(&input.messages);
sink.show_sent(sent);
let mut started = None;
let mut ended = None;
for event in sent {
sink.replay(event)?;
match event {
Event::RunStarted(event) => {
started = Some(event);
ended = None;
}
Event::RunFinished(_) | Event::RunError(_) => ended = Some(event.event_type()),
_ => {}
}
}
let nothing_to_continue = |event, rule, why: &str| {
let detail = format!("there is no run to continue: {why}");
Error::from(VerificationError::new(event, rule, detail))
};
if let Some(terminal) = ended {
return Err(nothing_to_continue(
terminal,
Rule::RunEnded,
"the run already ended",
));
}
let Some(started) = started else {
return Err(nothing_to_continue(
EventType::RunStarted,
Rule::OutOfOrder,
"no RUN_STARTED was sent",
));
};
if started.thread_id != input.thread_id || started.run_id != input.run_id {
return Err(Error::Protocol(crate::Error::Protocol(format!(
"the run that was started is {:?} on thread {:?}, and the input to continue it \
names run {:?} on thread {:?}",
started.run_id.as_str(),
started.thread_id.as_str(),
input.run_id.as_str(),
input.thread_id.as_str(),
))));
}
Ok((drive(agent, input, sink, Opening::Continue), events))
}
fn split(self, run_id: &RunId) -> (A, EventSink, EventReceiver) {
let Self {
agent,
chain,
cancel,
echo_input: _,
event_buffer_capacity,
} = self;
let (tx, rx) = mpsc::unbounded();
let sink = EventSink::new(run_id.clone(), tx, chain, cancel)
.with_event_buffer_capacity(event_buffer_capacity);
(agent, sink, EventReceiver::new(rx))
}
}
enum Opening {
Start { echo_input: bool },
Continue,
}
async fn drive<A: Agent>(agent: A, input: RunAgentInput, mut sink: EventSink, opening: Opening) {
let thread_id = input.thread_id.clone();
let run_id = input.run_id.clone();
if let Opening::Start { echo_input } = opening {
sink.seed(&input.messages);
let mut started = RunStartedEvent::new(thread_id.clone(), run_id.clone());
started.parent_run_id = input.parent_run_id.clone();
if echo_input {
started.input = Some(Box::new(input.clone()));
}
if sink.emit_forced(started.into()).is_err() {
return;
}
}
let decoded = decode_state::<A::State>(&input.state);
let (outcome, terminal) = match decoded {
Ok(state) => {
let mut ctx = RunContext::from_parts(input, state, sink);
let outcome = agent.run(&mut ctx).await;
if ctx.is_terminated() {
return;
}
let terminal;
(sink, terminal) = ctx.into_parts();
(outcome, terminal)
}
Err(error) => (Err(error), Terminal::default()),
};
terminate(&mut sink, outcome, terminal, &thread_id, &run_id);
}
fn terminate(
sink: &mut EventSink,
outcome: Result<RunOutcome>,
terminal: Terminal,
thread_id: &ThreadId,
run_id: &RunId,
) {
if matches!(outcome, Ok(RunOutcome::Cancelled) | Err(Error::Cancelled)) {
sink.close_unclosed(&Error::Cancelled);
}
let usage = terminal.usage();
let finished = |outcome| {
let mut finished =
RunFinishedEvent::new(thread_id.clone(), run_id.clone()).with_outcome(outcome);
finished.result = terminal.result.clone();
finished.usage = usage.clone();
Event::from(finished)
};
let event = match outcome {
Ok(outcome) => match outcome.validate() {
Ok(()) => finished(outcome),
Err(error) => error_event(&Error::Protocol(error), usage.clone()),
},
Err(Error::Cancelled) => finished(RunOutcome::Cancelled),
Err(error) => error_event(&error, usage.clone()),
};
if let Err(rejected) = sink.emit_forced(event) {
if rejected.is_disconnected() || sink.is_terminated() {
return;
}
let _ = sink.emit_forced(error_event(&rejected, usage));
}
if !sink.is_terminated() {
let error = RunErrorEvent::new("the transformer chain did not deliver a terminal event")
.with_code("PROTOCOL_VIOLATION");
let _ = sink.send(error.into());
}
}
fn error_event(error: &Error, usage: Option<Vec<TokenUsage>>) -> Event {
let mut event = RunErrorEvent::new(error.to_string()).with_code(error.code());
event.usage = usage;
event.into()
}
struct RunStream<F> {
driver: Option<Pin<Box<F>>>,
events: EventReceiver,
}
impl<F: Future<Output = ()>> Stream for RunStream<F> {
type Item = Event;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
loop {
match this.events.poll_next_unpin(cx) {
Poll::Ready(Some(event)) => return Poll::Ready(Some(event)),
Poll::Ready(None) => {
this.driver = None;
return Poll::Ready(None);
}
Poll::Pending => {}
}
let Some(driver) = this.driver.as_mut() else {
return Poll::Pending;
};
match driver.as_mut().poll(cx) {
Poll::Ready(()) => this.driver = None,
Poll::Pending => return Poll::Pending,
}
}
}
}
#[cfg(feature = "axum")]
pub(crate) fn terminal_error_events<S>(
events: S,
cancellation: Option<CancellationToken>,
) -> impl Stream<Item = Event> + Send
where
S: Stream<Item = Result<Event>> + Send + 'static,
{
futures_util::stream::unfold(Some(Box::pin(events)), move |events| {
let cancellation = cancellation.clone();
async move {
let mut events = events?;
match events.next().await {
Some(Ok(event)) => Some((event, Some(events))),
Some(Err(error)) => {
if let Some(token) = cancellation {
token.cancel();
}
drop(events);
let event =
Event::from(RunErrorEvent::new(error.to_string()).with_code(error.code()));
Some((event, None))
}
None => None,
}
}
})
}