1use 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
34pub 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(
52 codex,
53 args,
54 cmd.stdin_prompt(),
55 handler,
56 std::future::pending(),
57 )
58 .await
59}
60
61pub async fn stream_exec_cancellable<C, F>(
67 codex: &Codex,
68 cmd: &crate::command::exec::ExecCommand,
69 cancel: C,
70 handler: F,
71) -> Result<()>
72where
73 C: std::future::Future<Output = ()> + Send,
74 F: FnMut(JsonLineEvent),
75{
76 let mut args = cmd.args();
77 if !args.contains(&"--json".to_string()) {
78 args.push("--json".into());
79 }
80 run_streaming(codex, args, cmd.stdin_prompt(), handler, cancel).await
81}
82
83pub async fn stream_exec_resume<F>(
86 codex: &Codex,
87 cmd: &crate::command::exec::ExecResumeCommand,
88 handler: F,
89) -> Result<()>
90where
91 F: FnMut(JsonLineEvent),
92{
93 let mut args = cmd.args();
94 if !args.contains(&"--json".to_string()) {
95 args.push("--json".into());
96 }
97 run_streaming(
98 codex,
99 args,
100 cmd.stdin_prompt(),
101 handler,
102 std::future::pending(),
103 )
104 .await
105}
106
107pub async fn stream_exec_resume_cancellable<C, F>(
112 codex: &Codex,
113 cmd: &crate::command::exec::ExecResumeCommand,
114 cancel: C,
115 handler: F,
116) -> Result<()>
117where
118 C: std::future::Future<Output = ()> + Send,
119 F: FnMut(JsonLineEvent),
120{
121 let mut args = cmd.args();
122 if !args.contains(&"--json".to_string()) {
123 args.push("--json".into());
124 }
125 run_streaming(codex, args, cmd.stdin_prompt(), handler, cancel).await
126}
127
128async fn run_streaming<C, F>(
133 codex: &Codex,
134 args: Vec<String>,
135 stdin_prompt: Option<&str>,
136 mut handler: F,
137 cancel: C,
138) -> Result<()>
139where
140 C: std::future::Future<Output = ()> + Send,
141 F: FnMut(JsonLineEvent),
142{
143 let span = crate::exec::command_span("codex.stream", codex, &args);
144 let command_args = crate::exec::assemble_args(codex, args);
145 let _span_guard = span.clone().entered();
146
147 debug!(binary = %codex.binary.display(), args = ?command_args, "streaming codex command");
148
149 let mut outcome = crate::exec::SpanOutcome::start(span.clone());
152
153 let mut child_cmd = Command::new(&codex.binary);
154 child_cmd.args(&command_args);
155 if stdin_prompt.is_some() {
156 child_cmd.stdin(std::process::Stdio::piped());
157 } else {
158 child_cmd.stdin(std::process::Stdio::null());
159 }
160 child_cmd.stdout(std::process::Stdio::piped());
161 child_cmd.stderr(std::process::Stdio::piped());
162
163 child_cmd.kill_on_drop(true);
167 crate::exec::own_process_group(&mut child_cmd, codex.process_group);
168 crate::exec::apply_die_with_parent(&mut child_cmd, codex.die_with_parent);
169
170 if let Some(dir) = &codex.working_dir {
171 child_cmd.current_dir(dir);
172 }
173 crate::exec::apply_child_environment(&mut child_cmd, codex.clear_env, &codex.env);
174
175 let mut child = child_cmd.spawn().map_err(|e| Error::Io {
176 message: format!("failed to spawn codex: {e}"),
177 source: e,
178 working_dir: codex.working_dir.clone(),
179 })?;
180
181 let mut group =
185 crate::exec::arm_and_notify(codex.process_group, child.id(), codex.on_spawn.as_ref());
186
187 let stdout = child.stdout.take().expect("stdout was configured as piped");
188 let stderr = child.stderr.take().expect("stderr was configured as piped");
189 let child_stdin = child.stdin.take();
192
193 let stdin_task = async {
197 let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
198 return Ok(());
199 };
200 use tokio::io::AsyncWriteExt;
201 stdin
202 .write_all(prompt.as_bytes())
203 .await
204 .map_err(|e| Error::Io {
205 message: format!("failed to write the prompt to codex stdin: {e}"),
206 source: e,
207 working_dir: codex.working_dir.clone(),
208 })?;
209 stdin.shutdown().await.map_err(|e| Error::Io {
210 message: format!("failed to close codex stdin: {e}"),
211 source: e,
212 working_dir: codex.working_dir.clone(),
213 })
214 };
215
216 let stdout_task = async {
217 let mut reader = BufReader::new(stdout);
218 let mut captured_bytes = 0usize;
219 while let Some(line) = read_bounded_line(
220 &mut reader,
221 &mut captured_bytes,
222 codex.output_limit,
223 crate::OutputStream::Stdout,
224 &codex.working_dir,
225 )
226 .await?
227 {
228 if line.trim_start().starts_with('{') {
229 match serde_json::from_str::<JsonLineEvent>(&line) {
230 Ok(event) => handler(event),
231 Err(source) => {
232 return Err(Error::Json {
233 message: format!("failed to parse JSONL event: {line}"),
234 source,
235 });
236 }
237 }
238 }
239 }
240 Ok::<(), Error>(())
241 };
242
243 let stderr_task = async {
244 let mut reader = BufReader::new(stderr);
245 let mut collected = String::new();
246 let mut captured_bytes = 0usize;
247 while let Some(line) = read_bounded_line(
248 &mut reader,
249 &mut captured_bytes,
250 codex.output_limit,
251 crate::OutputStream::Stderr,
252 &codex.working_dir,
253 )
254 .await?
255 {
256 if !collected.is_empty() {
257 collected.push('\n');
258 }
259 collected.push_str(&line);
260 }
261 Ok::<String, Error>(collected)
262 };
263
264 let wait_task = async {
265 child.wait().await.map_err(|e| Error::Io {
266 message: format!("failed to wait on codex process: {e}"),
267 source: e,
268 working_dir: codex.working_dir.clone(),
269 })
270 };
271 let stream_future = async {
272 let ((), (), stderr_output, status) =
273 tokio::try_join!(stdin_task, stdout_task, stderr_task, wait_task)?;
274 Ok::<_, Error>((stderr_output, status))
275 };
276
277 drop(_span_guard);
281
282 let stop = async {
283 match codex.timeout {
284 Some(timeout) => tokio::select! {
285 () = cancel => StreamStop::Cancelled,
286 () = tokio::time::sleep(timeout) => StreamStop::Timeout(timeout),
287 },
288 None => {
289 cancel.await;
290 StreamStop::Cancelled
291 }
292 }
293 };
294 let finished = tokio::select! {
295 result = stream_future.instrument(span) => Ok(result),
296 reason = stop => Err(reason),
297 };
298
299 let (stderr_output, status) = match finished {
300 Ok(Ok(finished)) => finished,
301 Ok(Err(error)) => {
302 crate::exec::terminate_and_reap(
303 &mut child,
304 &mut group,
305 codex.termination_grace,
306 codex.working_dir.as_deref(),
307 )
308 .await?;
309 outcome.settle("failed", None);
310 return Err(error);
311 }
312 Err(reason) => {
313 crate::exec::terminate_and_reap(
314 &mut child,
315 &mut group,
316 codex.termination_grace,
317 codex.working_dir.as_deref(),
318 )
319 .await?;
320 let error = match reason {
321 StreamStop::Cancelled => {
322 outcome.settle("cancelled", None);
323 Error::Cancelled {
324 grace_seconds: codex.termination_grace.as_secs(),
325 }
326 }
327 StreamStop::Timeout(timeout) => {
328 outcome.settle("timeout", None);
329 Error::Timeout {
330 timeout_seconds: timeout.as_secs(),
331 }
332 }
333 };
334 return Err(error);
335 }
336 };
337
338 let exit_code = status.code().unwrap_or(-1);
339 if !status.success() {
340 outcome.settle("failed", Some(exit_code));
341 return Err(Error::from_command_failure(
342 format!("{} {}", codex.binary.display(), command_args.join(" ")),
343 exit_code,
344 String::new(),
345 stderr_output,
346 codex.working_dir.clone(),
347 ));
348 }
349
350 outcome.settle("ok", Some(exit_code));
351 group.disarm();
352 Ok(())
353}
354
355enum StreamStop {
356 Cancelled,
357 Timeout(std::time::Duration),
358}
359
360async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
361 reader: &mut R,
362 captured_bytes: &mut usize,
363 output_limit: Option<usize>,
364 stream: crate::OutputStream,
365 working_dir: &Option<std::path::PathBuf>,
366) -> Result<Option<String>> {
367 let mut line = Vec::new();
368 loop {
369 let available = reader.fill_buf().await.map_err(|source| Error::Io {
370 message: format!("failed to read {stream} line: {source}"),
371 source,
372 working_dir: working_dir.clone(),
373 })?;
374 if available.is_empty() {
375 if line.is_empty() {
376 return Ok(None);
377 }
378 break;
379 }
380 let take = available
381 .iter()
382 .position(|byte| *byte == b'\n')
383 .map_or(available.len(), |index| index + 1);
384 if output_limit.is_some_and(|limit| captured_bytes.saturating_add(take) > limit) {
385 return Err(Error::OutputLimitExceeded {
386 stream,
387 limit_bytes: output_limit.unwrap_or_default(),
388 });
389 }
390 line.extend_from_slice(&available[..take]);
391 *captured_bytes = captured_bytes.saturating_add(take);
392 let complete = line.last() == Some(&b'\n');
393 reader.consume(take);
394 if complete {
395 line.pop();
396 break;
397 }
398 }
399 if line.last() == Some(&b'\r') {
400 line.pop();
401 }
402 String::from_utf8(line)
403 .map(Some)
404 .map_err(|source| Error::Io {
405 message: format!("failed to decode {stream} line"),
406 source: std::io::Error::new(std::io::ErrorKind::InvalidData, source),
407 working_dir: working_dir.clone(),
408 })
409}
410
411#[cfg(all(test, unix))]
412mod tests {
413 use super::*;
414 use std::sync::{Arc, Mutex};
415
416 fn fake_codex(script_name: &str) -> Codex {
418 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
419 .join("tests")
420 .join(script_name);
421 Codex::builder()
422 .binary("/bin/bash")
423 .arg(script.to_str().unwrap())
424 .build()
425 .expect("bash must exist")
426 }
427
428 #[tokio::test]
429 async fn stream_exec_delivers_events() {
430 let codex = fake_codex("fake-codex.sh");
431 let cmd = crate::command::exec::ExecCommand::new("test prompt").json();
432 let events = Arc::new(Mutex::new(Vec::new()));
433 let events_clone = Arc::clone(&events);
434
435 stream_exec(&codex, &cmd, move |event| {
436 events_clone.lock().unwrap().push(event);
437 })
438 .await
439 .unwrap();
440
441 let events = events.lock().unwrap();
442 assert!(!events.is_empty(), "expected at least one event");
443
444 let types: Vec<&str> = events.iter().map(|e| e.event_type.as_str()).collect();
445 assert!(
446 types.contains(&"thread.started"),
447 "expected thread.started, got: {types:?}"
448 );
449 assert!(
450 types.contains(&"turn.completed"),
451 "expected turn.completed, got: {types:?}"
452 );
453 }
454
455 #[tokio::test]
459 async fn stream_exec_delivers_an_event_while_the_child_is_still_running() {
460 let codex = Codex::builder()
461 .binary("/bin/bash")
462 .arg("-c")
463 .arg(
464 "printf '%s\\n' '{\"type\":\"thread.started\",\"thread_id\":\"thread-early\"}'; sleep 10",
465 )
466 .build()
467 .expect("bash must exist");
468 let cmd = crate::command::exec::ExecCommand::new("probe").json();
469 let (sent, delivered) = tokio::sync::oneshot::channel();
470 let mut sent = Some(sent);
471
472 let task = tokio::spawn(async move {
473 stream_exec(&codex, &cmd, move |event| {
474 if event.thread_id() == Some("thread-early")
475 && let Some(sent) = sent.take()
476 {
477 let _ = sent.send(());
478 }
479 })
480 .await
481 });
482
483 let delivered = tokio::time::timeout(std::time::Duration::from_secs(1), delivered).await;
484 let still_running = !task.is_finished();
485 task.abort();
486 let _ = task.await;
487
488 assert!(delivered.is_ok(), "callback waited for the child to exit");
489 assert!(
490 still_running,
491 "the fixture must still be running when the callback fires"
492 );
493 }
494
495 #[tokio::test]
496 async fn stream_exec_resume_delivers_events() {
497 let codex = fake_codex("fake-codex.sh");
498 let cmd = crate::command::exec::ExecResumeCommand::new().last().json();
499 let events = Arc::new(Mutex::new(Vec::new()));
500 let events_clone = Arc::clone(&events);
501
502 stream_exec_resume(&codex, &cmd, move |event| {
503 events_clone.lock().unwrap().push(event);
504 })
505 .await
506 .unwrap();
507
508 let events = events.lock().unwrap();
509 assert!(!events.is_empty(), "expected at least one event");
510 }
511
512 #[tokio::test]
513 async fn streaming_reports_the_child_before_events_are_delivered() {
514 let order = Arc::new(Mutex::new(Vec::new()));
515 let spawn_order = Arc::clone(&order);
516 let event_order = Arc::clone(&order);
517 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
518 .join("tests")
519 .join("fake-codex.sh");
520 let codex = Codex::builder()
521 .binary("/bin/bash")
522 .arg(script.to_str().unwrap())
523 .on_spawn(Arc::new(move |_| spawn_order.lock().unwrap().push("spawn")))
524 .build()
525 .expect("bash must exist");
526
527 crate::ExecCommand::new("probe")
528 .json()
529 .stream(&codex, move |_| {
530 let mut order = event_order.lock().unwrap();
531 if !order.contains(&"event") {
532 order.push("event");
533 }
534 })
535 .await
536 .unwrap();
537
538 assert_eq!(&order.lock().unwrap()[..2], ["spawn", "event"]);
539 }
540
541 #[tokio::test]
545 async fn cleared_environment_reaches_every_streaming_variant() {
546 let capture = crate::test_support::EnvCapture::new("env-streaming");
547 let codex = crate::test_support::env_capturing_codex(&capture)
548 .clear_env()
549 .env("CODEX_WRAPPER_EXPLICIT", "streaming")
550 .build()
551 .expect("bash must exist");
552
553 crate::ExecCommand::new("opening")
554 .stream(&codex, |_| {})
555 .await
556 .unwrap();
557 let opening_environment = capture.read();
558 assert!(!opening_environment.contains_key("PATH"));
559 assert_eq!(
560 opening_environment
561 .get("CODEX_WRAPPER_EXPLICIT")
562 .map(String::as_str),
563 Some("streaming")
564 );
565
566 crate::ExecCommand::new("stdin")
567 .prompt_via_stdin()
568 .stream(&codex, |_| {})
569 .await
570 .unwrap();
571 let stdin_environment = capture.read();
572 assert!(!stdin_environment.contains_key("PATH"));
573 assert_eq!(
574 stdin_environment
575 .get("CODEX_WRAPPER_EXPLICIT")
576 .map(String::as_str),
577 Some("streaming")
578 );
579
580 crate::ExecResumeCommand::new()
581 .last()
582 .stream(&codex, |_| {})
583 .await
584 .unwrap();
585 let resume_environment = capture.read();
586 assert!(!resume_environment.contains_key("PATH"));
587 assert_eq!(
588 resume_environment
589 .get("CODEX_WRAPPER_EXPLICIT")
590 .map(String::as_str),
591 Some("streaming")
592 );
593 }
594
595 #[tokio::test]
599 async fn stream_exec_classifies_native_rollout_budget_exhaustion() {
600 let codex = fake_codex("fake-codex-rollout-budget.sh");
601 let cmd = crate::command::exec::ExecCommand::new("probe").json();
602 let events = Arc::new(Mutex::new(Vec::new()));
603 let collected = Arc::clone(&events);
604
605 let error = stream_exec(&codex, &cmd, move |event| {
606 collected.lock().unwrap().push(event);
607 })
608 .await
609 .expect_err("captured rollout exhaustion exits non-zero");
610
611 assert_eq!(error.exit_code(), Some(1));
612 let events = events.lock().unwrap();
613 let terminal = events
614 .iter()
615 .find(|event| event.is_turn_failed())
616 .expect("turn.failed must be delivered");
617 assert_eq!(
618 terminal.turn_failure_kind(),
619 Some(crate::TurnFailureKind::RolloutBudgetExhausted)
620 );
621 assert_eq!(terminal.usage(), None);
622 assert_eq!(crate::QueryResult::from_events(events.clone()).result, "ok");
623 }
624
625 #[tokio::test]
626 async fn stream_exec_timeout() {
627 let codex = Codex::builder()
628 .binary("/bin/bash")
629 .arg("-c")
630 .arg("sleep 10")
631 .timeout(std::time::Duration::from_millis(50))
632 .build()
633 .unwrap();
634
635 let cmd = crate::command::exec::ExecCommand::new("test").json();
636 let result = stream_exec(&codex, &cmd, |_| {}).await;
637
638 assert!(
639 matches!(result, Err(Error::Timeout { .. })),
640 "expected timeout error, got: {result:?}"
641 );
642 }
643
644 #[tokio::test]
647 async fn stream_exec_timeout_kills_the_spawned_process() {
648 use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
649
650 let pid_file = PidFile::new("stream-timeout");
651 let codex = blocking_codex(&pid_file)
652 .timeout(std::time::Duration::from_millis(500))
653 .build()
654 .expect("bash must exist");
655
656 let cmd = crate::command::exec::ExecCommand::new("probe").json();
657 let result = stream_exec(&codex, &cmd, |_| {}).await;
658 assert!(
659 matches!(result, Err(Error::Timeout { .. })),
660 "expected timeout error, got: {result:?}"
661 );
662
663 let pid = pid_file.read_pid().await;
664 assert!(
665 wait_until_gone(pid).await,
666 "codex ({pid}) survived the timeout"
667 );
668 }
669
670 #[tokio::test]
672 async fn stream_exec_cancellation_kills_the_spawned_process() {
673 use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
674
675 let pid_file = PidFile::new("stream-cancel");
676 let codex = blocking_codex(&pid_file).build().expect("bash must exist");
677
678 let cmd = crate::command::exec::ExecCommand::new("probe").json();
679 let cancelled = tokio::time::timeout(
680 std::time::Duration::from_millis(500),
681 stream_exec(&codex, &cmd, |_| {}),
682 )
683 .await;
684 assert!(
685 cancelled.is_err(),
686 "fake codex should still have been running, got: {cancelled:?}"
687 );
688
689 let pid = pid_file.read_pid().await;
690 assert!(
691 wait_until_gone(pid).await,
692 "codex ({pid}) survived the dropped future"
693 );
694 }
695
696 #[tokio::test]
697 async fn explicit_stream_cancellation_reaps_before_returning() {
698 use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
699
700 let pid_file = PidFile::new("stream-explicit-cancel");
701 let codex = blocking_codex(&pid_file).build().expect("bash must exist");
702 let cmd = crate::command::exec::ExecCommand::new("probe").json();
703 let cancel = async {
704 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
705 };
706
707 let result = stream_exec_cancellable(&codex, &cmd, cancel, |_| {}).await;
708 assert!(matches!(result, Err(Error::Cancelled { .. })));
709
710 let pid = pid_file.read_pid().await;
711 assert!(
712 wait_until_gone(pid).await,
713 "codex ({pid}) survived explicit stream cancellation"
714 );
715 }
716
717 #[tokio::test]
718 async fn stream_exec_parse_error() {
719 let codex = fake_codex("fake-codex-bad-json.sh");
720 let cmd = crate::command::exec::ExecCommand::new("test").json();
721 let result = stream_exec(&codex, &cmd, |_| {}).await;
722
723 assert!(
724 matches!(result, Err(Error::Json { .. })),
725 "expected json parse error, got: {result:?}"
726 );
727 }
728
729 #[tokio::test]
730 async fn streaming_enforces_the_raw_output_ceiling() {
731 let codex = Codex::builder()
732 .binary("/bin/bash")
733 .arg("-c")
734 .arg("for ((i=0; i<4096; i++)); do printf x; done; sleep 3")
735 .output_limit(128)
736 .timeout(std::time::Duration::from_secs(1))
737 .build()
738 .expect("bash must exist");
739 let cmd = crate::command::exec::ExecCommand::new("probe").json();
740
741 let result = stream_exec(&codex, &cmd, |_| {}).await;
742
743 assert!(matches!(
744 result,
745 Err(Error::OutputLimitExceeded {
746 stream: crate::OutputStream::Stdout,
747 limit_bytes: 128,
748 })
749 ));
750 }
751}