codex-wrapper 0.4.5

A type-safe Codex CLI wrapper for Rust
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
//! Streaming execution for `codex exec` commands.
//!
//! Instead of buffering all JSONL output and returning it at once,
//! the streaming API pipes stdout from the child process and delivers
//! each [`JsonLineEvent`] to a caller-supplied callback as soon as it
//! arrives.
//!
//! # Example
//!
//! ```no_run
//! use codex_wrapper::{Codex, ExecCommand, JsonLineEvent};
//!
//! # async fn example() -> codex_wrapper::Result<()> {
//! let codex = Codex::builder().build()?;
//! let cmd = ExecCommand::new("what is 2+2?").ephemeral();
//!
//! cmd.stream(&codex, |event: JsonLineEvent| {
//!     println!("{}: {:?}", event.event_type, event.extra);
//! })
//! .await?;
//! # Ok(())
//! # }
//! ```

use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
use tracing::{Instrument, debug};

use crate::Codex;
use crate::command::CodexCommand;
use crate::error::{Error, Result};
use crate::types::JsonLineEvent;

/// Stream JSONL events from `codex exec <prompt>`, invoking `handler` for each
/// parsed [`JsonLineEvent`].
///
/// The child's stderr is drained concurrently and returned in the error if the
/// process exits with a non-zero status.
pub async fn stream_exec<F>(
    codex: &Codex,
    cmd: &crate::command::exec::ExecCommand,
    handler: F,
) -> Result<()>
where
    F: FnMut(JsonLineEvent),
{
    let args = cmd.clone().json().args();
    run_streaming(
        codex,
        args,
        cmd.stdin_prompt(),
        handler,
        std::future::pending(),
    )
    .await
}

/// Stream JSONL events until the command completes or `cancel` resolves.
///
/// Cancellation terminates the owned process group, waits through the
/// client's configured grace period, and reaps the direct child before
/// returning [`Error::Cancelled`], or [`Error::CleanupFailed`] wrapping it if
/// stopping or reaping the child failed. Shutdown output is drained and discarded;
/// handlers stop receiving events after cancellation. Detached tools require
/// the CLI's cooperation; see [`crate::CodexBuilder::termination_signal`].
pub async fn stream_exec_cancellable<C, F>(
    codex: &Codex,
    cmd: &crate::command::exec::ExecCommand,
    cancel: C,
    handler: F,
) -> Result<()>
where
    C: std::future::Future<Output = ()> + Send,
    F: FnMut(JsonLineEvent),
{
    let args = cmd.clone().json().args();
    run_streaming(codex, args, cmd.stdin_prompt(), handler, cancel).await
}

/// Stream JSONL events from `codex exec resume`, invoking `handler` for each
/// parsed [`JsonLineEvent`].
pub async fn stream_exec_resume<F>(
    codex: &Codex,
    cmd: &crate::command::exec::ExecResumeCommand,
    handler: F,
) -> Result<()>
where
    F: FnMut(JsonLineEvent),
{
    let args = cmd.clone().json().args();
    run_streaming(
        codex,
        args,
        cmd.stdin_prompt(),
        handler,
        std::future::pending(),
    )
    .await
}

/// Stream resumed-turn JSONL events until completion or cancellation.
///
/// This has the same settled process-cleanup contract as
/// [`stream_exec_cancellable`].
pub async fn stream_exec_resume_cancellable<C, F>(
    codex: &Codex,
    cmd: &crate::command::exec::ExecResumeCommand,
    cancel: C,
    handler: F,
) -> Result<()>
where
    C: std::future::Future<Output = ()> + Send,
    F: FnMut(JsonLineEvent),
{
    let args = cmd.clone().json().args();
    run_streaming(codex, args, cmd.stdin_prompt(), handler, cancel).await
}

