|
| 1 | +//! Caller-consumable streaming entry point ([`AgentHarness::invoke_stream`]). |
| 2 | +//! |
| 3 | +//! [`AgentHarness::invoke_streaming`] drives each model call through |
| 4 | +//! [`ChatModel::stream`][crate::harness::model::ChatModel::stream] but only |
| 5 | +//! returns the fully-accumulated [`AgentRun`] once the run is over — a caller |
| 6 | +//! that wants to *watch* the run unfold has to attach an |
| 7 | +//! [`EventListener`][crate::harness::events::EventListener] or middleware. |
| 8 | +//! |
| 9 | +//! `invoke_stream` closes that gap: it returns an async |
| 10 | +//! [`Stream`][futures::Stream] of [`AgentStreamItem`]s that yields every |
| 11 | +//! [`AgentEvent`][crate::harness::events::AgentEvent] emitted during the run — |
| 12 | +//! model/reasoning deltas, tool-call `ToolStarted`/`ToolCompleted` lifecycle |
| 13 | +//! events, and sub-agent `SubAgentStarted`/`SubAgentCompleted` events (which |
| 14 | +//! reach the stream because sub-agents share the parent's |
| 15 | +//! [`EventSink`][crate::harness::events::EventSink]) — and finishes with a |
| 16 | +//! terminal item carrying the completed [`AgentRun`] (or the failure). |
| 17 | +//! |
| 18 | +//! It is a thin projection over the same ordered |
| 19 | +//! [`EventSink::emit`][crate::harness::events::EventSink::emit] fan-out the |
| 20 | +//! `EventListener` path already uses, not a parallel event system: a listener |
| 21 | +//! forwards each [`EventRecord`] into an unbounded channel that the returned |
| 22 | +//! stream drains. Lineage is carried by the events themselves (`ModelDelta` |
| 23 | +//! stamps `run_id`; sub-agent events stamp `depth`). Streaming a child agent's |
| 24 | +//! own model deltas into the parent requires routing the streaming flag through |
| 25 | +//! the sub-agent runner and is tracked as follow-up work. |
| 26 | +
|
| 27 | +use std::future::Future; |
| 28 | +use std::pin::Pin; |
| 29 | +use std::sync::Arc; |
| 30 | + |
| 31 | +use crate::error::Result; |
| 32 | +use crate::harness::context::{RunConfig, RunContext}; |
| 33 | +use crate::harness::events::{EventListener, EventRecord}; |
| 34 | +use crate::harness::message::Message; |
| 35 | +use crate::harness::middleware::AgentRun; |
| 36 | +use crate::harness::runtime::AgentHarness; |
| 37 | + |
| 38 | +use super::AgentLoopResult; |
| 39 | + |
| 40 | +/// One item yielded by [`AgentHarness::invoke_stream`]. |
| 41 | +/// |
| 42 | +/// The stream yields zero or more [`AgentStreamItem::Event`]s in emission |
| 43 | +/// order, followed by exactly one terminal item — either |
| 44 | +/// [`AgentStreamItem::Completed`] carrying the final [`AgentRun`], or |
| 45 | +/// [`AgentStreamItem::Failed`] carrying the error string. No items are produced |
| 46 | +/// after the terminal item. |
| 47 | +#[derive(Clone, Debug)] |
| 48 | +pub enum AgentStreamItem { |
| 49 | + /// A live event emitted during the run. Carries the full |
| 50 | + /// [`EventRecord`] (id + offset + [`AgentEvent`][crate::harness::events::AgentEvent]) |
| 51 | + /// so consumers keep ordering and lineage fields (`run_id`, `depth`). |
| 52 | + Event(EventRecord), |
| 53 | + /// Terminal: the run completed successfully. Boxed because [`AgentRun`] is |
| 54 | + /// large relative to the event variant. |
| 55 | + Completed(Box<AgentRun>), |
| 56 | + /// Terminal: the run failed; carries the error rendered as a string. |
| 57 | + Failed(String), |
| 58 | +} |
| 59 | + |
| 60 | +/// An [`EventListener`] that forwards every [`EventRecord`] into an unbounded |
| 61 | +/// channel. `on_event` is synchronous and must not block, so the channel is |
| 62 | +/// unbounded; in practice its depth is bounded by run progress (the loop awaits |
| 63 | +/// the network between emits). Send failures (receiver dropped) are ignored so |
| 64 | +/// a dropped stream never disturbs the run. |
| 65 | +struct ChannelListener { |
| 66 | + tx: tokio::sync::mpsc::UnboundedSender<EventRecord>, |
| 67 | +} |
| 68 | + |
| 69 | +impl EventListener for ChannelListener { |
| 70 | + fn on_event(&self, record: &EventRecord) { |
| 71 | + let _ = self.tx.send(record.clone()); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +/// Maps a finished run result onto its terminal [`AgentStreamItem`]. |
| 76 | +fn terminal_item(result: Result<AgentLoopResult>) -> AgentStreamItem { |
| 77 | + match result { |
| 78 | + Ok(loop_result) => AgentStreamItem::Completed(Box::new(loop_result.run)), |
| 79 | + Err(error) => AgentStreamItem::Failed(error.to_string()), |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +/// Drive-phase for the streaming state machine. |
| 84 | +enum Phase<'a> { |
| 85 | + /// The run future is still executing. |
| 86 | + Running(Pin<Box<dyn Future<Output = Result<AgentLoopResult>> + 'a>>), |
| 87 | + /// The run has finished; drain any buffered events, then emit `terminal`. |
| 88 | + Draining(AgentStreamItem), |
| 89 | + /// Terminal item already emitted; the stream is exhausted. |
| 90 | + Done, |
| 91 | +} |
| 92 | + |
| 93 | +impl<State: Send + Sync, Ctx: Send + Sync + 'static> AgentHarness<State, Ctx> { |
| 94 | + /// Runs the agent loop while streaming every emitted event to the caller. |
| 95 | + /// |
| 96 | + /// Returns a [`Stream`][futures::Stream] of [`AgentStreamItem`]s: live |
| 97 | + /// [`AgentStreamItem::Event`]s in emission order (model/reasoning deltas, |
| 98 | + /// tool-call lifecycle, sub-agent lifecycle, usage, …) followed by a single |
| 99 | + /// terminal [`AgentStreamItem::Completed`] / [`AgentStreamItem::Failed`]. |
| 100 | + /// Driving the loop and consuming the stream are the same task: the run |
| 101 | + /// only makes progress while the stream is polled, so a caller that stops |
| 102 | + /// polling pauses the run (and dropping the stream cancels it). |
| 103 | + /// |
| 104 | + /// This is the streaming counterpart of |
| 105 | + /// [`AgentHarness::invoke_streaming`]; the run itself is identical (each |
| 106 | + /// model call is driven through |
| 107 | + /// [`ChatModel::stream`][crate::harness::model::ChatModel::stream]). |
| 108 | + pub fn invoke_stream<'a>( |
| 109 | + &'a self, |
| 110 | + state: &'a State, |
| 111 | + ctx_data: Ctx, |
| 112 | + config: RunConfig, |
| 113 | + input: Vec<Message>, |
| 114 | + ) -> impl futures::Stream<Item = AgentStreamItem> + 'a { |
| 115 | + let ctx = RunContext::new(config, ctx_data); |
| 116 | + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); |
| 117 | + // Subscribe before driving so no event (starting with `RunStarted`) is |
| 118 | + // missed. The listener rides the run's `EventSink`, which sub-agents |
| 119 | + // clone, so their lifecycle events reach this stream too. |
| 120 | + ctx.events.subscribe(Arc::new(ChannelListener { tx })); |
| 121 | + |
| 122 | + // `invoke_streaming_in_context_with_status` is the public wrapper over |
| 123 | + // the shared `drive(.., streaming = true)` path; it drives *our* `ctx` |
| 124 | + // (with the listener already attached) and hands back the terminal |
| 125 | + // `AgentLoopResult`. |
| 126 | + let run_fut: Pin<Box<dyn Future<Output = Result<AgentLoopResult>> + 'a>> = |
| 127 | + Box::pin(self.invoke_streaming_in_context_with_status(state, ctx, input)); |
| 128 | + |
| 129 | + futures::stream::unfold( |
| 130 | + (Phase::Running(run_fut), rx), |
| 131 | + |(phase, mut rx)| async move { |
| 132 | + match phase { |
| 133 | + Phase::Running(mut run_fut) => { |
| 134 | + tokio::select! { |
| 135 | + biased; |
| 136 | + // Prefer draining ready events so the consumer sees |
| 137 | + // fine-grained progress rather than a late burst. |
| 138 | + maybe = rx.recv() => match maybe { |
| 139 | + Some(record) => { |
| 140 | + Some((AgentStreamItem::Event(record), (Phase::Running(run_fut), rx))) |
| 141 | + } |
| 142 | + None => { |
| 143 | + // All senders dropped (the run's context — |
| 144 | + // and every sub-agent clone of the sink — |
| 145 | + // is gone): the run is finishing. Await it |
| 146 | + // for the terminal item. |
| 147 | + let terminal = terminal_item(run_fut.await); |
| 148 | + Some((terminal, (Phase::Done, rx))) |
| 149 | + } |
| 150 | + }, |
| 151 | + result = &mut run_fut => { |
| 152 | + // The run finished. Events emitted during this |
| 153 | + // final poll may still be buffered; drain them |
| 154 | + // ahead of the terminal item. |
| 155 | + let terminal = terminal_item(result); |
| 156 | + match rx.try_recv() { |
| 157 | + Ok(record) => Some(( |
| 158 | + AgentStreamItem::Event(record), |
| 159 | + (Phase::Draining(terminal), rx), |
| 160 | + )), |
| 161 | + Err(_) => Some((terminal, (Phase::Done, rx))), |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + Phase::Draining(terminal) => match rx.try_recv() { |
| 167 | + Ok(record) => Some(( |
| 168 | + AgentStreamItem::Event(record), |
| 169 | + (Phase::Draining(terminal), rx), |
| 170 | + )), |
| 171 | + Err(_) => Some((terminal, (Phase::Done, rx))), |
| 172 | + }, |
| 173 | + Phase::Done => None, |
| 174 | + } |
| 175 | + }, |
| 176 | + ) |
| 177 | + } |
| 178 | +} |
0 commit comments