Skip to main content

codex_wrapper/
streaming.rs

1//! Streaming execution for `codex exec` commands.
2//!
3//! Instead of buffering all JSONL output and returning it at once,
4//! the streaming API pipes stdout from the child process and delivers
5//! each [`JsonLineEvent`] to a caller-supplied callback as soon as it
6//! arrives.
7//!
8//! # Example
9//!
10//! ```no_run
11//! use codex_wrapper::{Codex, ExecCommand, JsonLineEvent};
12//!
13//! # async fn example() -> codex_wrapper::Result<()> {
14//! let codex = Codex::builder().build()?;
15//! let cmd = ExecCommand::new("what is 2+2?").ephemeral();
16//!
17//! cmd.stream(&codex, |event: JsonLineEvent| {
18//!     println!("{}: {:?}", event.event_type, event.extra);
19//! })
20//! .await?;
21//! # Ok(())
22//! # }
23//! ```
24
25use tokio::io::{AsyncBufReadExt, BufReader};
26use tokio::process::Command;
27use tracing::{Instrument, debug};
28
29use crate::Codex;
30use crate::command::CodexCommand;
31use crate::error::{Error, Result};
32use crate::types::JsonLineEvent;
33
34/// Stream JSONL events from `codex exec <prompt>`, invoking `handler` for each
35/// parsed [`JsonLineEvent`].
36///
37/// The child's stderr is drained concurrently and returned in the error if the
38/// process exits with a non-zero status.
39pub async fn stream_exec<F>(
40    codex: &Codex,
41    cmd: &crate::command::exec::ExecCommand,
42    handler: F,
43) -> Result<()>
44where
45    F: FnMut(JsonLineEvent),
46{
47    let mut args = cmd.args();
48    if !args.contains(&"--json".to_string()) {
49        args.push("--json".into());
50    }
51    run_streaming(codex, args, cmd.stdin_prompt(), handler).await
52}
53
54/// Stream JSONL events from `codex exec resume`, invoking `handler` for each
55/// parsed [`JsonLineEvent`].
56pub async fn stream_exec_resume<F>(
57    codex: &Codex,
58    cmd: &crate::command::exec::ExecResumeCommand,
59    handler: F,
60) -> Result<()>
61where
62    F: FnMut(JsonLineEvent),
63{
64    let mut args = cmd.args();
65    if !args.contains(&"--json".to_string()) {
66        args.push("--json".into());
67    }
68    run_streaming(codex, args, cmd.stdin_prompt(), handler).await
69}
70
71/// Core streaming implementation shared by both exec variants.
72///
73/// `stdin_prompt` carries the prompt for a `codex exec -` run, where it is
74/// delivered on stdin rather than in argv.
75async fn run_streaming<F>(
76    codex: &Codex,
77    args: Vec<String>,
78    stdin_prompt: Option<&str>,
79    mut handler: F,
80) -> Result<()>
81where
82    F: FnMut(JsonLineEvent),
83{
84    let span = crate::exec::command_span("codex.stream", codex, &args);
85    let command_args = crate::exec::assemble_args(codex, args);
86    let _span_guard = span.clone().entered();
87
88    debug!(binary = %codex.binary.display(), args = ?command_args, "streaming codex command");
89
90    // Settles on every exit below, and on drop for the one that has no exit:
91    // a cancelled stream, which is the outcome most easily missed.
92    let mut outcome = crate::exec::SpanOutcome::start(span.clone());
93
94    let mut child_cmd = Command::new(&codex.binary);
95    child_cmd.args(&command_args);
96    if stdin_prompt.is_some() {
97        child_cmd.stdin(std::process::Stdio::piped());
98    } else {
99        child_cmd.stdin(std::process::Stdio::null());
100    }
101    child_cmd.stdout(std::process::Stdio::piped());
102    child_cmd.stderr(std::process::Stdio::piped());
103
104    // Kill the child if this future is dropped: on timeout, on caller
105    // cancellation, or on task abort. Without this, tokio detaches the child
106    // and codex keeps running with no handle left to stop it.
107    child_cmd.kill_on_drop(true);
108    crate::exec::own_process_group(&mut child_cmd, codex.process_group);
109    crate::exec::apply_die_with_parent(&mut child_cmd, codex.die_with_parent);
110
111    if let Some(dir) = &codex.working_dir {
112        child_cmd.current_dir(dir);
113    }
114    crate::exec::apply_child_environment(&mut child_cmd, codex.clear_env, &codex.env);
115
116    let mut child = child_cmd.spawn().map_err(|e| Error::Io {
117        message: format!("failed to spawn codex: {e}"),
118        source: e,
119        working_dir: codex.working_dir.clone(),
120    })?;
121
122    // Armed for the whole stream. Dropping this future signals the group,
123    // which reaches the subprocesses codex started for tool use; kill_on_drop
124    // alone would leave those running (#78).
125    let mut group =
126        crate::exec::arm_and_notify(codex.process_group, child.id(), codex.on_spawn.as_ref());
127
128    let stdout = child.stdout.take().expect("stdout was configured as piped");
129    let stderr = child.stderr.take().expect("stderr was configured as piped");
130    // Taken up front so the write does not borrow `child`, which the wait
131    // below needs.
132    let child_stdin = child.stdin.take();
133
134    // Write the prompt and close the handle, so the CLI stops waiting for
135    // more. This runs as part of the streamed future rather than before it,
136    // so a prompt larger than the pipe buffer cannot block the readers.
137    let stdin_task = async {
138        let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
139            return Ok(());
140        };
141        use tokio::io::AsyncWriteExt;
142        stdin
143            .write_all(prompt.as_bytes())
144            .await
145            .map_err(|e| Error::Io {
146                message: format!("failed to write the prompt to codex stdin: {e}"),
147                source: e,
148                working_dir: codex.working_dir.clone(),
149            })?;
150        stdin.shutdown().await.map_err(|e| Error::Io {
151            message: format!("failed to close codex stdin: {e}"),
152            source: e,
153            working_dir: codex.working_dir.clone(),
154        })
155    };
156
157    let stdout_task = async {
158        let reader = BufReader::new(stdout);
159        let mut lines = reader.lines();
160        while let Some(line) = lines.next_line().await.map_err(|e| Error::Io {
161            message: format!("failed to read stdout line: {e}"),
162            source: e,
163            working_dir: codex.working_dir.clone(),
164        })? {
165            if line.trim_start().starts_with('{') {
166                match serde_json::from_str::<JsonLineEvent>(&line) {
167                    Ok(event) => handler(event),
168                    Err(source) => {
169                        return Err(Error::Json {
170                            message: format!("failed to parse JSONL event: {line}"),
171                            source,
172                        });
173                    }
174                }
175            }
176        }
177        Ok::<(), Error>(())
178    };
179
180    let stderr_task = async {
181        let reader = BufReader::new(stderr);
182        let mut lines = reader.lines();
183        let mut collected = String::new();
184        while let Some(line) = lines.next_line().await.map_err(|e| Error::Io {
185            message: format!("failed to read stderr line: {e}"),
186            source: e,
187            working_dir: codex.working_dir.clone(),
188        })? {
189            if !collected.is_empty() {
190                collected.push('\n');
191            }
192            collected.push_str(&line);
193        }
194        Ok::<String, Error>(collected)
195    };
196
197    let stream_future = async {
198        let (stdin_result, stdout_result, stderr_result) =
199            tokio::join!(stdin_task, stdout_task, stderr_task);
200        stdin_result?;
201        stdout_result?;
202        let stderr_output = stderr_result?;
203
204        let status = child.wait().await.map_err(|e| Error::Io {
205            message: format!("failed to wait on codex process: {e}"),
206            source: e,
207            working_dir: codex.working_dir.clone(),
208        })?;
209
210        let exit_code = status.code().unwrap_or(-1);
211        if !status.success() {
212            outcome.settle("failed", Some(exit_code));
213            return Err(Error::from_command_failure(
214                format!("{} {}", codex.binary.display(), command_args.join(" ")),
215                exit_code,
216                String::new(),
217                stderr_output,
218                codex.working_dir.clone(),
219            ));
220        }
221
222        outcome.settle("ok", Some(exit_code));
223        group.disarm();
224        Ok(())
225    };
226
227    // Dropped explicitly before awaiting: the guard exists so the span is the
228    // parent of everything above, while the await below must not hold it
229    // across a yield point.
230    drop(_span_guard);
231
232    if let Some(timeout) = codex.timeout {
233        // On elapse the stream future is dropped, taking `outcome` with it,
234        // whose drop records the run as cancelled. That is the same path a
235        // caller dropping this future takes.
236        match tokio::time::timeout(timeout, stream_future.instrument(span.clone())).await {
237            Ok(result) => result,
238            Err(_) => Err(Error::Timeout {
239                timeout_seconds: timeout.as_secs(),
240            }),
241        }
242    } else {
243        stream_future.instrument(span).await
244    }
245}
246
247#[cfg(all(test, unix))]
248mod tests {
249    use super::*;
250    use std::sync::{Arc, Mutex};
251
252    /// Build a [`Codex`] client that uses `bash` to run the fake-codex script.
253    fn fake_codex(script_name: &str) -> Codex {
254        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
255            .join("tests")
256            .join(script_name);
257        Codex::builder()
258            .binary("/bin/bash")
259            .arg(script.to_str().unwrap())
260            .build()
261            .expect("bash must exist")
262    }
263
264    #[tokio::test]
265    async fn stream_exec_delivers_events() {
266        let codex = fake_codex("fake-codex.sh");
267        let cmd = crate::command::exec::ExecCommand::new("test prompt").json();
268        let events = Arc::new(Mutex::new(Vec::new()));
269        let events_clone = Arc::clone(&events);
270
271        stream_exec(&codex, &cmd, move |event| {
272            events_clone.lock().unwrap().push(event);
273        })
274        .await
275        .unwrap();
276
277        let events = events.lock().unwrap();
278        assert!(!events.is_empty(), "expected at least one event");
279
280        let types: Vec<&str> = events.iter().map(|e| e.event_type.as_str()).collect();
281        assert!(
282            types.contains(&"thread.started"),
283            "expected thread.started, got: {types:?}"
284        );
285        assert!(
286            types.contains(&"turn.completed"),
287            "expected turn.completed, got: {types:?}"
288        );
289    }
290
291    /// The API promises delivery as events arrive. Buffering until stdout
292    /// closes loses a thread id when a long-running process or its host dies
293    /// after `thread.started`, which is the durability use case for streaming.
294    #[tokio::test]
295    async fn stream_exec_delivers_an_event_while_the_child_is_still_running() {
296        let codex = Codex::builder()
297            .binary("/bin/bash")
298            .arg("-c")
299            .arg(
300                "printf '%s\\n' '{\"type\":\"thread.started\",\"thread_id\":\"thread-early\"}'; sleep 10",
301            )
302            .build()
303            .expect("bash must exist");
304        let cmd = crate::command::exec::ExecCommand::new("probe").json();
305        let (sent, delivered) = tokio::sync::oneshot::channel();
306        let mut sent = Some(sent);
307
308        let task = tokio::spawn(async move {
309            stream_exec(&codex, &cmd, move |event| {
310                if event.thread_id() == Some("thread-early")
311                    && let Some(sent) = sent.take()
312                {
313                    let _ = sent.send(());
314                }
315            })
316            .await
317        });
318
319        let delivered = tokio::time::timeout(std::time::Duration::from_secs(1), delivered).await;
320        let still_running = !task.is_finished();
321        task.abort();
322        let _ = task.await;
323
324        assert!(delivered.is_ok(), "callback waited for the child to exit");
325        assert!(
326            still_running,
327            "the fixture must still be running when the callback fires"
328        );
329    }
330
331    #[tokio::test]
332    async fn stream_exec_resume_delivers_events() {
333        let codex = fake_codex("fake-codex.sh");
334        let cmd = crate::command::exec::ExecResumeCommand::new().last().json();
335        let events = Arc::new(Mutex::new(Vec::new()));
336        let events_clone = Arc::clone(&events);
337
338        stream_exec_resume(&codex, &cmd, move |event| {
339            events_clone.lock().unwrap().push(event);
340        })
341        .await
342        .unwrap();
343
344        let events = events.lock().unwrap();
345        assert!(!events.is_empty(), "expected at least one event");
346    }
347
348    #[tokio::test]
349    async fn streaming_reports_the_child_before_events_are_delivered() {
350        let order = Arc::new(Mutex::new(Vec::new()));
351        let spawn_order = Arc::clone(&order);
352        let event_order = Arc::clone(&order);
353        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
354            .join("tests")
355            .join("fake-codex.sh");
356        let codex = Codex::builder()
357            .binary("/bin/bash")
358            .arg(script.to_str().unwrap())
359            .on_spawn(Arc::new(move |_| spawn_order.lock().unwrap().push("spawn")))
360            .build()
361            .expect("bash must exist");
362
363        crate::ExecCommand::new("probe")
364            .json()
365            .stream(&codex, move |_| {
366                let mut order = event_order.lock().unwrap();
367                if !order.contains(&"event") {
368                    order.push("event");
369                }
370            })
371            .await
372            .unwrap();
373
374        assert_eq!(&order.lock().unwrap()[..2], ["spawn", "event"]);
375    }
376
377    /// Streaming owns a separate process builder from buffered execution.
378    /// Cover opening, stdin opening, and resume so none can regress to ambient
379    /// inheritance while the others stay isolated.
380    #[tokio::test]
381    async fn cleared_environment_reaches_every_streaming_variant() {
382        let capture = crate::test_support::EnvCapture::new("env-streaming");
383        let codex = crate::test_support::env_capturing_codex(&capture)
384            .clear_env()
385            .env("CODEX_WRAPPER_EXPLICIT", "streaming")
386            .build()
387            .expect("bash must exist");
388
389        crate::ExecCommand::new("opening")
390            .stream(&codex, |_| {})
391            .await
392            .unwrap();
393        let opening_environment = capture.read();
394        assert!(!opening_environment.contains_key("PATH"));
395        assert_eq!(
396            opening_environment
397                .get("CODEX_WRAPPER_EXPLICIT")
398                .map(String::as_str),
399            Some("streaming")
400        );
401
402        crate::ExecCommand::new("stdin")
403            .prompt_via_stdin()
404            .stream(&codex, |_| {})
405            .await
406            .unwrap();
407        let stdin_environment = capture.read();
408        assert!(!stdin_environment.contains_key("PATH"));
409        assert_eq!(
410            stdin_environment
411                .get("CODEX_WRAPPER_EXPLICIT")
412                .map(String::as_str),
413            Some("streaming")
414        );
415
416        crate::ExecResumeCommand::new()
417            .last()
418            .stream(&codex, |_| {})
419            .await
420            .unwrap();
421        let resume_environment = capture.read();
422        assert!(!resume_environment.contains_key("PATH"));
423        assert_eq!(
424            resume_environment
425                .get("CODEX_WRAPPER_EXPLICIT")
426                .map(String::as_str),
427            Some("streaming")
428        );
429    }
430
431    /// Contract captured from a paid 0.145.0 run: the callback receives the
432    /// typed terminal before the process reports its non-zero exit, including
433    /// an assistant message but no fabricated token counts.
434    #[tokio::test]
435    async fn stream_exec_classifies_native_rollout_budget_exhaustion() {
436        let codex = fake_codex("fake-codex-rollout-budget.sh");
437        let cmd = crate::command::exec::ExecCommand::new("probe").json();
438        let events = Arc::new(Mutex::new(Vec::new()));
439        let collected = Arc::clone(&events);
440
441        let error = stream_exec(&codex, &cmd, move |event| {
442            collected.lock().unwrap().push(event);
443        })
444        .await
445        .expect_err("captured rollout exhaustion exits non-zero");
446
447        assert_eq!(error.exit_code(), Some(1));
448        let events = events.lock().unwrap();
449        let terminal = events
450            .iter()
451            .find(|event| event.is_turn_failed())
452            .expect("turn.failed must be delivered");
453        assert_eq!(
454            terminal.turn_failure_kind(),
455            Some(crate::TurnFailureKind::RolloutBudgetExhausted)
456        );
457        assert_eq!(terminal.usage(), None);
458        assert_eq!(crate::QueryResult::from_events(events.clone()).result, "ok");
459    }
460
461    #[tokio::test]
462    async fn stream_exec_timeout() {
463        let codex = Codex::builder()
464            .binary("/bin/bash")
465            .arg("-c")
466            .arg("sleep 10")
467            .timeout(std::time::Duration::from_millis(50))
468            .build()
469            .unwrap();
470
471        let cmd = crate::command::exec::ExecCommand::new("test").json();
472        let result = stream_exec(&codex, &cmd, |_| {}).await;
473
474        assert!(
475            matches!(result, Err(Error::Timeout { .. })),
476            "expected timeout error, got: {result:?}"
477        );
478    }
479
480    /// The streaming path drops both `stream_future` and the child it borrows.
481    /// Without `kill_on_drop`, the timeout above would leave codex running.
482    #[tokio::test]
483    async fn stream_exec_timeout_kills_the_spawned_process() {
484        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
485
486        let pid_file = PidFile::new("stream-timeout");
487        let codex = blocking_codex(&pid_file)
488            .timeout(std::time::Duration::from_millis(500))
489            .build()
490            .expect("bash must exist");
491
492        let cmd = crate::command::exec::ExecCommand::new("probe").json();
493        let result = stream_exec(&codex, &cmd, |_| {}).await;
494        assert!(
495            matches!(result, Err(Error::Timeout { .. })),
496            "expected timeout error, got: {result:?}"
497        );
498
499        let pid = pid_file.read_pid().await;
500        assert!(
501            wait_until_gone(pid).await,
502            "codex ({pid}) survived the timeout"
503        );
504    }
505
506    /// The caller dropping the stream future, with no wrapper timeout.
507    #[tokio::test]
508    async fn stream_exec_cancellation_kills_the_spawned_process() {
509        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
510
511        let pid_file = PidFile::new("stream-cancel");
512        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
513
514        let cmd = crate::command::exec::ExecCommand::new("probe").json();
515        let cancelled = tokio::time::timeout(
516            std::time::Duration::from_millis(500),
517            stream_exec(&codex, &cmd, |_| {}),
518        )
519        .await;
520        assert!(
521            cancelled.is_err(),
522            "fake codex should still have been running, got: {cancelled:?}"
523        );
524
525        let pid = pid_file.read_pid().await;
526        assert!(
527            wait_until_gone(pid).await,
528            "codex ({pid}) survived the dropped future"
529        );
530    }
531
532    #[tokio::test]
533    async fn stream_exec_parse_error() {
534        let codex = fake_codex("fake-codex-bad-json.sh");
535        let cmd = crate::command::exec::ExecCommand::new("test").json();
536        let result = stream_exec(&codex, &cmd, |_| {}).await;
537
538        assert!(
539            matches!(result, Err(Error::Json { .. })),
540            "expected json parse error, got: {result:?}"
541        );
542    }
543}