/// Core streaming implementation shared by both exec variants.
///
/// `stdin_prompt` carries the prompt for a `codex exec -` run, where it is
/// delivered on stdin rather than in argv.
async fn run_streaming<C, F>(
    codex: &Codex,
    args: Vec<String>,
    stdin_prompt: Option<&str>,
    mut handler: F,
    cancel: C,
) -> Result<()>
where
    C: std::future::Future<Output = ()> + Send,
    F: FnMut(JsonLineEvent),
{
    let span = crate::exec::command_span("codex.stream", codex, &args);
    let command_args = crate::exec::assemble_args(codex, args);
    let _span_guard = span.clone().entered();

    debug!(arg_count = command_args.len(), "streaming codex command");

    // Settles on every exit below, and on drop for the one that has no exit:
    // a cancelled stream, which is the outcome most easily missed.
    let mut outcome = crate::exec::SpanOutcome::start(span.clone());

    let mut child_cmd = Command::new(&codex.binary);
    child_cmd.args(&command_args);
    if stdin_prompt.is_some() {
        child_cmd.stdin(std::process::Stdio::piped());
    } else {
        child_cmd.stdin(std::process::Stdio::null());
    }
    child_cmd.stdout(std::process::Stdio::piped());
    child_cmd.stderr(std::process::Stdio::piped());

    // Kill the child if this future is dropped: on timeout, on caller
    // cancellation, or on task abort. Without this, tokio detaches the child
    // and codex keeps running with no handle left to stop it.
    child_cmd.kill_on_drop(true);
    crate::exec::own_process_group(&mut child_cmd, codex.process_group);
    crate::exec::apply_die_with_parent(&mut child_cmd, codex.die_with_parent);

    if let Some(dir) = &codex.working_dir {
        child_cmd.current_dir(dir);
    }
    crate::exec::apply_child_environment(&mut child_cmd, codex.clear_env, &codex.env);

    let mut child = child_cmd.spawn().map_err(|e| Error::Io {
        message: format!("failed to spawn codex: {e}"),
        source: e,
        working_dir: codex.working_dir.clone(),
    })?;

    // Armed for the whole stream. Dropping this future signals the group,
    // which reaches descendants still in that group; kill_on_drop alone only
    // stops the direct child. Detached tools require cooperative cleanup.
    let mut group = crate::exec::arm_and_notify(
        codex.process_group,
        codex.termination_signal,
        child.id(),
        codex.on_spawn.as_ref(),
    );

    let mut stdout = BufReader::new(child.stdout.take().expect("stdout was configured as piped"));
    let mut stderr = BufReader::new(child.stderr.take().expect("stderr was configured as piped"));
    // Taken up front so the write does not borrow `child`, which the wait
    // below needs.
    let child_stdin = child.stdin.take();

    // Write the prompt and close the handle, so the CLI stops waiting for
    // more. This runs as part of the streamed future rather than before it,
    // so a prompt larger than the pipe buffer cannot block the readers.
    let stdin_task = async {
        let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
            return Ok(());
        };
        use tokio::io::AsyncWriteExt;
        stdin
            .write_all(prompt.as_bytes())
            .await
            .map_err(|e| Error::Io {
                message: format!("failed to write the prompt to codex stdin: {e}"),
                source: e,
                working_dir: codex.working_dir.clone(),
            })?;
        stdin.shutdown().await.map_err(|e| Error::Io {
            message: format!("failed to close codex stdin: {e}"),
            source: e,
            working_dir: codex.working_dir.clone(),
        })
    };

    let stdout_task = async {
        let mut captured_bytes = 0usize;
        while let Some(line) = read_bounded_line(
            &mut stdout,
            &mut captured_bytes,
            codex.output_limit,
            crate::OutputStream::Stdout,
            &codex.working_dir,
        )
        .await?
        {
            if line.trim_start().starts_with('{') {
                match serde_json::from_str::<JsonLineEvent>(&line) {
                    Ok(event) => handler(event),
                    Err(source) => {
                        return Err(Error::Json {
                            message: format!("failed to parse JSONL event: {line}"),
                            source,
                        });
                    }
                }
            }
        }
        Ok::<(), Error>(())
    };

    let stderr_task = async {
        let mut collected = String::new();
        let mut captured_bytes = 0usize;
        while let Some(line) = read_bounded_line(
            &mut stderr,
            &mut captured_bytes,
            codex.output_limit,
            crate::OutputStream::Stderr,
            &codex.working_dir,
        )
        .await?
        {
            if !collected.is_empty() {
                collected.push('\n');
            }
            collected.push_str(&line);
        }
        Ok::<String, Error>(collected)
    };

    let stream_future = async {
        let ((), (), stderr_output) = tokio::try_join!(stdin_task, stdout_task, stderr_task)?;
        // Keep the leader unreaped until all readers finish so a cancellation
        // never signals a group whose leader PID could already be reused.
        let status = child.wait().await.map_err(|e| Error::Io {
            message: format!("failed to wait on codex process: {e}"),
            source: e,
            working_dir: codex.working_dir.clone(),
        })?;
        Ok::<_, Error>((stderr_output, status))
    };

    // Dropped explicitly before awaiting: the guard exists so the span is the
    // parent of everything above, while the await below must not hold it
    // across a yield point.
    drop(_span_guard);

    let stop = async {
        match codex.timeout {
            Some(timeout) => tokio::select! {
                () = cancel => StreamStop::Cancelled,
                () = tokio::time::sleep(timeout) => StreamStop::Timeout(timeout),
            },
            None => {
                cancel.await;
                StreamStop::Cancelled
            }
        }
    };
    let finished = tokio::select! {
        result = stream_future.instrument(span) => Ok(result),
        reason = stop => Err(reason),
    };

    let (stderr_output, status) = match finished {
        Ok(Ok(finished)) => finished,
        Ok(Err(error)) => {
            let cleanup = crate::exec::terminate_and_reap_draining(
                &mut child,
                &mut group,
                codex.termination_grace,
                codex.working_dir.as_deref(),
                &mut stdout,
                &mut stderr,
            )
            .await;
            let label = if cleanup.is_ok() {
                "failed"
            } else {
                "cleanup_failed"
            };
            outcome.settle(label, None);
            return Err(Error::after_cleanup(error, cleanup));
        }
        Err(reason) => {
            let cleanup = crate::exec::terminate_and_reap_draining(
                &mut child,
                &mut group,
                codex.termination_grace,
                codex.working_dir.as_deref(),
                &mut stdout,
                &mut stderr,
            )
            .await;
            let (label, error) = match reason {
                StreamStop::Cancelled => (
                    "cancelled",
                    Error::Cancelled {
                        grace_seconds: codex.termination_grace.as_secs(),
                    },
                ),
                StreamStop::Timeout(timeout) => (
                    "timeout",
                    Error::Timeout {
                        timeout_seconds: timeout.as_secs(),
                    },
                ),
            };
            // Matches the buffered path, so a span never reads as a settled
            // stop when the child may not have been reaped.
            let label = if cleanup.is_ok() {
                label
            } else {
                "cleanup_failed"
            };
            outcome.settle(label, None);
            return Err(Error::after_cleanup(error, cleanup));
        }
    };

    // A nonzero exit is also a completed, reaped run, not a drop cleanup.
    group.disarm();
    let exit_code = status.code().unwrap_or(-1);
    if !status.success() {
        outcome.settle("failed", Some(exit_code));
        return Err(Error::from_command_failure(
            format!("{} {}", codex.binary.display(), command_args.join(" ")),
            exit_code,
            String::new(),
            stderr_output,
            codex.working_dir.clone(),
        ));
    }

    outcome.settle("ok", Some(exit_code));
    Ok(())
}

