batty-cli 0.11.63

Supervised agent execution for software teams
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
//! Codex SDK-mode shim runtime: communicates with Codex via JSONL events
//! from `codex exec --json` instead of screen-scraping a PTY.
//!
//! Unlike the Claude SDK runtime (persistent subprocess with stdin NDJSON),
//! Codex uses a **spawn-per-message** model: each `SendMessage` launches a
//! new `codex exec --json` subprocess. Multi-turn context is preserved via
//! `codex exec resume <thread_id>`.
//!
//! Emits the same `Command`/`Event` protocol to the orchestrator as the
//! PTY runtime, making it transparent to all upstream consumers.

use std::collections::VecDeque;
use std::io::Write;
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use chrono::TimeZone;
use regex::Regex;

use super::codex_types::{self, CodexEvent};
use super::common::{
    self, MAX_QUEUE_DEPTH, QueuedMessage, SESSION_STATS_INTERVAL_SECS, drain_queue_errors,
    format_injected_message,
};
use super::protocol::{Channel, Command as ShimCommand, Event, ShimState};
use super::pty_log::PtyLogWriter;
use super::runtime::ShimArgs;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

const PROCESS_EXIT_POLL_MS: u64 = 100;
const GROUP_TERM_GRACE_SECS: u64 = 2;

// ---------------------------------------------------------------------------
// Shared state
// ---------------------------------------------------------------------------

struct CodexState {
    state: ShimState,
    state_changed_at: Instant,
    started_at: Instant,
    /// Thread ID from the first `thread.started` event, used for resume.
    thread_id: Option<String>,
    /// Accumulated agent response text for the current turn.
    accumulated_response: String,
    /// Message ID of the currently pending (in-flight) message.
    pending_message_id: Option<String>,
    /// Messages queued while the agent is in Working state.
    message_queue: VecDeque<QueuedMessage>,
    /// Total bytes of response text received.
    cumulative_output_bytes: u64,
    /// The codex binary name/path.
    program: String,
    /// Working directory for spawning subprocesses.
    cwd: std::path::PathBuf,
    /// Whether a ContextApproaching event has already been emitted this session.
    context_approaching_emitted: bool,
    /// When a backend quota block expires, if known.
    quota_blocked_until: Option<u64>,
}

// ---------------------------------------------------------------------------
// Main entry point
// ---------------------------------------------------------------------------

