use futures::{StreamExt as _, TryStreamExt as _};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::{ConductorError, Result};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum AgentEvent {
#[serde(rename = "thinking")]
Thinking {
#[serde(rename = "executionId")]
execution_id: String,
content: String,
},
#[serde(rename = "tool_call")]
ToolCall {
#[serde(rename = "executionId")]
execution_id: String,
#[serde(rename = "toolName")]
tool_name: String,
args: Value,
},
#[serde(rename = "tool_result")]
ToolResult {
#[serde(rename = "executionId")]
execution_id: String,
#[serde(rename = "toolName")]
tool_name: String,
result: Value,
},
#[serde(rename = "handoff")]
Handoff {
#[serde(rename = "executionId")]
execution_id: String,
target: String,
},
#[serde(rename = "waiting")]
Waiting {
#[serde(rename = "executionId")]
execution_id: String,
#[serde(rename = "pendingTool", default)]
pending_tool: Value,
},
#[serde(rename = "guardrail_pass")]
GuardrailPass {
#[serde(rename = "executionId")]
execution_id: String,
#[serde(rename = "guardrailName")]
guardrail_name: String,
},
#[serde(rename = "guardrail_fail")]
GuardrailFail {
#[serde(rename = "executionId")]
execution_id: String,
#[serde(rename = "guardrailName")]
guardrail_name: String,
content: String,
},
#[serde(rename = "error")]
Error {
#[serde(rename = "executionId")]
execution_id: String,
content: String,
#[serde(rename = "toolName")]
tool_name: String,
},
#[serde(rename = "done")]
Done {
#[serde(rename = "executionId")]
execution_id: String,
output: Value,
},
#[serde(rename = "context_condensed")]
ContextCondensed {
#[serde(rename = "executionId")]
execution_id: String,
content: String,
#[serde(rename = "messagesBefore")]
messages_before: i32,
#[serde(rename = "messagesAfter")]
messages_after: i32,
#[serde(rename = "exchangesCondensed")]
exchanges_condensed: i32,
},
#[serde(rename = "subagent_start")]
SubagentStart {
#[serde(rename = "executionId")]
execution_id: String,
target: String,
content: String,
},
#[serde(rename = "subagent_stop")]
SubagentStop {
#[serde(rename = "executionId")]
execution_id: String,
target: String,
result: String,
},
}
impl AgentEvent {
#[must_use]
pub fn execution_id(&self) -> &str {
match self {
AgentEvent::Thinking { execution_id, .. }
| AgentEvent::ToolCall { execution_id, .. }
| AgentEvent::ToolResult { execution_id, .. }
| AgentEvent::Handoff { execution_id, .. }
| AgentEvent::Waiting { execution_id, .. }
| AgentEvent::GuardrailPass { execution_id, .. }
| AgentEvent::GuardrailFail { execution_id, .. }
| AgentEvent::Error { execution_id, .. }
| AgentEvent::Done { execution_id, .. }
| AgentEvent::ContextCondensed { execution_id, .. }
| AgentEvent::SubagentStart { execution_id, .. }
| AgentEvent::SubagentStop { execution_id, .. } => execution_id,
}
}
}
#[derive(Debug, Default)]
struct SseDecoder {
buffer: String,
finished: bool,
}
impl SseDecoder {
fn new() -> Self {
Self::default()
}
fn push(&mut self, chunk: &[u8]) {
self.buffer.push_str(&String::from_utf8_lossy(chunk));
}
fn finish(&mut self) {
self.finished = true;
}
fn next_data(&mut self) -> Option<String> {
loop {
let boundary = Self::find_boundary(&self.buffer).or_else(|| {
(self.finished && !self.buffer.is_empty()).then(|| {
let len = self.buffer.len();
(len, len)
})
})?;
let (frame_end, consumed) = boundary;
let raw_frame = self.buffer[..frame_end].to_string();
self.buffer.drain(..consumed);
let data = Self::extract_data(&raw_frame);
if data.is_empty() {
continue;
}
return Some(data);
}
}
fn find_boundary(buffer: &str) -> Option<(usize, usize)> {
let lf = buffer.find("\n\n").map(|i| (i, i + 2));
let crlf = buffer.find("\r\n\r\n").map(|i| (i, i + 4));
match (lf, crlf) {
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(None, None) => None,
}
}
fn extract_data(raw_frame: &str) -> String {
let mut lines = Vec::new();
for line in raw_frame.split('\n') {
let line = line.strip_suffix('\r').unwrap_or(line);
if let Some(rest) = line.strip_prefix("data:") {
lines.push(rest.strip_prefix(' ').unwrap_or(rest));
}
}
lines.join("\n")
}
}
fn parse_event(data: &str) -> Result<AgentEvent> {
serde_json::from_str(data).map_err(ConductorError::Json)
}
pub struct AgentStream {
body: futures::stream::BoxStream<'static, reqwest::Result<bytes::Bytes>>,
decoder: SseDecoder,
}
impl AgentStream {
pub fn new(response: reqwest::Response) -> Self {
Self {
body: response.bytes_stream().boxed(),
decoder: SseDecoder::new(),
}
}
pub async fn next(&mut self) -> Option<Result<AgentEvent>> {
loop {
if let Some(data) = self.decoder.next_data() {
return Some(parse_event(&data));
}
match self.body.try_next().await {
Ok(Some(chunk)) => self.decoder.push(&chunk),
Ok(None) => {
self.decoder.finish();
return self.decoder.next_data().map(|data| parse_event(&data));
}
Err(e) => return Some(Err(ConductorError::Http(e))),
}
}
}
}
impl From<reqwest::Response> for AgentStream {
fn from(response: reqwest::Response) -> Self {
Self::new(response)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn waiting_json(execution_id: &str) -> String {
serde_json::json!({
"type": "waiting",
"executionId": execution_id,
"pendingTool": {"tool_name": "issue_refund", "parameters": {"amount": 42.0}}
})
.to_string()
}
#[test]
fn test_decoder_parses_single_frame() {
let mut decoder = SseDecoder::new();
decoder.push(format!("data: {}\n\n", waiting_json("exec-1")).as_bytes());
let data = decoder.next_data().expect("frame should be available");
let event = parse_event(&data).unwrap();
assert_eq!(
event,
AgentEvent::Waiting {
execution_id: "exec-1".to_owned(),
pending_tool: serde_json::json!({
"tool_name": "issue_refund",
"parameters": {"amount": 42.0}
}),
}
);
assert_eq!(event.execution_id(), "exec-1");
}
#[test]
fn test_decoder_handles_frame_split_across_chunks() {
let full = format!("data: {}\n\n", waiting_json("exec-2"));
let split_at = full.len() / 2;
let (first, second) = full.split_at(split_at);
let mut decoder = SseDecoder::new();
decoder.push(first.as_bytes());
assert!(
decoder.next_data().is_none(),
"no complete frame yet, must not yield"
);
decoder.push(second.as_bytes());
let data = decoder.next_data().expect("frame should now be complete");
let event = parse_event(&data).unwrap();
assert_eq!(event.execution_id(), "exec-2");
}
#[test]
fn test_decoder_handles_multiple_data_lines_in_one_frame() {
let mut decoder = SseDecoder::new();
decoder.push(b"data: {\"type\":\"thinking\",\n");
decoder.push(b"data: \"executionId\":\"exec-3\",\"content\":\"hi\"}\n\n");
let data = decoder.next_data().expect("frame should be complete");
let event = parse_event(&data).unwrap();
assert_eq!(
event,
AgentEvent::Thinking {
execution_id: "exec-3".to_owned(),
content: "hi".to_owned(),
}
);
}
#[test]
fn test_decoder_skips_comments_and_id_lines() {
let mut decoder = SseDecoder::new();
let frame = format!(
"id: 7\n: this is a heartbeat comment\nevent: agent\ndata: {}\n\n",
waiting_json("exec-4")
);
decoder.push(frame.as_bytes());
let data = decoder.next_data().expect("frame should be complete");
let event = parse_event(&data).unwrap();
assert_eq!(event.execution_id(), "exec-4");
}
#[test]
fn test_decoder_yields_multiple_queued_frames_in_order() {
let mut decoder = SseDecoder::new();
decoder.push(
format!(
"data: {}\n\ndata: {}\n\n",
waiting_json("exec-5"),
serde_json::json!({"type": "done", "executionId": "exec-5", "output": "ok"}),
)
.as_bytes(),
);
let first = parse_event(&decoder.next_data().unwrap()).unwrap();
assert_eq!(first.execution_id(), "exec-5");
assert!(matches!(first, AgentEvent::Waiting { .. }));
let second = parse_event(&decoder.next_data().unwrap()).unwrap();
assert!(matches!(second, AgentEvent::Done { .. }));
assert!(decoder.next_data().is_none());
}
#[test]
fn test_decoder_flushes_unterminated_final_frame_on_finish() {
let mut decoder = SseDecoder::new();
decoder.push(format!("data: {}", waiting_json("exec-6")).as_bytes());
assert!(decoder.next_data().is_none(), "no blank line yet");
decoder.finish();
let data = decoder
.next_data()
.expect("finish() should flush the trailing frame");
let event = parse_event(&data).unwrap();
assert_eq!(event.execution_id(), "exec-6");
}
#[test]
fn test_parse_event_error_variant() {
let json = serde_json::json!({
"type": "error",
"executionId": "exec-7",
"content": "tool timed out",
"toolName": "issue_refund_ref"
})
.to_string();
let event = parse_event(&json).unwrap();
assert_eq!(
event,
AgentEvent::Error {
execution_id: "exec-7".to_owned(),
content: "tool timed out".to_owned(),
tool_name: "issue_refund_ref".to_owned(),
}
);
}
#[test]
fn test_parse_event_thinking_variant() {
let json = serde_json::json!({
"type": "thinking",
"executionId": "exec-8",
"content": "llm_call_ref"
})
.to_string();
let event = parse_event(&json).unwrap();
assert_eq!(
event,
AgentEvent::Thinking {
execution_id: "exec-8".to_owned(),
content: "llm_call_ref".to_owned(),
}
);
}
#[test]
fn test_parse_event_tool_call_and_tool_result_variants() {
let call_json = serde_json::json!({
"type": "tool_call",
"executionId": "exec-9",
"toolName": "issue_refund",
"args": {"amount": 42.0}
})
.to_string();
assert_eq!(
parse_event(&call_json).unwrap(),
AgentEvent::ToolCall {
execution_id: "exec-9".to_owned(),
tool_name: "issue_refund".to_owned(),
args: serde_json::json!({"amount": 42.0}),
}
);
let result_json = serde_json::json!({
"type": "tool_result",
"executionId": "exec-9",
"toolName": "issue_refund",
"result": {"refunded": true}
})
.to_string();
assert_eq!(
parse_event(&result_json).unwrap(),
AgentEvent::ToolResult {
execution_id: "exec-9".to_owned(),
tool_name: "issue_refund".to_owned(),
result: serde_json::json!({"refunded": true}),
}
);
}
#[test]
fn test_parse_event_handoff_variant() {
let json = serde_json::json!({
"type": "handoff",
"executionId": "exec-10",
"target": "billing_agent"
})
.to_string();
assert_eq!(
parse_event(&json).unwrap(),
AgentEvent::Handoff {
execution_id: "exec-10".to_owned(),
target: "billing_agent".to_owned(),
}
);
}
#[test]
fn test_parse_event_guardrail_pass_and_fail_variants() {
let pass_json = serde_json::json!({
"type": "guardrail_pass",
"executionId": "exec-11",
"guardrailName": "no_pii"
})
.to_string();
assert_eq!(
parse_event(&pass_json).unwrap(),
AgentEvent::GuardrailPass {
execution_id: "exec-11".to_owned(),
guardrail_name: "no_pii".to_owned(),
}
);
let fail_json = serde_json::json!({
"type": "guardrail_fail",
"executionId": "exec-11",
"guardrailName": "no_pii",
"content": "found an SSN"
})
.to_string();
assert_eq!(
parse_event(&fail_json).unwrap(),
AgentEvent::GuardrailFail {
execution_id: "exec-11".to_owned(),
guardrail_name: "no_pii".to_owned(),
content: "found an SSN".to_owned(),
}
);
}
#[test]
fn test_parse_event_context_condensed_variant() {
let json = serde_json::json!({
"type": "context_condensed",
"executionId": "exec-12",
"content": "token_limit",
"messagesBefore": 40,
"messagesAfter": 10,
"exchangesCondensed": 15
})
.to_string();
assert_eq!(
parse_event(&json).unwrap(),
AgentEvent::ContextCondensed {
execution_id: "exec-12".to_owned(),
content: "token_limit".to_owned(),
messages_before: 40,
messages_after: 10,
exchanges_condensed: 15,
}
);
}
#[test]
fn test_parse_event_subagent_start_and_stop_variants() {
let start_json = serde_json::json!({
"type": "subagent_start",
"executionId": "exec-13",
"target": "researcher",
"content": "find the latest price"
})
.to_string();
assert_eq!(
parse_event(&start_json).unwrap(),
AgentEvent::SubagentStart {
execution_id: "exec-13".to_owned(),
target: "researcher".to_owned(),
content: "find the latest price".to_owned(),
}
);
let stop_json = serde_json::json!({
"type": "subagent_stop",
"executionId": "exec-13",
"target": "researcher",
"result": "$42"
})
.to_string();
assert_eq!(
parse_event(&stop_json).unwrap(),
AgentEvent::SubagentStop {
execution_id: "exec-13".to_owned(),
target: "researcher".to_owned(),
result: "$42".to_owned(),
}
);
}
#[test]
fn test_parse_event_rejects_malformed_json() {
let result = parse_event("not json");
result.unwrap_err();
}
#[tokio::test]
async fn test_agent_stream_yields_events_from_chunked_bytes() {
let frame1 = format!("data: {}\n\n", waiting_json("exec-9"));
let frame2 =
serde_json::json!({"type": "done", "executionId": "exec-9", "output": 1}).to_string();
let frame2 = format!("data: {frame2}\n\n");
let split = frame1.len() - 3;
let chunks: Vec<reqwest::Result<bytes::Bytes>> = vec![
Ok(bytes::Bytes::copy_from_slice(&frame1.as_bytes()[..split])),
Ok(bytes::Bytes::copy_from_slice(&frame1.as_bytes()[split..])),
Ok(bytes::Bytes::copy_from_slice(frame2.as_bytes())),
];
let body = futures::stream::iter(chunks).boxed();
let mut stream = AgentStream {
body,
decoder: SseDecoder::new(),
};
let first = stream.next().await.unwrap().unwrap();
assert!(matches!(first, AgentEvent::Waiting { .. }));
assert_eq!(first.execution_id(), "exec-9");
let second = stream.next().await.unwrap().unwrap();
assert!(matches!(second, AgentEvent::Done { .. }));
assert!(stream.next().await.is_none());
}
}