1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::{
collections::VecDeque,
future::Future,
pin::Pin,
sync::{Arc, Mutex, MutexGuard},
task::{Context, Poll},
};
use futures_core::Stream;
use runifold_core::Usage;
use runifold_model::{ModelStreamEvent, ToolCall};
use serde::{Deserialize, Serialize};
use crate::{
AgentError, AgentFuture, AgentOutcome, TerminalRequirementFailure, TerminalReviewVerdictKind,
};
/// The callable boundary represented by an Agent stream event.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[non_exhaustive]
pub enum CallableKind {
/// A locally registered Tool.
Tool,
/// A child Agent route.
Agent,
}
/// One real-time event from the canonical Agent execution loop.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[non_exhaustive]
pub enum AgentStreamEvent {
/// The Agent execution started.
Started {
/// Stable local Agent name.
agent: String,
},
/// A model turn started.
TurnStarted {
/// One-based turn number.
turn: u32,
},
/// One provider-neutral model streaming event.
Model {
/// One-based owning turn.
turn: u32,
/// Canonical event accepted by the model stream accumulator.
event: ModelStreamEvent,
},
/// One dynamic context source completed retrieval.
ContextRetrieved {
/// Operator-visible source name.
source: String,
/// Number of documents injected into the transcript.
documents: usize,
},
/// A Tool or child Agent call started.
CallableStarted {
/// One-based owning turn.
turn: u32,
/// Callable boundary.
kind: CallableKind,
/// Canonical model-emitted call.
call: ToolCall,
},
/// A Tool or child Agent call reached a recoverable terminal result.
CallableCompleted {
/// One-based owning turn.
turn: u32,
/// Callable boundary.
kind: CallableKind,
/// Model-emitted call identity.
call_id: String,
/// Model-facing callable name.
name: String,
/// Whether execution produced a successful output.
success: bool,
},
/// Shared run-tree resource usage changed.
UsageUpdated {
/// Latest cumulative usage snapshot.
usage: Usage,
},
/// The Agent reached a terminal model response.
Completed {
/// Complete canonical outcome.
outcome: AgentOutcome,
},
/// An invalid terminal candidate scheduled a bounded repair turn.
TerminalRepairScheduled {
/// One-based repair attempt number.
attempt: u32,
/// Safe reason the candidate was rejected.
failure: TerminalRequirementFailure,
},
/// Internal review started before a model response can affect execution.
TurnReviewStarted {
/// One-based model turn being reviewed.
turn: u32,
},
/// Internal review returned a validated verdict.
TurnReviewCompleted {
/// One-based model turn that was reviewed.
turn: u32,
/// Stable semantic verdict category.
verdict: TerminalReviewVerdictKind,
},
/// An internal review verdict scheduled a replacement model turn.
TurnReviewRepairScheduled {
/// Cumulative one-based internal repair number.
attempt: u32,
/// Model turn whose response was rejected.
turn: u32,
},
/// Semantic review of a locally valid terminal candidate started.
TerminalReviewStarted {
/// One-based review attempt.
attempt: u32,
},
/// Semantic review returned a validated verdict.
TerminalReviewCompleted {
/// One-based review attempt.
attempt: u32,
/// Stable semantic verdict category.
verdict: TerminalReviewVerdictKind,
},
/// A semantic review verdict scheduled a bounded regeneration turn.
TerminalReviewRepairScheduled {
/// One-based repair number.
attempt: u32,
},
}
pub(crate) trait AgentObserver: Send + Sync {
fn emit(&self, event: AgentStreamEvent);
fn backpressured(&self) -> bool {
false
}
}
#[derive(Debug)]
pub(crate) struct NoopObserver;
impl AgentObserver for NoopObserver {
fn emit(&self, _event: AgentStreamEvent) {}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct BufferedObserver {
events: Arc<Mutex<VecDeque<AgentStreamEvent>>>,
}
impl BufferedObserver {
pub(crate) fn events(&self) -> Arc<Mutex<VecDeque<AgentStreamEvent>>> {
self.events.clone()
}
}
impl AgentObserver for BufferedObserver {
fn emit(&self, event: AgentStreamEvent) {
self.events
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push_back(event);
}
fn backpressured(&self) -> bool {
true
}
}
pub(crate) async fn emit_agent_event(observer: &dyn AgentObserver, event: AgentStreamEvent) {
observer.emit(event);
if observer.backpressured() {
YieldOnce::new().await;
}
}
struct YieldOnce {
yielded: bool,
}
impl YieldOnce {
const fn new() -> Self {
Self { yielded: false }
}
}
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
context.waker().wake_by_ref();
Poll::Pending
}
}
}
/// A borrow-scoped stream that drives the canonical Agent loop when polled.
#[must_use = "streams do nothing unless polled"]
pub struct AgentEventStream<'a> {
execution: Option<AgentFuture<'a, Result<AgentOutcome, AgentError>>>,
events: Arc<Mutex<VecDeque<AgentStreamEvent>>>,
failure: Option<AgentError>,
finished: bool,
}
impl<'a> AgentEventStream<'a> {
pub(crate) fn new(
execution: AgentFuture<'a, Result<AgentOutcome, AgentError>>,
events: Arc<Mutex<VecDeque<AgentStreamEvent>>>,
) -> Self {
Self {
execution: Some(execution),
events,
failure: None,
finished: false,
}
}
fn events(&self) -> MutexGuard<'_, VecDeque<AgentStreamEvent>> {
self.events
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn pop_event(&self) -> Option<AgentStreamEvent> {
self.events().pop_front()
}
}
impl Stream for AgentEventStream<'_> {
type Item = Result<AgentStreamEvent, AgentError>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if let Some(event) = this.pop_event() {
return Poll::Ready(Some(Ok(event)));
}
if let Some(execution) = this.execution.as_mut() {
match execution.as_mut().poll(context) {
Poll::Pending => {
return this
.pop_event()
.map_or(Poll::Pending, |event| Poll::Ready(Some(Ok(event))));
}
Poll::Ready(Ok(_outcome)) => {
this.execution = None;
}
Poll::Ready(Err(error)) => {
this.execution = None;
this.failure = Some(error);
}
}
}
if let Some(event) = this.pop_event() {
return Poll::Ready(Some(Ok(event)));
}
if let Some(error) = this.failure.take() {
return Poll::Ready(Some(Err(error)));
}
if this.execution.is_none() {
this.finished = true;
}
if this.finished {
Poll::Ready(None)
} else {
Poll::Pending
}
}
}
impl std::fmt::Debug for AgentEventStream<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AgentEventStream")
.field("queued_events", &self.events().len())
.field("has_execution", &self.execution.is_some())
.field("has_failure", &self.failure.is_some())
.field("finished", &self.finished)
.finish()
}
}