Skip to main content

greentic_runner_host/http/
agent_stream.rs

1//! Streaming building blocks for `POST /agent/chat/stream`: a session-keyed
2//! observer registry, an SSE-forwarding `StepObserver`, and a fan-out composite
3//! that lets the streaming observer coexist with the audit observer.
4
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use dashmap::DashMap;
9use greentic_aw_runtime::StepObserver;
10use serde::Serialize;
11use tokio::sync::mpsc::UnboundedSender;
12
13/// Session-id → active streaming observer. Shared by `ServerState` (writer:
14/// the SSE handler) and `RuntimeAgentNodeHandler` (reader: the agent step).
15pub type StreamObserverRegistry = Arc<DashMap<String, Arc<dyn StepObserver>>>;
16
17/// One SSE frame emitted to the designer. Mirrors the designer's `TestChatEvent`
18/// wire taxonomy (`event: frame`, kebab-case `kind`).
19#[derive(Debug, Clone, Serialize)]
20#[serde(tag = "kind", rename_all = "kebab-case")]
21pub enum StreamFrame {
22    TextChunk {
23        text: String,
24    },
25    ToolCall {
26        call_id: String,
27        tool_name: String,
28        args: serde_json::Value,
29    },
30    ToolResult {
31        call_id: String,
32        status: FrameStatus,
33        #[serde(skip_serializing_if = "Option::is_none")]
34        result: Option<serde_json::Value>,
35        #[serde(skip_serializing_if = "Option::is_none")]
36        error: Option<String>,
37    },
38    /// One completed LLM iteration's token usage. Lets the designer render a
39    /// per-message LLM/token trace line even when the turn calls no tools.
40    LlmCall {
41        tokens_in: u64,
42        tokens_out: u64,
43    },
44    /// The worker's `flow:` tool parked on a card (the agent ended the turn
45    /// `awaiting_tool_input`). `card` is the agent's `pending_presentation`;
46    /// the caller answers it by sending the submit as the next request's
47    /// `resume_payload`. Always followed by the terminal `Done`.
48    PendingCard {
49        card: serde_json::Value,
50    },
51    Done,
52    Error {
53        message: String,
54    },
55}
56
57#[derive(Debug, Clone, Serialize)]
58#[serde(rename_all = "lowercase")]
59pub enum FrameStatus {
60    Ok,
61    Error,
62}
63
64/// A `StepObserver` that forwards token/tool callbacks as `StreamFrame`s onto an
65/// unbounded `tokio::sync::mpsc` channel. The send side (this observer, called
66/// from the LLM read loop) never blocks or drops a frame for backpressure
67/// reasons — the channel is unbounded. The receive side is drained directly by
68/// the SSE responder via `futures::stream::unfold`, which feeds `Sse::new`
69/// (see `agent_chat_stream_core` / `agent_chat_stream`); there is no separate
70/// bounded intermediate stage between the observer and the SSE response.
71pub struct SseForwardObserver {
72    tx: UnboundedSender<StreamFrame>,
73    /// Flips to `true` on the first `on_token_delta` call. Lets the SSE
74    /// handler's no-delta fallback tell whether the backend actually streamed
75    /// token chunks this turn, so it only synthesizes a single `TextChunk`
76    /// from the assembled reply for non-streaming backends (streaming
77    /// backends already delivered their text via this observer).
78    streamed: AtomicBool,
79}
80
81impl SseForwardObserver {
82    pub fn new(tx: UnboundedSender<StreamFrame>) -> Self {
83        Self {
84            tx,
85            streamed: AtomicBool::new(false),
86        }
87    }
88
89    /// Whether this observer has forwarded at least one token delta so far.
90    pub fn streamed(&self) -> bool {
91        self.streamed.load(Ordering::Relaxed)
92    }
93}
94
95impl StepObserver for SseForwardObserver {
96    fn wants_streaming(&self) -> bool {
97        true
98    }
99    fn on_token_delta(&self, chunk: &str) {
100        self.streamed.store(true, Ordering::Relaxed);
101        let _ = self.tx.send(StreamFrame::TextChunk {
102            text: chunk.to_string(),
103        });
104    }
105    fn on_tool_call(&self, name: &str, call_id: &str, args: &serde_json::Value) {
106        let _ = self.tx.send(StreamFrame::ToolCall {
107            call_id: call_id.to_string(),
108            tool_name: name.to_string(),
109            args: args.clone(),
110        });
111    }
112    fn on_tool_result(&self, _name: &str, call_id: &str, result: &serde_json::Value) {
113        let _ = self.tx.send(StreamFrame::ToolResult {
114            call_id: call_id.to_string(),
115            status: FrameStatus::Ok,
116            result: Some(result.clone()),
117            error: None,
118        });
119    }
120    fn on_tool_failed(&self, _name: &str, call_id: &str, error: &serde_json::Value) {
121        let message = error
122            .get("error")
123            .and_then(serde_json::Value::as_str)
124            .map(str::to_string)
125            .unwrap_or_else(|| error.to_string());
126        let _ = self.tx.send(StreamFrame::ToolResult {
127            call_id: call_id.to_string(),
128            status: FrameStatus::Error,
129            result: None,
130            error: Some(message),
131        });
132    }
133    fn on_llm_call(&self, tokens_in: u64, tokens_out: u64) {
134        let _ = self.tx.send(StreamFrame::LlmCall {
135            tokens_in,
136            tokens_out,
137        });
138    }
139}
140
141/// Fan-out `StepObserver`: forwards every callback to all members and reports
142/// `wants_streaming` as the OR of its members. Used to run the SSE observer and
143/// the audit observer from the same agent step.
144pub struct CompositeObserver {
145    members: Vec<Arc<dyn StepObserver>>,
146}
147
148impl CompositeObserver {
149    pub fn new(members: Vec<Arc<dyn StepObserver>>) -> Self {
150        Self { members }
151    }
152}
153
154impl StepObserver for CompositeObserver {
155    fn wants_streaming(&self) -> bool {
156        self.members.iter().any(|m| m.wants_streaming())
157    }
158    fn on_token_delta(&self, chunk: &str) {
159        for m in &self.members {
160            m.on_token_delta(chunk);
161        }
162    }
163    fn on_tool_call(&self, name: &str, call_id: &str, args: &serde_json::Value) {
164        for m in &self.members {
165            m.on_tool_call(name, call_id, args);
166        }
167    }
168    fn on_tool_result(&self, name: &str, call_id: &str, result: &serde_json::Value) {
169        for m in &self.members {
170            m.on_tool_result(name, call_id, result);
171        }
172    }
173    fn on_tool_failed(&self, name: &str, call_id: &str, error: &serde_json::Value) {
174        for m in &self.members {
175            m.on_tool_failed(name, call_id, error);
176        }
177    }
178    fn on_llm_call(&self, tokens_in: u64, tokens_out: u64) {
179        for m in &self.members {
180            m.on_llm_call(tokens_in, tokens_out);
181        }
182    }
183    fn on_guardrail(&self, obs: &greentic_aw_runtime::guardrail::GuardrailObservation) {
184        for m in &self.members {
185            m.on_guardrail(obs);
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use serde_json::json;
194    use std::sync::{Arc, Mutex};
195
196    // Records every callback so we can assert fan-out.
197    #[derive(Default)]
198    struct Recorder {
199        streaming: bool,
200        calls: Mutex<Vec<String>>,
201    }
202    impl StepObserver for Recorder {
203        fn wants_streaming(&self) -> bool {
204            self.streaming
205        }
206        fn on_token_delta(&self, c: &str) {
207            self.calls.lock().unwrap().push(format!("t:{c}"));
208        }
209        fn on_tool_call(&self, n: &str, id: &str, _args: &serde_json::Value) {
210            self.calls.lock().unwrap().push(format!("c:{n}:{id}"));
211        }
212        fn on_tool_result(&self, n: &str, id: &str, _r: &serde_json::Value) {
213            self.calls.lock().unwrap().push(format!("r:{n}:{id}"));
214        }
215        fn on_tool_failed(&self, n: &str, id: &str, _e: &serde_json::Value) {
216            self.calls.lock().unwrap().push(format!("f:{n}:{id}"));
217        }
218        fn on_guardrail(&self, obs: &greentic_aw_runtime::guardrail::GuardrailObservation) {
219            self.calls
220                .lock()
221                .unwrap()
222                .push(format!("g:{}:{:?}", obs.cap_id, obs.action));
223        }
224    }
225
226    fn guardrail_observation(
227        action: greentic_aw_runtime::guardrail::GuardrailAction,
228    ) -> greentic_aw_runtime::guardrail::GuardrailObservation {
229        greentic_aw_runtime::guardrail::GuardrailObservation {
230            cap_id: "greentic:guardrail/pii".to_string(),
231            extension_id: "ext-pii".to_string(),
232            direction: greentic_aw_runtime::guardrail::GuardrailDirection::Inbound,
233            code: "pii".to_string(),
234            action,
235        }
236    }
237
238    #[test]
239    fn composite_fans_out_to_all_members_and_ors_streaming() {
240        let a = Arc::new(Recorder {
241            streaming: false,
242            ..Default::default()
243        });
244        let b = Arc::new(Recorder {
245            streaming: true,
246            ..Default::default()
247        });
248        let comp = CompositeObserver::new(vec![a.clone(), b.clone()]);
249        assert!(comp.wants_streaming(), "OR of members");
250        comp.on_token_delta("hi");
251        comp.on_tool_call("email", "call_1", &json!({"to": "x@example.com"}));
252        comp.on_tool_failed("email", "call_1", &json!({"error": "boom"}));
253        comp.on_guardrail(&guardrail_observation(
254            greentic_aw_runtime::guardrail::GuardrailAction::Blocked,
255        ));
256        assert_eq!(
257            *a.calls.lock().unwrap(),
258            vec![
259                "t:hi",
260                "c:email:call_1",
261                "f:email:call_1",
262                "g:greentic:guardrail/pii:Blocked"
263            ]
264        );
265        assert_eq!(
266            *b.calls.lock().unwrap(),
267            vec![
268                "t:hi",
269                "c:email:call_1",
270                "f:email:call_1",
271                "g:greentic:guardrail/pii:Blocked"
272            ]
273        );
274    }
275
276    #[test]
277    fn sse_forward_observer_streamed_flips_true_on_first_delta() {
278        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
279        let obs = SseForwardObserver::new(tx);
280        assert!(!obs.streamed(), "should start unstreamed");
281        obs.on_token_delta("hi");
282        assert!(obs.streamed(), "should flip true after first delta");
283    }
284
285    #[test]
286    fn sse_forward_observer_emits_frames_in_order() {
287        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
288        let obs = SseForwardObserver::new(tx);
289        assert!(obs.wants_streaming());
290        obs.on_token_delta("Hel");
291        obs.on_tool_call("sql", "c1", &json!({"query": "select 1"}));
292        obs.on_tool_result("sql", "c1", &json!({"rows": 2}));
293        obs.on_token_delta("lo");
294        drop(obs);
295        let mut kinds = vec![];
296        while let Ok(f) = rx.try_recv() {
297            kinds.push(f);
298        }
299        assert!(matches!(kinds[0], StreamFrame::TextChunk { ref text } if text == "Hel"));
300        assert!(matches!(
301            kinds[1],
302            StreamFrame::ToolCall { ref call_id, ref args, .. }
303            if call_id == "c1" && *args == json!({"query": "select 1"})
304        ));
305        assert!(matches!(kinds[2], StreamFrame::ToolResult { ref call_id, .. } if call_id == "c1"));
306        assert!(matches!(kinds[3], StreamFrame::TextChunk { ref text } if text == "lo"));
307    }
308
309    #[test]
310    fn sse_forward_observer_emits_tool_call_args() {
311        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
312        let obs = SseForwardObserver::new(tx);
313        obs.on_tool_call("http", "c2", &json!({"url": "https://example.com"}));
314        let frame = rx.try_recv().expect("frame sent");
315        match frame {
316            StreamFrame::ToolCall {
317                call_id,
318                tool_name,
319                args,
320            } => {
321                assert_eq!(call_id, "c2");
322                assert_eq!(tool_name, "http");
323                assert_eq!(args, json!({"url": "https://example.com"}));
324            }
325            other => panic!("expected ToolCall frame, got {other:?}"),
326        }
327    }
328
329    #[test]
330    fn sse_forward_observer_on_tool_failed_emits_error_status() {
331        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
332        let obs = SseForwardObserver::new(tx);
333        obs.on_tool_failed("http", "c3", &json!({"error": "connection refused"}));
334        let frame = rx.try_recv().expect("frame sent");
335        match frame {
336            StreamFrame::ToolResult {
337                call_id,
338                status,
339                result,
340                error,
341            } => {
342                assert_eq!(call_id, "c3");
343                assert!(matches!(status, FrameStatus::Error));
344                assert!(result.is_none());
345                assert_eq!(error, Some("connection refused".to_string()));
346            }
347            other => panic!("expected ToolResult frame, got {other:?}"),
348        }
349    }
350
351    #[test]
352    fn sse_forward_observer_on_llm_call_emits_kebab_llm_call_frame() {
353        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
354        let obs = SseForwardObserver::new(tx);
355        obs.on_llm_call(5168, 274);
356        let frame = rx.try_recv().expect("frame sent");
357        match &frame {
358            StreamFrame::LlmCall {
359                tokens_in,
360                tokens_out,
361            } => {
362                assert_eq!(*tokens_in, 5168);
363                assert_eq!(*tokens_out, 274);
364            }
365            other => panic!("expected LlmCall frame, got {other:?}"),
366        }
367        // Wire shape the designer's `RunnerFrame::LlmCall` deserializes.
368        let wire = serde_json::to_value(&frame).unwrap();
369        assert_eq!(wire["kind"], "llm-call");
370        assert_eq!(wire["tokens_in"], 5168);
371        assert_eq!(wire["tokens_out"], 274);
372    }
373
374    #[test]
375    fn sse_forward_observer_on_tool_failed_stringifies_non_error_shaped_value() {
376        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
377        let obs = SseForwardObserver::new(tx);
378        // No "error" string field — falls back to Value::to_string().
379        obs.on_tool_failed("http", "c4", &json!({"reason": "blocked"}));
380        let frame = rx.try_recv().expect("frame sent");
381        match frame {
382            StreamFrame::ToolResult { error, .. } => {
383                assert_eq!(error, Some(json!({"reason": "blocked"}).to_string()));
384            }
385            other => panic!("expected ToolResult frame, got {other:?}"),
386        }
387    }
388
389    #[test]
390    fn stream_frame_serializes_kebab_case_kind() {
391        let f = StreamFrame::TextChunk { text: "hi".into() };
392        assert_eq!(
393            serde_json::to_value(&f).unwrap(),
394            serde_json::json!({"kind":"text-chunk","text":"hi"})
395        );
396        let e = StreamFrame::ToolResult {
397            call_id: "c1".into(),
398            status: FrameStatus::Error,
399            result: None,
400            error: Some("boom".into()),
401        };
402        assert_eq!(
403            serde_json::to_value(&e).unwrap(),
404            serde_json::json!({"kind":"tool-result","call_id":"c1","status":"error","error":"boom"})
405        );
406    }
407
408    /// Wire contract with the designer's Test chat: the card a parked `flow:`
409    /// tool asks the user to answer travels as `kind: "pending-card"`.
410    #[test]
411    fn pending_card_frame_serializes_with_its_card() {
412        let card = serde_json::json!({"type": "AdaptiveCard", "body": [{"text": "Room?"}]});
413        let f = StreamFrame::PendingCard { card: card.clone() };
414        assert_eq!(
415            serde_json::to_value(&f).unwrap(),
416            serde_json::json!({"kind": "pending-card", "card": card})
417        );
418    }
419}