conductor-sdk 0.2.0

Rust SDK for Netflix Conductor workflow orchestration
Documentation
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// Copyright {{.Year}} Conductor OSS
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

// Server-Sent Events decoding for a running agent execution.
//
// Wraps the byte stream returned by `crate::client::AgentClient::stream` and decodes it into a
// sequence of `AgentEvent`s. `execution_id` is mandatory on every variant.
//
// # Known limitation
//
// This enum has no catch-all fallback variant, so a server event kind not listed here makes
// `AgentStream::next` return a deserialization `Err` and stop iteration.

use futures::{StreamExt as _, TryStreamExt as _};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::{ConductorError, Result};

/// A single decoded event from an agent execution's SSE stream. Every variant carries
/// `execution_id`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum AgentEvent {
    /// An LLM call started for a task. `content` is that task's reference name.
    #[serde(rename = "thinking")]
    Thinking {
        #[serde(rename = "executionId")]
        execution_id: String,
        content: String,
    },
    /// A tool is about to be invoked.
    #[serde(rename = "tool_call")]
    ToolCall {
        #[serde(rename = "executionId")]
        execution_id: String,
        #[serde(rename = "toolName")]
        tool_name: String,
        args: Value,
    },
    /// A tool call finished.
    #[serde(rename = "tool_result")]
    ToolResult {
        #[serde(rename = "executionId")]
        execution_id: String,
        #[serde(rename = "toolName")]
        tool_name: String,
        result: Value,
    },
    /// Execution handed off to a sub-agent/sub-workflow.
    #[serde(rename = "handoff")]
    Handoff {
        #[serde(rename = "executionId")]
        execution_id: String,
        target: String,
    },
    /// The execution is paused awaiting input (a human-in-the-loop tool call, or a
    /// server-side workflow pause).
    ///
    /// `pending_tool` is a raw [`Value`] rather than a typed struct, since its shape varies by
    /// pending-tool type. Can also be an empty object for a workflow-level pause with no
    /// specific pending tool.
    #[serde(rename = "waiting")]
    Waiting {
        #[serde(rename = "executionId")]
        execution_id: String,
        #[serde(rename = "pendingTool", default)]
        pending_tool: Value,
    },
    /// A guardrail check passed.
    #[serde(rename = "guardrail_pass")]
    GuardrailPass {
        #[serde(rename = "executionId")]
        execution_id: String,
        #[serde(rename = "guardrailName")]
        guardrail_name: String,
    },
    /// A guardrail check failed. `content` is the guardrail's failure message.
    #[serde(rename = "guardrail_fail")]
    GuardrailFail {
        #[serde(rename = "executionId")]
        execution_id: String,
        #[serde(rename = "guardrailName")]
        guardrail_name: String,
        content: String,
    },
    /// A task failed or timed out, or the workflow was terminated. `content` is the failure
    /// reason; `tool_name` is the task/workflow reference name it happened on (literally
    /// `"workflow"` for a workflow-level termination, matching the server's own convention).
    #[serde(rename = "error")]
    Error {
        #[serde(rename = "executionId")]
        execution_id: String,
        content: String,
        #[serde(rename = "toolName")]
        tool_name: String,
    },
    /// The execution finished successfully.
    #[serde(rename = "done")]
    Done {
        #[serde(rename = "executionId")]
        execution_id: String,
        output: Value,
    },
    /// The conversation's context window was condensed/summarized. `content` is what triggered
    /// the condensation.
    #[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,
    },
    /// A sub-agent execution started. `content` is the prompt it was given.
    #[serde(rename = "subagent_start")]
    SubagentStart {
        #[serde(rename = "executionId")]
        execution_id: String,
        target: String,
        content: String,
    },
    /// A sub-agent execution stopped.
    #[serde(rename = "subagent_stop")]
    SubagentStop {
        #[serde(rename = "executionId")]
        execution_id: String,
        target: String,
        result: String,
    },
}

impl AgentEvent {
    /// The execution id carried by every variant.
    #[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,
        }
    }
}

// Incremental SSE frame decoder: buffers raw bytes and yields complete frames (delimited by a
// blank line) as they become available, tolerating a frame's bytes arriving split across
// multiple pushes.
#[derive(Debug, Default)]
struct SseDecoder {
    buffer: String,
    finished: bool,
}

impl SseDecoder {
    fn new() -> Self {
        Self::default()
    }

    // Append newly received bytes to the internal buffer.
    fn push(&mut self, chunk: &[u8]) {
        self.buffer.push_str(&String::from_utf8_lossy(chunk));
    }

    // Signal that the underlying stream has ended; any bytes still buffered afterwards are
    // treated as one final, unterminated frame.
    fn finish(&mut self) {
        self.finished = true;
    }

    // Pop the next complete frame's `data:` payload out of the buffer, if one is available.
    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() {
                // Blank/comment-only frame (e.g. an SSE heartbeat `: ping`) — keep reading; the
                // buffer strictly shrinks each iteration (`consumed` is always > 0 here), so this
                // always terminates once real data or an empty buffer is reached.
                continue;
            }
            return Some(data);
        }
    }

    // Find the earliest blank-line frame boundary (`"\n\n"` or `"\r\n\r\n"`), returning
    // `(frame_end, bytes_consumed_including_delimiter)`.
    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,
        }
    }

    // Join every `data:` line in a frame with `\n`, per the SSE spec; ignores `event:`/`id:`/
    // `retry:` lines and `:`-prefixed comment lines.
    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)
}

/// Decoded [`AgentEvent`] stream over a running agent execution's SSE endpoint.
///
/// Constructed from the [`reqwest::Response`] returned by `crate::client::AgentClient::stream`.
/// Drive it with [`AgentStream::next`]:
///
/// ```ignore
/// let mut stream = agent_client.stream(&execution_id).await?.into();
/// while let Some(event) = stream.next().await.transpose()? {
///     match event {
///         AgentEvent::Waiting { execution_id, pending_tool, .. } => { /* ... */ }
///         AgentEvent::Done { output, .. } => println!("{output}"),
///         _ => {}
///     }
/// }
/// ```
pub struct AgentStream {
    body: futures::stream::BoxStream<'static, reqwest::Result<bytes::Bytes>>,
    decoder: SseDecoder,
}

impl AgentStream {
    /// Wrap a raw streaming HTTP response (as returned by `AgentClient::stream`).
    pub fn new(response: reqwest::Response) -> Self {
        Self {
            body: response.bytes_stream().boxed(),
            decoder: SseDecoder::new(),
        }
    }

    /// Fetch the next decoded event, or `None` once the stream has ended.
    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");

        // Simulate the body arriving as several chunks, with one frame split across two chunks.
        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());
    }
}