/// Run the Codex SDK-mode shim. This function does not return until the shim exits.
///
/// Unlike the Claude SDK runtime, each message spawns a new `codex exec --json`
/// subprocess. The shim manages the lifecycle per-message and emits the same
/// `Command`/`Event` protocol to the orchestrator.
pub fn run_codex_sdk(args: ShimArgs, channel: Channel) -> Result<()> {
    eprintln!("[shim-codex {}] started (spawn-per-message mode)", args.id);

    // Shared state
    let state = Arc::new(Mutex::new(CodexState {
        state: ShimState::Idle,
        state_changed_at: Instant::now(),
        started_at: Instant::now(),
        thread_id: None,
        accumulated_response: String::new(),
        pending_message_id: None,
        message_queue: VecDeque::new(),
        cumulative_output_bytes: 0,
        program: "codex".to_string(),
        cwd: args.cwd.clone(),
        context_approaching_emitted: false,
        quota_blocked_until: None,
    }));

    // PTY log writer (optional — writes readable text for tmux display)
    let pty_log: Option<Arc<Mutex<PtyLogWriter>>> = args
        .pty_log_path
        .as_deref()
        .map(|p| PtyLogWriter::new(p).context("failed to create PTY log"))
        .transpose()?
        .map(|w| Arc::new(Mutex::new(w)));

    // Channel clones
    let mut cmd_channel = channel;

    // Emit Ready immediately — no persistent subprocess to wait for.
    cmd_channel.send(&Event::Ready)?;

    // Session stats thread
    let state_stats = Arc::clone(&state);
    let mut stats_channel = cmd_channel
        .try_clone()
        .context("failed to clone channel for stats")?;
    thread::spawn(move || {
        loop {
            thread::sleep(Duration::from_secs(SESSION_STATS_INTERVAL_SECS));
            let st = state_stats.lock().unwrap();
            if st.state == ShimState::Dead {
                return;
            }
            let output_bytes = st.cumulative_output_bytes;
            let uptime_secs = st.started_at.elapsed().as_secs();
            drop(st);

            if stats_channel
                .send(&Event::SessionStats {
                    output_bytes,
                    uptime_secs,
                    input_tokens: 0,
                    output_tokens: 0,
                    context_usage_pct: None,
                })
                .is_err()
            {
                return;
            }
        }
    });

    // Command loop (main thread)
    let state_cmd = Arc::clone(&state);
    let shim_id = args.id.clone();
    loop {
        let cmd = match cmd_channel.recv::<ShimCommand>() {
            Ok(Some(c)) => c,
            Ok(None) => {
                eprintln!("[shim-codex {shim_id}] orchestrator disconnected");
                break;
            }
            Err(e) => {
                eprintln!("[shim-codex {shim_id}] channel error: {e}");
                break;
            }
        };

        match cmd {
            ShimCommand::SendMessage {
                from,
                body,
                message_id,
            } => {
                let delivery_id = message_id.clone();
                let mut st = state_cmd.lock().unwrap();
                if let Some(until) = st.quota_blocked_until {
                    let now = current_unix_secs();
                    if until > now {
                        let retry_at_label = format_quota_retry_label(until);
                        let reason = format!(
                            "backend quota is blocked until {retry_at_label}; message not sent"
                        );
                        drop(st);
                        cmd_channel.send(&Event::QuotaBlocked {
                            message: reason.clone(),
                            retry_at_epoch_secs: Some(until),
                            retry_at_label: Some(retry_at_label),
                        })?;
                        continue;
                    }
                    st.quota_blocked_until = None;
                }
                match st.state {
                    ShimState::Idle => {
                        st.pending_message_id = message_id;
                        st.accumulated_response.clear();
                        st.state = ShimState::Working;
                        st.state_changed_at = Instant::now();
                        let thread_id = st.thread_id.clone();
                        let program = st.program.clone();
                        let cwd = st.cwd.clone();
                        drop(st);

                        cmd_channel.send(&Event::StateChanged {
                            from: ShimState::Idle,
                            to: ShimState::Working,
                            summary: String::new(),
                        })?;
                        if let Some(id) = delivery_id {
                            cmd_channel.send(&Event::MessageDelivered { id })?;
                        }

                        // Spawn codex exec subprocess for this message
                        let text = format_injected_message(&from, &body);
                        let (exec_program, exec_args) =
                            codex_types::codex_sdk_args(&program, thread_id.as_deref());

                        let mut evt_channel = cmd_channel
                            .try_clone()
                            .context("failed to clone channel for codex exec")?;
                        let state_exec = Arc::clone(&state_cmd);
                        let pty_log_exec = pty_log.clone();
                        let shim_id_exec = shim_id.clone();

                        // Run the codex exec subprocess in a background thread
                        thread::spawn(move || {
                            run_codex_exec(
                                &shim_id_exec,
                                &exec_program,
                                &exec_args,
                                &text,
                                &cwd,
                                &state_exec,
                                &mut evt_channel,
                                pty_log_exec.as_ref(),
                            );
                        });
                    }
                    ShimState::Working => {
                        // Queue the message
                        if st.message_queue.len() >= MAX_QUEUE_DEPTH {
                            let dropped = st.message_queue.pop_front();
                            let dropped_id = dropped.as_ref().and_then(|m| m.message_id.clone());
                            st.message_queue.push_back(QueuedMessage {
                                from,
                                body,
                                message_id,
                            });
                            let depth = st.message_queue.len();
                            drop(st);

                            cmd_channel.send(&Event::Error {
                                command: "SendMessage".into(),
                                reason: format!(
                                    "message queue full ({MAX_QUEUE_DEPTH}), dropped oldest message{}",
                                    dropped_id
                                        .map(|id| format!(" (id: {id})"))
                                        .unwrap_or_default(),
                                ),
                            })?;
                            cmd_channel.send(&Event::Warning {
                                message: format!(
                                    "message queued while agent working (depth: {depth})"
                                ),
                                idle_secs: None,
                            })?;
                        } else {
                            st.message_queue.push_back(QueuedMessage {
                                from,
                                body,
                                message_id,
                            });
                            let depth = st.message_queue.len();
                            drop(st);

                            cmd_channel.send(&Event::Warning {
                                message: format!(
                                    "message queued while agent working (depth: {depth})"
                                ),
                                idle_secs: None,
                            })?;
                        }
                    }
                    other => {
                        drop(st);
                        cmd_channel.send(&Event::Error {
                            command: "SendMessage".into(),
                            reason: format!("agent in {other} state, cannot accept message"),
                        })?;
                    }
                }
            }

            ShimCommand::CaptureScreen { last_n_lines } => {
                let st = state_cmd.lock().unwrap();
                let content = match last_n_lines {
                    Some(n) => last_n_lines_of(&st.accumulated_response, n),
                    None => st.accumulated_response.clone(),
                };
                drop(st);
                cmd_channel.send(&Event::ScreenCapture {
                    content,
                    cursor_row: 0,
                    cursor_col: 0,
                })?;
            }

            ShimCommand::GetState => {
                let st = state_cmd.lock().unwrap();
                let since = st.state_changed_at.elapsed().as_secs();
                let state = st.state;
                drop(st);
                cmd_channel.send(&Event::State {
                    state,
                    since_secs: since,
                })?;
            }

            ShimCommand::Resize { .. } => {
                // No-op — no PTY.
            }

            ShimCommand::Ping => {
                cmd_channel.send(&Event::Pong)?;
            }

            ShimCommand::Shutdown { reason, .. } => {
                eprintln!(
                    "[shim-codex {shim_id}] shutdown requested ({})",
                    reason.label()
                );
                if let Err(error) = super::runtime::preserve_work_before_kill(&args.cwd) {
                    eprintln!(
                        "[shim-codex {shim_id}] failed to preserve work before shutdown: {error:#}"
                    );
                }
                let mut st = state_cmd.lock().unwrap();
                st.state = ShimState::Dead;
                st.state_changed_at = Instant::now();
                drop(st);
                break;
            }

            ShimCommand::Kill => {
                if let Err(error) = super::runtime::preserve_work_before_kill(&args.cwd) {
                    eprintln!(
                        "[shim-codex {shim_id}] failed to preserve work before kill: {error:#}"
                    );
                }
                let mut st = state_cmd.lock().unwrap();
                st.state = ShimState::Dead;
                st.state_changed_at = Instant::now();
                drop(st);
                break;
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Per-message subprocess execution
// ---------------------------------------------------------------------------

/// Spawn `codex exec --json ...` and process its JSONL output.
/// When the subprocess exits, transition back to Idle and drain the queue.
#[allow(clippy::too_many_arguments)]
fn run_codex_exec(
    shim_id: &str,
    program: &str,
    args: &[String],
    prompt: &str,
    cwd: &std::path::Path,
    state: &Arc<Mutex<CodexState>>,
    evt_channel: &mut Channel,
    pty_log: Option<&Arc<Mutex<PtyLogWriter>>>,
) {
    // Spawn the subprocess
    let mut child = match Command::new(program)
        .args(args)
        .current_dir(cwd)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .env_remove("CLAUDECODE")
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            eprintln!("[shim-codex {shim_id}] failed to spawn codex exec: {e}");
            let mut st = state.lock().unwrap();
            let msg_id = st.pending_message_id.take();
            st.state = ShimState::Idle;
            st.state_changed_at = Instant::now();
            drop(st);
            let _ = evt_channel.send(&Event::Error {
                command: "SendMessage".into(),
                reason: format!("codex exec spawn failed: {e}"),
            });
            let _ = evt_channel.send(&Event::StateChanged {
                from: ShimState::Working,
                to: ShimState::Idle,
                summary: format!("spawn failed: {e}"),
            });
            let _ = evt_channel.send(&Event::Completion {
                message_id: msg_id,
                response: String::new(),
                last_lines: format!("spawn failed: {e}"),
            });
            return;
        }
    };

    let child_pid = child.id();
    eprintln!("[shim-codex {shim_id}] codex exec spawned (pid {child_pid})");

    if let Some(mut stdin) = child.stdin.take() {
        if let Err(e) = stdin.write_all(prompt.as_bytes()) {
            eprintln!("[shim-codex {shim_id}] failed to write prompt to stdin: {e}");
        }
    }

    let stdout = child.stdout.take().unwrap();
    let stderr = child.stderr.take().unwrap();

    // stderr reader (log only). Non-recoverable auth failures are detected
    // in the structured `turn.failed` / `error` events below — the codex
    // CLI surfaces the same message there, so we don't need to race the
    // stderr thread against the stdout JSONL path.
    let shim_id_err = shim_id.to_string();
    let pty_log_err = pty_log.map(Arc::clone);
    thread::spawn(move || {
        let reader = BufReader::new(stderr);
        for line_result in reader.lines() {
            match line_result {
                Ok(line) => {
                    eprintln!("[shim-codex {shim_id_err}] stderr: {line}");
                    if let Some(ref log) = pty_log_err {
                        let _ = log
                            .lock()
                            .unwrap()
                            .write(format!("[stderr] {line}\n").as_bytes());
                    }
                }
                Err(_) => break,
            }
        }
    });

    // stdout JSONL reader
    let reader = BufReader::new(stdout);
    for line_result in reader.lines() {
        let line = match line_result {
            Ok(l) => l,
            Err(e) => {
                eprintln!("[shim-codex {shim_id}] stdout read error: {e}");
                break;
            }
        };

        if line.trim().is_empty() {
            continue;
        }

        let evt: CodexEvent = match serde_json::from_str(&line) {
            Ok(e) => e,
            Err(e) => {
                eprintln!("[shim-codex {shim_id}] ignoring unparseable JSONL: {e}");
                continue;
            }
        };

        match evt.event_type.as_str() {
            "thread.started" => {
                if let Some(tid) = evt.thread_id {
                    let mut st = state.lock().unwrap();
                    st.thread_id = Some(tid.clone());
                    eprintln!("[shim-codex {shim_id}] thread started: {tid}");
                }
            }

            "item.completed" | "item.updated" => {
                if let Some(ref item) = evt.item {
                    if let Some(text) = item.agent_text() {
                        if !text.is_empty() {
                            let mut st = state.lock().unwrap();
                            // Replace accumulated response on each complete agent_message
                            // (Codex sends the full text each time, not deltas)
                            if evt.event_type == "item.completed" {
                                st.accumulated_response = text.to_string();
                            }
                            st.cumulative_output_bytes += text.len() as u64;

                            // Check for context approaching limit (proactive).
                            if !st.context_approaching_emitted
                                && common::detect_context_approaching_limit(text)
                            {
                                st.context_approaching_emitted = true;
                                drop(st);
                                let _ = evt_channel.send(&Event::ContextApproaching {
                                    message: "Agent output contains context-pressure signals"
                                        .into(),
                                    input_tokens: 0,
                                    output_tokens: 0,
                                });
                            } else {
                                drop(st);
                            }

                            if let Some(log) = pty_log {
                                let _ = log.lock().unwrap().write(text.as_bytes());
                                let _ = log.lock().unwrap().write(b"\n");
                            }
                        }
                    }
                }
            }

            "turn.failed" => {
                let error_msg = evt
                    .error
                    .as_ref()
                    .map(|e| e.message.clone())
                    .unwrap_or_else(|| "unknown error".to_string());
                eprintln!("[shim-codex {shim_id}] turn failed: {error_msg}");

                // Non-recoverable auth failure: the codex refresh token has
                // been consumed. No amount of respawning fixes this — a
                // human must re-login. Park the shim Idle and surface an
                // AuthRequired event so the daemon stops dispatching.
                if detect_auth_required(&error_msg) {
                    let mut st = state.lock().unwrap();
                    st.pending_message_id = None;
                    st.state = ShimState::Idle;
                    st.state_changed_at = Instant::now();
                    let drain = drain_queue_errors(&mut st.message_queue, ShimState::Idle);
                    drop(st);

                    let _ = evt_channel.send(&Event::AuthRequired { message: error_msg });
                    for event in drain {
                        let _ = evt_channel.send(&event);
                    }
                    let _ = child.wait();
                    return;
                }

                // Check for context exhaustion
                if common::detect_context_exhausted(&error_msg) {
                    let mut st = state.lock().unwrap();
                    let last_lines = last_n_lines_of(&st.accumulated_response, 5);
                    st.state = ShimState::ContextExhausted;
                    st.state_changed_at = Instant::now();
                    let drain =
                        drain_queue_errors(&mut st.message_queue, ShimState::ContextExhausted);
                    drop(st);

                    let _ = evt_channel.send(&Event::StateChanged {
                        from: ShimState::Working,
                        to: ShimState::ContextExhausted,
                        summary: last_lines.clone(),
                    });
                    let _ = evt_channel.send(&Event::ContextExhausted {
                        message: error_msg,
                        last_lines,
                    });
                    for event in drain {
                        let _ = evt_channel.send(&event);
                    }
                    return;
                }

                if let Some(quota_block) = detect_quota_block(&error_msg) {
                    let mut st = state.lock().unwrap();
                    st.pending_message_id = None;
                    st.state = ShimState::Idle;
                    st.state_changed_at = Instant::now();
                    st.quota_blocked_until = quota_block.retry_at_epoch_secs;
                    let drain = drain_queue_errors(&mut st.message_queue, ShimState::Idle);
                    drop(st);

                    let _ = evt_channel.send(&Event::QuotaBlocked {
                        message: error_msg.clone(),
                        retry_at_epoch_secs: quota_block.retry_at_epoch_secs,
                        retry_at_label: quota_block.retry_at_label.clone(),
                    });
                    for event in drain {
                        let _ = evt_channel.send(&event);
                    }
                    let _ = child.wait();
                    return;
                }
            }

            "error" => {
                let error_msg = evt
                    .error
                    .as_ref()
                    .map(|e| e.message.clone())
                    .unwrap_or_else(|| "stream error".to_string());
                eprintln!("[shim-codex {shim_id}] error event: {error_msg}");

                // Non-recoverable auth failure short-circuits before quota
                // detection so we never treat a dead refresh token as a
                // transient billing issue.
                if detect_auth_required(&error_msg) {
                    let mut st = state.lock().unwrap();
                    st.pending_message_id = None;
                    st.state = ShimState::Idle;
                    st.state_changed_at = Instant::now();
                    let drain = drain_queue_errors(&mut st.message_queue, ShimState::Idle);
                    drop(st);

                    let _ = evt_channel.send(&Event::AuthRequired { message: error_msg });
                    for event in drain {
                        let _ = evt_channel.send(&event);
                    }
                    let _ = child.wait();
                    return;
                }

                // Detect quota/billing exhaustion — emit a specific event so
                // the daemon can pause dispatch and alert the human.
                let lower = error_msg.to_ascii_lowercase();
                if lower.contains("usage limit")
                    || lower.contains("quota")
                    || lower.contains("billing")
                    || lower.contains("purchase more credits")
                {
                    eprintln!("[shim-codex {shim_id}] QUOTA EXHAUSTED: {error_msg}");
                    if let Some(quota_block) = detect_quota_block(&error_msg) {
                        let mut st = state.lock().unwrap();
                        st.pending_message_id = None;
                        st.state = ShimState::Idle;
                        st.state_changed_at = Instant::now();
                        st.quota_blocked_until = quota_block.retry_at_epoch_secs;
                        let drain = drain_queue_errors(&mut st.message_queue, ShimState::Idle);
                        drop(st);

                        let _ = evt_channel.send(&Event::QuotaBlocked {
                            message: error_msg.clone(),
                            retry_at_epoch_secs: quota_block.retry_at_epoch_secs,
                            retry_at_label: quota_block.retry_at_label.clone(),
                        });
                        for event in drain {
                            let _ = evt_channel.send(&event);
                        }
                        let _ = child.wait();
                        return;
                    }
                }
            }

            // turn.started, turn.completed, item.started — informational, no action
            _ => {}
        }
    }

    // stdout closed — subprocess finished. Wait for exit.
    let exit_code = child.wait().ok().and_then(|s| s.code());
    eprintln!("[shim-codex {shim_id}] codex exec exited (code: {exit_code:?})");

    // Transition Working → Idle, emit Completion
    let mut st = state.lock().unwrap();
    let response = std::mem::take(&mut st.accumulated_response);
    let last_lines = last_n_lines_of(&response, 5);
    let msg_id = st.pending_message_id.take();
    st.state = ShimState::Idle;
    st.state_changed_at = Instant::now();

    // Check for queued messages
    let queued_msg = if !st.message_queue.is_empty() {
        st.message_queue.pop_front()
    } else {
        None
    };

    if let Some(ref qm) = queued_msg {
        st.pending_message_id = qm.message_id.clone();
        st.state = ShimState::Working;
        st.state_changed_at = Instant::now();
        st.accumulated_response.clear();
    }

    let thread_id = st.thread_id.clone();
    let program = st.program.clone();
    let cwd_owned = st.cwd.clone();
    let queue_depth = st.message_queue.len();
    drop(st);

    let _ = evt_channel.send(&Event::StateChanged {
        from: ShimState::Working,
        to: ShimState::Idle,
        summary: last_lines.clone(),
    });
    let _ = evt_channel.send(&Event::Completion {
        message_id: msg_id,
        response,
        last_lines,
    });

    // Drain queued message by spawning another codex exec
    if let Some(qm) = queued_msg {
        let _ = evt_channel.send(&Event::StateChanged {
            from: ShimState::Idle,
            to: ShimState::Working,
            summary: format!("delivering queued message ({queue_depth} remaining)"),
        });

        let text = format_injected_message(&qm.from, &qm.body);
        let (exec_program, exec_args) = codex_types::codex_sdk_args(&program, thread_id.as_deref());

        // Recursive call for queued message (same thread)
        run_codex_exec(
            shim_id,
            &exec_program,
            &exec_args,
            &text,
            &cwd_owned,
            state,
            evt_channel,
            pty_log,
        );
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct QuotaBlock {
    retry_at_epoch_secs: Option<u64>,
    retry_at_label: Option<String>,
}

/// Detect the non-recoverable codex auth-credential error. The refresh token
/// can only be used once; once that single use has been consumed (typically by
/// another concurrent codex process), no amount of respawning can recover —
/// a human has to `codex login` again. Keep the matcher narrow so that
/// transient network-level auth failures still flow through the normal retry
/// paths.
fn detect_auth_required(message: &str) -> bool {
    let lower = message.to_ascii_lowercase();
    lower.contains("refresh token was already used")
        || (lower.contains("failed to refresh token") && lower.contains("log out and sign in"))
}

#[cfg(test)]
mod detect_auth_required_tests {
    use super::detect_auth_required;

    #[test]
    fn matches_refresh_token_already_used() {
        assert!(detect_auth_required(
            "Your access token could not be refreshed because your refresh token was already used. \
             Please log out and sign in again."
        ));
    }

    #[test]
    fn matches_generic_failed_to_refresh_with_login_hint() {
        assert!(detect_auth_required(
            "Failed to refresh token: please log out and sign in again"
        ));
    }

    #[test]
    fn ignores_unrelated_errors() {
        assert!(!detect_auth_required("stream error"));
        assert!(!detect_auth_required("usage limit reached"));
        assert!(!detect_auth_required("context length exceeded"));
    }
}

fn detect_quota_block(message: &str) -> Option<QuotaBlock> {
    let lower = message.to_ascii_lowercase();
    let quota_hit = lower.contains("usage limit")
        || lower.contains("purchase more credits")
        || (lower.contains("quota") && lower.contains("try again"));
    if !quota_hit {
        return None;
    }

    let retry_at_epoch_secs = message
        .split_once("try again at")
        .and_then(|(_, tail)| parse_quota_retry_at(tail.trim()));
    let retry_at_label = retry_at_epoch_secs.map(format_quota_retry_label);
    Some(QuotaBlock {
        retry_at_epoch_secs,
        retry_at_label,
    })
}

fn parse_quota_retry_at(value: &str) -> Option<u64> {
    let ordinal_suffixes = Regex::new(r"(?i)\b(\d{1,2})(st|nd|rd|th)\b").ok()?;
    let normalized = ordinal_suffixes
        .replace_all(value.trim().trim_end_matches('.'), "$1")
        .to_string();
    let naive = chrono::NaiveDateTime::parse_from_str(&normalized, "%b %e, %Y %I:%M %p")
        .or_else(|_| chrono::NaiveDateTime::parse_from_str(&normalized, "%B %e, %Y %I:%M %p"))
        .ok()?;
    let local = chrono::Local
        .from_local_datetime(&naive)
        .single()
        .or_else(|| chrono::Local.from_local_datetime(&naive).earliest())
        .or_else(|| chrono::Local.from_local_datetime(&naive).latest())?;
    Some(local.timestamp().max(0) as u64)
}

fn format_quota_retry_label(unix_secs: u64) -> String {
    use std::time::{Duration, UNIX_EPOCH};

    let dt = UNIX_EPOCH + Duration::from_secs(unix_secs);
    let datetime: chrono::DateTime<chrono::Local> = dt.into();
    datetime.format("%Y-%m-%d %H:%M").to_string()
}

fn current_unix_secs() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};

    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Terminate a child process: SIGTERM, grace period, then SIGKILL.
#[allow(dead_code)]
fn terminate_child(child: &mut Child) {
    let pid = child.id();
    #[cfg(unix)]
    {
        unsafe {
            libc::kill(pid as i32, libc::SIGTERM);
        }
        let deadline = Instant::now() + Duration::from_secs(GROUP_TERM_GRACE_SECS);
        loop {
            if Instant::now() > deadline {
                break;
            }
            match child.try_wait() {
                Ok(Some(_)) => return,
                _ => thread::sleep(Duration::from_millis(PROCESS_EXIT_POLL_MS)),
            }
        }
        unsafe {
            libc::kill(pid as i32, libc::SIGKILL);
        }
    }
    #[allow(unreachable_code)]
    {
        let _ = child.kill();
    }
}

/// Extract the last N lines from a string.
fn last_n_lines_of(text: &str, n: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    let start = lines.len().saturating_sub(n);
    lines[start..].join("\n")
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shim::protocol;

    #[test]
    fn last_n_lines_basic() {
        assert_eq!(last_n_lines_of("a\nb\nc", 2), "b\nc");
        assert_eq!(last_n_lines_of("a\nb\nc", 10), "a\nb\nc");
        assert_eq!(last_n_lines_of("", 5), "");
    }

    #[test]
    fn codex_state_initial() {
        let st = CodexState {
            state: ShimState::Idle,
            state_changed_at: Instant::now(),
            started_at: Instant::now(),
            thread_id: None,
            accumulated_response: String::new(),
            pending_message_id: None,
            message_queue: VecDeque::new(),
            cumulative_output_bytes: 0,
            program: "codex".into(),
            cwd: std::path::PathBuf::from("/tmp"),
            context_approaching_emitted: false,
            quota_blocked_until: None,
        };
        assert_eq!(st.state, ShimState::Idle);
        assert!(st.thread_id.is_none());
    }

    #[test]
    fn channel_events_roundtrip() {
        let (parent_sock, child_sock) = protocol::socketpair().unwrap();
        let mut parent = protocol::Channel::new(parent_sock);
        let mut child = protocol::Channel::new(child_sock);

        child.send(&Event::Ready).unwrap();
        let event: Event = parent.recv().unwrap().unwrap();
        assert!(matches!(event, Event::Ready));
    }

    #[test]
    fn parse_quota_retry_at_handles_codex_usage_limit_timestamp() {
        let parsed = parse_quota_retry_at("Apr 16th, 2026 12:54 PM.");
        assert!(parsed.is_some(), "expected retry timestamp to parse");
    }

    #[test]
    fn detect_quota_block_extracts_retry_metadata() {
        let quota = detect_quota_block(
            "You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at Apr 16th, 2026 12:54 PM.",
        )
        .expect("expected quota block");
        assert!(quota.retry_at_epoch_secs.is_some());
        assert_eq!(quota.retry_at_label.as_deref(), Some("2026-04-16 12:54"));
    }

    #[test]
    fn detect_quota_block_ignores_non_quota_failures() {
        assert!(detect_quota_block("stream error").is_none());
    }
}