enum StreamStop {
    Cancelled,
    Timeout(std::time::Duration),
}

pub(crate) async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
    reader: &mut R,
    captured_bytes: &mut usize,
    output_limit: Option<usize>,
    stream: crate::OutputStream,
    working_dir: &Option<std::path::PathBuf>,
) -> Result<Option<String>> {
    let mut line = Vec::new();
    loop {
        let available = reader.fill_buf().await.map_err(|source| Error::Io {
            message: format!("failed to read {stream} line: {source}"),
            source,
            working_dir: working_dir.clone(),
        })?;
        if available.is_empty() {
            if line.is_empty() {
                return Ok(None);
            }
            break;
        }
        let take = available
            .iter()
            .position(|byte| *byte == b'\n')
            .map_or(available.len(), |index| index + 1);
        if output_limit.is_some_and(|limit| captured_bytes.saturating_add(take) > limit) {
            return Err(Error::OutputLimitExceeded {
                stream,
                limit_bytes: output_limit.unwrap_or_default(),
            });
        }
        line.extend_from_slice(&available[..take]);
        *captured_bytes = captured_bytes.saturating_add(take);
        let complete = line.last() == Some(&b'\n');
        reader.consume(take);
        if complete {
            line.pop();
            break;
        }
    }
    if line.last() == Some(&b'\r') {
        line.pop();
    }
    String::from_utf8(line)
        .map(Some)
        .map_err(|source| Error::Io {
            message: format!("failed to decode {stream} line"),
            source: std::io::Error::new(std::io::ErrorKind::InvalidData, source),
            working_dir: working_dir.clone(),
        })
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// Build a [`Codex`] client that uses `bash` to run the fake-codex script.
    fn fake_codex(script_name: &str) -> Codex {
        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join(script_name);
        Codex::builder()
            .binary("/bin/bash")
            .arg(script.to_str().unwrap())
            .build()
            .expect("bash must exist")
    }

    #[tokio::test]
    async fn stream_exec_delivers_events() {
        let codex = fake_codex("fake-codex.sh");
        let cmd = crate::command::exec::ExecCommand::new("test prompt").json();
        let events = Arc::new(Mutex::new(Vec::new()));
        let events_clone = Arc::clone(&events);

        stream_exec(&codex, &cmd, move |event| {
            events_clone.lock().unwrap().push(event);
        })
        .await
        .unwrap();

        let events = events.lock().unwrap();
        assert!(!events.is_empty(), "expected at least one event");

        let types: Vec<&str> = events.iter().map(|e| e.event_type.as_str()).collect();
        assert!(
            types.contains(&"thread.started"),
            "expected thread.started, got: {types:?}"
        );
        assert!(
            types.contains(&"turn.completed"),
            "expected turn.completed, got: {types:?}"
        );
    }

    /// The API promises delivery as events arrive. Buffering until stdout
    /// closes loses a thread id when a long-running process or its host dies
    /// after `thread.started`, which is the durability use case for streaming.
    #[tokio::test]
    async fn stream_exec_delivers_an_event_while_the_child_is_still_running() {
        let codex = Codex::builder()
            .binary("/bin/bash")
            .arg("-c")
            .arg(
                "printf '%s\\n' '{\"type\":\"thread.started\",\"thread_id\":\"thread-early\"}'; sleep 10",
            )
            .build()
            .expect("bash must exist");
        let cmd = crate::command::exec::ExecCommand::new("probe").json();
        let (sent, delivered) = tokio::sync::oneshot::channel();
        let mut sent = Some(sent);

        let task = tokio::spawn(async move {
            stream_exec(&codex, &cmd, move |event| {
                if event.thread_id() == Some("thread-early")
                    && let Some(sent) = sent.take()
                {
                    let _ = sent.send(());
                }
            })
            .await
        });

        let delivered = tokio::time::timeout(std::time::Duration::from_secs(1), delivered).await;
        let still_running = !task.is_finished();
        task.abort();
        let _ = task.await;

        assert!(delivered.is_ok(), "callback waited for the child to exit");
        assert!(
            still_running,
            "the fixture must still be running when the callback fires"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn streaming_interrupt_drains_without_parsing_or_delivering_shutdown_bytes() {
        let fixture = crate::test_support::InterruptFixture::new("stream-interrupt-drain");
        let codex = fixture
            .builder()
            .termination_signal(crate::TerminationSignal::Interrupt)
            .output_limit(64)
            .build()
            .unwrap();
        let command = crate::ExecCommand::from_stdin("prompt");
        let mut calls = 0;
        let result =
            stream_exec_cancellable(&codex, &command, fixture.detached_ready(), |_| calls += 1)
                .await;
        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
        assert_eq!(calls, 0, "shutdown bytes must not reach the event handler");
        assert!(fixture.marker(".int").exists());
        assert!(
            fixture.marker(".cleaned").exists(),
            "shutdown output blocked cleanup"
        );
        fixture.assert_stopped().await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn streaming_resume_interrupt_ignored_uses_hard_fallback() {
        let fixture = crate::test_support::InterruptFixture::new("stream-resume-interrupt-ignored");
        let codex = fixture
            .builder()
            .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
            .termination_signal(crate::TerminationSignal::Interrupt)
            .termination_grace(std::time::Duration::from_millis(100))
            .build()
            .unwrap();
        let command = crate::ExecResumeCommand::new().last();
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(3),
            stream_exec_resume_cancellable(&codex, &command, fixture.ready(), |_| {}),
        )
        .await
        .expect("hard fallback exceeded the grace budget");
        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
        assert!(fixture.marker(".int").exists());
        fixture.assert_stopped().await;
    }

    #[tokio::test]
    async fn stream_exec_resume_delivers_events() {
        let codex = fake_codex("fake-codex.sh");
        let cmd = crate::command::exec::ExecResumeCommand::new().last().json();
        let events = Arc::new(Mutex::new(Vec::new()));
        let events_clone = Arc::clone(&events);

        stream_exec_resume(&codex, &cmd, move |event| {
            events_clone.lock().unwrap().push(event);
        })
        .await
        .unwrap();

        let events = events.lock().unwrap();
        assert!(!events.is_empty(), "expected at least one event");
    }

    #[tokio::test]
    async fn streaming_reports_the_child_before_events_are_delivered() {
        let order = Arc::new(Mutex::new(Vec::new()));
        let spawn_order = Arc::clone(&order);
        let event_order = Arc::clone(&order);
        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fake-codex.sh");
        let codex = Codex::builder()
            .binary("/bin/bash")
            .arg(script.to_str().unwrap())
            .on_spawn(Arc::new(move |_| spawn_order.lock().unwrap().push("spawn")))
            .build()
            .expect("bash must exist");

        crate::ExecCommand::new("probe")
            .json()
            .stream(&codex, move |_| {
                let mut order = event_order.lock().unwrap();
                if !order.contains(&"event") {
                    order.push("event");
                }
            })
            .await
            .unwrap();

        assert_eq!(&order.lock().unwrap()[..2], ["spawn", "event"]);
    }

    /// Streaming owns a separate process builder from buffered execution.
    /// Cover opening, stdin opening, and resume so none can regress to ambient
    /// inheritance while the others stay isolated.
    #[tokio::test]
    async fn cleared_environment_reaches_every_streaming_variant() {
        let capture = crate::test_support::EnvCapture::new("env-streaming");
        let codex = crate::test_support::env_capturing_codex(&capture)
            .clear_env()
            .env("CODEX_WRAPPER_EXPLICIT", "streaming")
            .build()
            .expect("bash must exist");

        crate::ExecCommand::new("opening")
            .stream(&codex, |_| {})
            .await
            .unwrap();
        let opening_environment = capture.read();
        assert!(!opening_environment.contains_key("PATH"));
        assert_eq!(
            opening_environment
                .get("CODEX_WRAPPER_EXPLICIT")
                .map(String::as_str),
            Some("streaming")
        );

        crate::ExecCommand::new("stdin")
            .prompt_via_stdin()
            .stream(&codex, |_| {})
            .await
            .unwrap();
        let stdin_environment = capture.read();
        assert!(!stdin_environment.contains_key("PATH"));
        assert_eq!(
            stdin_environment
                .get("CODEX_WRAPPER_EXPLICIT")
                .map(String::as_str),
            Some("streaming")
        );

        crate::ExecResumeCommand::new()
            .last()
            .stream(&codex, |_| {})
            .await
            .unwrap();
        let resume_environment = capture.read();
        assert!(!resume_environment.contains_key("PATH"));
        assert_eq!(
            resume_environment
                .get("CODEX_WRAPPER_EXPLICIT")
                .map(String::as_str),
            Some("streaming")
        );
    }

    /// Contract captured from a paid 0.145.0 run: the callback receives the
    /// typed terminal before the process reports its non-zero exit, including
    /// an assistant message but no fabricated token counts.
    #[tokio::test]
    async fn stream_exec_classifies_native_rollout_budget_exhaustion() {
        let codex = fake_codex("fake-codex-rollout-budget.sh");
        let cmd = crate::command::exec::ExecCommand::new("probe").json();
        let events = Arc::new(Mutex::new(Vec::new()));
        let collected = Arc::clone(&events);

        let error = stream_exec(&codex, &cmd, move |event| {
            collected.lock().unwrap().push(event);
        })
        .await
        .expect_err("captured rollout exhaustion exits non-zero");

        assert_eq!(error.exit_code(), Some(1));
        let events = events.lock().unwrap();
        let terminal = events
            .iter()
            .find(|event| event.is_turn_failed())
            .expect("turn.failed must be delivered");
        assert_eq!(
            terminal.turn_failure_kind(),
            Some(crate::TurnFailureKind::RolloutBudgetExhausted)
        );
        assert_eq!(terminal.usage(), None);
        assert_eq!(crate::QueryResult::from_events(events.clone()).result, "ok");
    }

    #[tokio::test]
    async fn stream_exec_timeout() {
        let codex = Codex::builder()
            .binary("/bin/bash")
            .arg("-c")
            .arg("sleep 10")
            .timeout(std::time::Duration::from_millis(50))
            .build()
            .unwrap();

        let cmd = crate::command::exec::ExecCommand::new("test").json();
        let result = stream_exec(&codex, &cmd, |_| {}).await;

        assert!(
            matches!(result, Err(Error::Timeout { .. })),
            "expected timeout error, got: {result:?}"
        );
    }

    /// The streaming path drops both `stream_future` and the child it borrows.
    /// Without `kill_on_drop`, the timeout above would leave codex running.
    #[tokio::test]
    async fn stream_exec_timeout_kills_the_spawned_process() {
        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};

        let pid_file = PidFile::new("stream-timeout");
        let codex = blocking_codex(&pid_file)
            .timeout(std::time::Duration::from_millis(500))
            .build()
            .expect("bash must exist");

        let cmd = crate::command::exec::ExecCommand::new("probe").json();
        let result = stream_exec(&codex, &cmd, |_| {}).await;
        assert!(
            matches!(result, Err(Error::Timeout { .. })),
            "expected timeout error, got: {result:?}"
        );

        let pid = pid_file.read_pid().await;
        assert!(
            wait_until_gone(pid).await,
            "codex ({pid}) survived the timeout"
        );
    }

    /// The caller dropping the stream future, with no wrapper timeout.
    #[tokio::test]
    async fn stream_exec_cancellation_kills_the_spawned_process() {
        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};

        let pid_file = PidFile::new("stream-cancel");
        let codex = blocking_codex(&pid_file).build().expect("bash must exist");

        let cmd = crate::command::exec::ExecCommand::new("probe").json();
        let cancelled = tokio::time::timeout(
            std::time::Duration::from_millis(500),
            stream_exec(&codex, &cmd, |_| {}),
        )
        .await;
        assert!(
            cancelled.is_err(),
            "fake codex should still have been running, got: {cancelled:?}"
        );

        let pid = pid_file.read_pid().await;
        assert!(
            wait_until_gone(pid).await,
            "codex ({pid}) survived the dropped future"
        );
    }

    #[tokio::test]
    async fn explicit_stream_cancellation_reaps_before_returning() {
        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};

        let pid_file = PidFile::new("stream-explicit-cancel");
        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
        let cmd = crate::command::exec::ExecCommand::new("probe").json();
        let cancel = async {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        };

        let result = stream_exec_cancellable(&codex, &cmd, cancel, |_| {}).await;
        assert!(matches!(result, Err(Error::Cancelled { .. })));

        let pid = pid_file.read_pid().await;
        assert!(
            wait_until_gone(pid).await,
            "codex ({pid}) survived explicit stream cancellation"
        );
    }

    #[tokio::test]
    async fn dropping_during_stream_cancellation_grace_kills_the_group() {
        let fixture = crate::test_support::GracePeriodFixture::new("stream-cancel-grace-drop");
        let codex = fixture.builder().build().unwrap();
        let cmd = crate::ExecCommand::new("probe").json();
        fixture
            .assert_drop_during_grace(stream_exec_cancellable(
                &codex,
                &cmd,
                fixture.ready(),
                |_| {},
            ))
            .await;
    }

    #[tokio::test]
    async fn stream_exec_parse_error() {
        let codex = fake_codex("fake-codex-bad-json.sh");
        let cmd = crate::command::exec::ExecCommand::new("test").json();
        let result = stream_exec(&codex, &cmd, |_| {}).await;

        assert!(
            matches!(result, Err(Error::Json { .. })),
            "expected json parse error, got: {result:?}"
        );
    }

    #[tokio::test]
    async fn streaming_enforces_the_raw_output_ceiling() {
        let codex = Codex::builder()
            .binary("/bin/bash")
            .arg("-c")
            .arg("for ((i=0; i<4096; i++)); do printf x; done; sleep 3")
            .output_limit(128)
            .timeout(std::time::Duration::from_secs(1))
            .build()
            .expect("bash must exist");
        let cmd = crate::command::exec::ExecCommand::new("probe").json();

        let result = stream_exec(&codex, &cmd, |_| {}).await;

        assert!(matches!(
            result,
            Err(Error::OutputLimitExceeded {
                stream: crate::OutputStream::Stdout,
                limit_bytes: 128,
            })
        ));
    }

    // -----------------------------------------------------------------
    // Failed cleanup is not reported as a settled stop
    //
    // The injection replaces the cleanup result after the real termination
    // and wait have run, so these cover reporting, not that a syscall fails.
    // -----------------------------------------------------------------

    /// The stop reason inside a [`Error::CleanupFailed`] whose cleanup half
    /// is the injected failure, not some other error.
    fn injected_cleanup_reason(result: Result<()>) -> Error {
        match result {
            Err(Error::CleanupFailed { reason, cleanup }) => {
                assert!(
                    cleanup.to_string().contains("injected cleanup failure"),
                    "{cleanup:?}"
                );
                *reason
            }
            other => panic!("expected CleanupFailed, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn failed_stream_cleanup_after_cancellation_is_not_a_bare_cancel() {
        let pid_file = crate::test_support::PidFile::new("stream-cleanup-failed-cancel");
        let codex = crate::test_support::blocking_codex(&pid_file)
            .termination_grace(std::time::Duration::from_millis(10))
            .build()
            .unwrap();
        let cmd = crate::command::exec::ExecCommand::new("probe").json();
        let cancel_soon = || tokio::time::sleep(std::time::Duration::from_millis(100));

        let injection = crate::exec::CleanupFailureInjection::arm();
        let result = stream_exec_cancellable(&codex, &cmd, cancel_soon(), |_| {}).await;
        let reason = injected_cleanup_reason(result);
        assert!(matches!(reason, Error::Cancelled { .. }), "{reason:?}");

        drop(injection);
        let result = stream_exec_cancellable(&codex, &cmd, cancel_soon(), |_| {}).await;
        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
    }

    #[tokio::test]
    async fn failed_stream_cleanup_after_timeout_keeps_the_timeout_as_reason() {
        let pid_file = crate::test_support::PidFile::new("stream-cleanup-failed-timeout");
        let codex = crate::test_support::blocking_codex(&pid_file)
            .timeout(std::time::Duration::from_millis(100))
            .termination_grace(std::time::Duration::from_millis(10))
            .build()
            .unwrap();
        let cmd = crate::command::exec::ExecCommand::new("probe").json();

        let _injection = crate::exec::CleanupFailureInjection::arm();
        let result = stream_exec(&codex, &cmd, |_| {}).await;
        let reason = injected_cleanup_reason(result);
        assert!(matches!(reason, Error::Timeout { .. }), "{reason:?}");
    }

    /// A parse failure ends the stream through the error branch rather than a
    /// stop signal, and must report a failed cleanup the same way.
    #[tokio::test]
    async fn failed_stream_cleanup_after_a_parse_error_keeps_the_json_error() {
        let codex = fake_codex("fake-codex-bad-json.sh");
        let cmd = crate::command::exec::ExecCommand::new("test").json();

        let injection = crate::exec::CleanupFailureInjection::arm();
        let result = stream_exec(&codex, &cmd, |_| {}).await;
        let reason = injected_cleanup_reason(result);
        assert!(matches!(reason, Error::Json { .. }), "{reason:?}");

        drop(injection);
        let result = stream_exec(&codex, &cmd, |_| {}).await;
        assert!(matches!(result, Err(Error::Json { .. })), "{result:?}");
    }

    #[tokio::test]
    async fn failed_stream_cleanup_after_an_output_limit_keeps_the_limit() {
        let codex = Codex::builder()
            .binary("/bin/bash")
            .arg("-c")
            .arg("for ((i=0; i<4096; i++)); do printf x; done; sleep 3")
            .output_limit(128)
            .timeout(std::time::Duration::from_secs(1))
            .build()
            .expect("bash must exist");
        let cmd = crate::command::exec::ExecCommand::new("probe").json();

        let _injection = crate::exec::CleanupFailureInjection::arm();
        let result = stream_exec(&codex, &cmd, |_| {}).await;
        let reason = injected_cleanup_reason(result);
        assert!(
            matches!(
                reason,
                Error::OutputLimitExceeded {
                    stream: crate::OutputStream::Stdout,
                    limit_bytes: 128,
                }
            ),
            "{reason:?}"
        );
    }
}