1use super::{BuiltAgent, Input, RunOutcome};
2use crate::error::KitError;
3use async_trait::async_trait;
4use std::collections::VecDeque;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Mutex, PoisonError};
7use std::time::Duration;
8use tokio::sync::Notify;
9use tokio::task::JoinHandle;
10use troupekit_agent::{
11 AgentError, AgentIo, AgentRun, EvalRegistry, EventSink, ModelHandle, UsageLedger,
12};
13use troupekit_core::clock::Clock;
14use troupekit_core::event::{Event, EventBody};
15use troupekit_core::ids::RunId;
16use troupekit_core::inmem::InMemCheckpoints;
17use troupekit_core::store::CheckpointStore;
18use troupekit_tools::ToolRegistry;
19
20#[non_exhaustive]
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct StreamSettings {
26 pub capacity: usize,
27}
28
29impl StreamSettings {
30 pub const MIN_CAPACITY: usize = 16;
34
35 pub const MAX_CAPACITY: usize = 1_048_576;
39
40 pub(crate) fn check(&self, agent: &str) -> Result<(), KitError> {
41 let range = StreamSettings::MIN_CAPACITY..=StreamSettings::MAX_CAPACITY;
42 if range.contains(&self.capacity) {
43 return Ok(());
44 }
45 Err(KitError::config(
46 agent,
47 format!(
48 "stream capacity must be {} to {}, got {}",
49 range.start(),
50 range.end(),
51 self.capacity
52 ),
53 ))
54 }
55}
56
57impl Default for StreamSettings {
58 fn default() -> Self {
62 StreamSettings { capacity: 4096 }
63 }
64}
65
66#[derive(Clone, Default)]
70pub(crate) struct Cancel(Arc<CancelState>);
71
72#[derive(Default)]
73struct CancelState {
74 set: AtomicBool,
75 changed: Notify,
76}
77
78impl Cancel {
79 pub(crate) fn set(&self) {
82 self.0.set.store(true, Ordering::SeqCst);
83 self.0.changed.notify_waiters();
84 }
85
86 pub(crate) fn is_set(&self) -> bool {
89 self.0.set.load(Ordering::SeqCst)
90 }
91
92 async fn wait(&self) {
93 loop {
94 let changed = self.0.changed.notified();
95 tokio::pin!(changed);
96 changed.as_mut().enable();
97 if self.is_set() {
98 return;
99 }
100 changed.await;
101 }
102 }
103
104 pub(crate) async fn sleep(&self, duration: Duration) -> bool {
107 tokio::time::timeout(duration, self.wait()).await.is_ok()
108 }
109}
110
111pub(crate) async fn detached<T, F>(
116 run_id: RunId,
117 work: impl FnOnce(Cancel) -> F,
118) -> Result<T, KitError>
119where
120 F: std::future::Future<Output = Result<T, KitError>> + Send + 'static,
121 T: Send + 'static,
122{
123 let cancel = Cancel::default();
124 let work = work(cancel.clone());
125 let task = match troupekit_trace::current() {
126 Some(scope) => tokio::spawn(scope.in_scope(work)),
127 None => tokio::spawn(work),
128 };
129 let _cancel = CancelOnDrop(&cancel);
130 match task.await {
131 Ok(result) => result,
132 Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
133 Err(_) => Err(KitError::Cancelled { run_id }),
134 }
135}
136
137pub struct RunStream<T = RunOutcome> {
141 run_id: RunId,
142 queue: Arc<Queue>,
143 cancel: Cancel,
144 task: tokio::sync::Mutex<Option<JoinHandle<Result<T, KitError>>>>,
145}
146
147impl<T> RunStream<T> {
148 pub(crate) fn spawn<F>(
149 run_id: RunId,
150 queue: Arc<Queue>,
151 cancel: Cancel,
152 task: F,
153 ) -> RunStream<T>
154 where
155 F: std::future::Future<Output = Result<T, KitError>> + Send + 'static,
156 T: Send + 'static,
157 {
158 let closer = Closer(queue.clone());
159 let task = tokio::spawn(async move {
160 let _closer = closer;
161 task.await
162 });
163 RunStream {
164 run_id,
165 queue,
166 cancel,
167 task: tokio::sync::Mutex::new(Some(task)),
168 }
169 }
170
171 pub async fn next(&self) -> Option<Event> {
175 self.queue.pop().await
176 }
177
178 pub fn run_id(&self) -> RunId {
182 self.run_id
183 }
184
185 pub fn dropped_deltas(&self) -> u64 {
189 self.queue.dropped()
190 }
191
192 pub fn cancel(&self) {
197 self.cancel.set();
198 }
199
200 pub async fn finish(&self) -> Result<T, KitError> {
205 let mut slot = self.task.lock().await;
206 let Some(task) = slot.as_mut() else {
207 return Err(KitError::config(
208 &self.run_id.to_string(),
209 "finish was already called for this stream",
210 ));
211 };
212 let _cancel = CancelOnDrop(&self.cancel);
213 let joined = task.await;
214 *slot = None;
215 match joined {
216 Ok(result) => result,
217 Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
218 Err(_) => Err(KitError::Cancelled {
219 run_id: self.run_id,
220 }),
221 }
222 }
223}
224
225struct CancelOnDrop<'a>(&'a Cancel);
229
230impl Drop for CancelOnDrop<'_> {
231 fn drop(&mut self) {
235 self.0.set();
236 }
237}
238
239impl<T> Drop for RunStream<T> {
240 fn drop(&mut self) {
244 self.cancel.set();
245 }
246}
247
248impl<T> std::fmt::Debug for RunStream<T> {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253 f.debug_struct("RunStream")
254 .field("run_id", &self.run_id)
255 .field("dropped_deltas", &self.dropped_deltas())
256 .finish_non_exhaustive()
257 }
258}
259
260impl BuiltAgent {
261 pub async fn stream(&self, input: impl Into<Input>) -> Result<RunStream, KitError> {
265 self.stream_with(input, StreamSettings::default()).await
266 }
267
268 pub async fn stream_with(
272 &self,
273 input: impl Into<Input>,
274 settings: StreamSettings,
275 ) -> Result<RunStream, KitError> {
276 let inner = &self.inner;
277 settings.check(&inner.persona.name)?;
278 let messages = self.messages(input.into()).await?;
279 let queue = Arc::new(Queue::new(settings.capacity));
280 let io = StreamIo {
281 base: self.clone(),
282 queue: queue.clone(),
283 };
284 let mut run = AgentRun::new(&inner.persona, messages, inner.limits.clone(), &io).await?;
285 let run_id = run.run_id();
286 let store: Arc<dyn CheckpointStore> = match &inner.store {
287 Some(store) => store.clone(),
288 None => Arc::new(InMemCheckpoints::default()),
289 };
290 store.save(run.checkpoint()).await?;
291 let agent = self.clone();
292 let cancel = Cancel::default();
293 let stop = cancel.clone();
294 let task = async move { agent.finish(&io, &mut run, store.as_ref(), &stop).await };
295 assert_eq!(queue.dropped(), 0);
296 Ok(RunStream::spawn(run_id, queue, cancel, task))
297 }
298}
299
300pub(crate) struct Queue {
301 state: Mutex<QueueState>,
302 ready: Notify,
303 capacity: usize,
304}
305
306struct QueueState {
307 events: VecDeque<Event>,
308 dropped: u64,
309 closed: bool,
310}
311
312impl Queue {
313 pub(crate) fn new(capacity: usize) -> Queue {
314 assert!(capacity >= StreamSettings::MIN_CAPACITY);
315 assert!(capacity <= StreamSettings::MAX_CAPACITY);
316 Queue {
317 state: Mutex::new(QueueState {
318 events: VecDeque::new(),
319 dropped: 0,
320 closed: false,
321 }),
322 ready: Notify::new(),
323 capacity,
324 }
325 }
326
327 fn push(&self, event: Event) {
328 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
329 if state.closed {
330 return;
331 }
332 let delta = matches!(event.body, EventBody::TextDelta { .. });
333 if delta && state.events.len() >= self.capacity {
334 state.dropped += 1;
335 return;
336 }
337 state.events.push_back(event);
338 drop(state);
339 self.ready.notify_one();
340 }
341
342 fn close(&self) {
343 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
344 state.closed = true;
345 drop(state);
346 self.ready.notify_waiters();
347 self.ready.notify_one();
348 }
349
350 async fn pop(&self) -> Option<Event> {
351 loop {
352 let notified = self.ready.notified();
353 tokio::pin!(notified);
354 notified.as_mut().enable();
355 {
356 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
357 if let Some(event) = state.events.pop_front() {
358 return Some(event);
359 }
360 if state.closed {
361 return None;
362 }
363 }
364 notified.await;
365 }
366 }
367
368 pub(crate) fn dropped(&self) -> u64 {
369 self.state
370 .lock()
371 .unwrap_or_else(PoisonError::into_inner)
372 .dropped
373 }
374}
375
376struct Closer(Arc<Queue>);
377
378impl Drop for Closer {
379 fn drop(&mut self) {
383 self.0.close();
384 }
385}
386
387impl EventSink for Queue {
388 fn emit(&self, event: Event) {
389 self.push(event);
390 }
391}
392
393pub(crate) trait BaseIo: Send + Sync + 'static {
394 fn io(&self) -> &dyn AgentIo;
395}
396
397impl BaseIo for BuiltAgent {
398 fn io(&self) -> &dyn AgentIo {
399 &self.inner.io
400 }
401}
402
403impl BaseIo for Arc<dyn AgentIo> {
404 fn io(&self) -> &dyn AgentIo {
405 self.as_ref()
406 }
407}
408
409pub(crate) struct StreamIo<B> {
413 pub(crate) base: B,
414 pub(crate) queue: Arc<Queue>,
415}
416
417impl<B: BaseIo> EventSink for StreamIo<B> {
418 fn emit(&self, event: Event) {
419 self.queue.push(event.clone());
420 self.base.io().events().emit(event);
421 }
422}
423
424#[async_trait]
425impl<B: BaseIo> AgentIo for StreamIo<B> {
426 async fn model(&self, selector: &str) -> Result<ModelHandle, AgentError> {
427 self.base.io().model(selector).await
428 }
429
430 fn tools(&self) -> &ToolRegistry {
431 self.base.io().tools()
432 }
433
434 fn evals(&self) -> &EvalRegistry {
435 self.base.io().evals()
436 }
437
438 fn ledger(&self) -> &dyn UsageLedger {
439 self.base.io().ledger()
440 }
441
442 fn events(&self) -> &dyn EventSink {
443 self
444 }
445
446 fn clock(&self) -> &dyn Clock {
447 self.base.io().clock()
448 }
449}