use crate::error::{ErrorCode, FfiError};
use crate::host::EventListener;
use crate::records::{FfiEvent, FfiEventKind, FfiPause, FfiUsage, RunResult};
use crate::runtime;
use async_trait::async_trait;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::{Arc, Mutex, PoisonError};
use troupekit_core::event::{Event, EventBody, PauseReason, Usage};
use troupekit_kit::{GraphReport, RunOutcome};
pub struct RunStream {
run_id: String,
inner: Arc<dyn KitStream>,
mode: Mutex<Mode>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Idle,
Pulling,
Listening,
}
impl std::fmt::Debug for RunStream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RunStream")
.field("run_id", &self.run_id)
.field(
"mode",
&*self.mode.lock().unwrap_or_else(PoisonError::into_inner),
)
.finish_non_exhaustive()
}
}
impl RunStream {
pub(crate) fn agent(stream: troupekit_kit::RunStream<RunOutcome>) -> Arc<RunStream> {
RunStream::wrap(stream.run_id().to_string(), Arc::new(stream))
}
pub(crate) fn graph(stream: troupekit_kit::RunStream<GraphReport>) -> Arc<RunStream> {
RunStream::wrap(stream.run_id().to_string(), Arc::new(stream))
}
fn wrap(run_id: String, inner: Arc<dyn KitStream>) -> Arc<RunStream> {
assert!(!run_id.is_empty());
Arc::new(RunStream {
run_id,
inner,
mode: Mutex::new(Mode::Idle),
})
}
fn enter(&self, wanted: Mode) -> Result<(), FfiError> {
let mut mode = self.mode.lock().unwrap_or_else(PoisonError::into_inner);
match (*mode, wanted) {
(Mode::Idle, _) | (Mode::Pulling, Mode::Pulling) => {
*mode = wanted;
Ok(())
}
(Mode::Listening, Mode::Listening) => Err(FfiError::new(
ErrorCode::InvalidArgument,
"a listener is already set on this stream",
)),
(Mode::Listening, _) => Err(FfiError::new(
ErrorCode::InvalidArgument,
"this stream delivers to its listener; next is not available",
)),
(Mode::Pulling, _) => Err(FfiError::new(
ErrorCode::InvalidArgument,
"next was already called on this stream; set_listener is not available",
)),
}
}
pub async fn next(&self) -> Result<Option<FfiEvent>, FfiError> {
self.enter(Mode::Pulling)?;
Ok(self.inner.next().await.map(mirror))
}
pub fn set_listener(&self, listener: Arc<dyn EventListener>) -> Result<(), FfiError> {
self.listen_with(|| self.start_listener(listener))
}
pub(crate) fn listen_with(
&self,
setup: impl FnOnce() -> Result<(), FfiError>,
) -> Result<(), FfiError> {
self.enter(Mode::Listening)?;
let started = setup();
if started.is_err() {
let mut mode = self.mode.lock().unwrap_or_else(PoisonError::into_inner);
assert_eq!(*mode, Mode::Listening);
*mode = Mode::Idle;
}
started
}
fn start_listener(&self, listener: Arc<dyn EventListener>) -> Result<(), FfiError> {
let handle = runtime::handle()?;
let inner = self.inner.clone();
let started = std::thread::Builder::new()
.name("troupekit-listener".into())
.spawn(move || {
let mut live = true;
while let Some(event) = handle.block_on(inner.next()) {
if live {
let event = mirror(event);
live = catch_unwind(AssertUnwindSafe(|| listener.on_event(event))).is_ok();
}
}
});
match started {
Ok(_) => Ok(()),
Err(e) => Err(FfiError::new(
ErrorCode::Internal,
format!("the listener thread did not start: {e}"),
)),
}
}
pub fn cancel(&self) {
self.inner.cancel();
}
pub fn run_id(&self) -> String {
self.run_id.clone()
}
pub fn dropped_deltas(&self) -> u64 {
self.inner.dropped()
}
pub async fn result(&self) -> Result<RunResult, FfiError> {
let inner = self.inner.clone();
runtime::spawn(async move { inner.result().await }).await
}
}
#[async_trait]
trait KitStream: Send + Sync + 'static {
async fn next(&self) -> Option<Event>;
fn cancel(&self);
fn dropped(&self) -> u64;
async fn result(&self) -> Result<RunResult, FfiError>;
}
#[async_trait]
impl KitStream for troupekit_kit::RunStream<RunOutcome> {
async fn next(&self) -> Option<Event> {
troupekit_kit::RunStream::next(self).await
}
fn cancel(&self) {
troupekit_kit::RunStream::cancel(self);
}
fn dropped(&self) -> u64 {
self.dropped_deltas()
}
async fn result(&self) -> Result<RunResult, FfiError> {
let outcome = self.finish().await?;
Ok(RunResult::from_outcome(&outcome))
}
}
#[async_trait]
impl KitStream for troupekit_kit::RunStream<GraphReport> {
async fn next(&self) -> Option<Event> {
troupekit_kit::RunStream::next(self).await
}
fn cancel(&self) {
troupekit_kit::RunStream::cancel(self);
}
fn dropped(&self) -> u64 {
self.dropped_deltas()
}
async fn result(&self) -> Result<RunResult, FfiError> {
let report = self.finish().await?;
let output = report.output();
let text = match output {
serde_json::Value::String(text) => text.clone(),
other => other.to_string(),
};
let result = RunResult {
text,
output_json: output.to_string(),
usage: usage_of(report.usage()),
run_id: report.run_id().to_string(),
..RunResult::default()
};
assert_eq!(result.model_calls, 0);
Ok(result)
}
}
pub(crate) fn mirror(event: Event) -> FfiEvent {
let kind = match event.body {
EventBody::RunStarted { workflow } => FfiEventKind::RunStarted { workflow },
EventBody::StepStarted { step, persona } => FfiEventKind::StepStarted { step, persona },
EventBody::TextDelta { text } => FfiEventKind::TextDelta { text },
EventBody::ToolCallStarted { call_id, name } => {
FfiEventKind::ToolCallStarted { call_id, name }
}
EventBody::ToolCallFinished { call_id, is_error } => {
FfiEventKind::ToolCallFinished { call_id, is_error }
}
EventBody::StepFinished { step, usage } => FfiEventKind::StepFinished {
step,
usage: usage_of(usage),
},
EventBody::RunPaused { reason } => FfiEventKind::RunPaused {
reason: match reason {
PauseReason::Approval { node } => FfiPause::Approval { node },
PauseReason::Question { node } => FfiPause::Question { node },
PauseReason::Budget { limit } => FfiPause::Budget { limit },
},
},
EventBody::RunFinished { usage } => FfiEventKind::RunFinished {
usage: usage_of(usage),
},
EventBody::RunFailed { error } => FfiEventKind::RunFailed { error },
};
FfiEvent {
run_id: event.run_id.to_string(),
seq: event.seq,
at_ms: event.at_ms,
kind,
}
}
pub(crate) fn usage_of(usage: Usage) -> FfiUsage {
FfiUsage {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
cost_usd_micros: usage.cost_usd_micros,
}
}