Skip to main content

agent_abstraction/
run.rs

1//! Spawning an agent and turning its output into events and an outcome.
2//!
3//! Two entry points over the same machinery:
4//! - [`run`] waits and hands back the finished [`Outcome`].
5//! - [`stream`] hands back a [`Run`] that yields [`Event`]s as they arrive, for
6//!   a UI that shows work in progress.
7//!
8//! Both read stdout and stderr concurrently. Draining only one would deadlock
9//! the moment the other filled its pipe buffer, which for a chatty agent is a
10//! matter of seconds.
11
12use std::collections::VecDeque;
13use std::process::Stdio;
14
15use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
16use tokio::process::{Child, Command};
17use tokio::sync::mpsc;
18
19use crate::agent::{Continue, EnvPolicy};
20use crate::error::{Error, Result};
21use crate::event::{Event, MAX_LINE, Parser, Terminal, append_capped};
22use crate::outcome::{Outcome, Stop};
23use crate::proc::{kill_group_by_pid, kill_process_group};
24use crate::request::Request;
25
26/// Read one line, giving up on a line that never ends.
27///
28/// `AsyncBufReadExt::lines` buffers until a newline arrives, so a stream that
29/// emits megabytes without one exhausts memory before any total cap applies.
30/// This reads a bounded amount and, past the limit, returns what it has and
31/// discards the remainder of that line. Returns `None` at end of input.
32async fn read_bounded_line<R>(reader: &mut R, buf: &mut String) -> std::io::Result<Option<bool>>
33where
34    R: tokio::io::AsyncBufRead + Unpin,
35{
36    buf.clear();
37    let mut bytes = Vec::new();
38    let mut truncated = false;
39    loop {
40        let mut byte = [0u8; 1];
41        match reader.read(&mut byte).await? {
42            // End of input: a trailing fragment still counts as a line.
43            0 => {
44                if bytes.is_empty() {
45                    return Ok(None);
46                }
47                break;
48            }
49            _ if byte[0] == b'\n' => break,
50            _ => {
51                if bytes.len() < MAX_LINE {
52                    bytes.push(byte[0]);
53                } else {
54                    // Keep draining to the newline so the pipe does not block,
55                    // but stop accumulating.
56                    truncated = true;
57                }
58            }
59        }
60    }
61    // Output is not guaranteed to be valid UTF-8, and one bad byte should not
62    // end a run.
63    buf.push_str(&String::from_utf8_lossy(&bytes));
64    Ok(Some(truncated))
65}
66
67/// Aborts a task when dropped.
68///
69/// The decision forwarder holds the child's stdin, so leaving it running past
70/// the run would keep a pipe open to a process that is gone.
71struct AbortOnDrop(tokio::task::JoinHandle<()>);
72
73impl Drop for AbortOnDrop {
74    fn drop(&mut self) {
75        self.0.abort();
76    }
77}
78
79/// How many decisions may queue on the way back to the agent.
80///
81/// Small on purpose: the agent asks one question at a time and waits, so a deep
82/// queue here would only mean answers piling up for questions nobody asked.
83const APPROVAL_BUFFER: usize = 8;
84
85/// How many events may queue before the producer waits for the consumer. Deep
86/// enough that a burst of tool events does not stall the agent, shallow enough
87/// that a consumer which stops reading does not grow without bound.
88const EVENT_BUFFER: usize = 256;
89
90/// A host action travelling back to an interactive agent.
91///
92/// Claude and Codex encode these differently, so the public handle preserves
93/// the intent and lets the selected transport serialize it at the boundary.
94#[derive(Debug)]
95enum Control {
96    Message(String),
97    Approval {
98        id: String,
99        decision: crate::Decision,
100    },
101}
102
103/// A run in progress.
104///
105/// Yields events through [`Run::recv`] and settles into an [`Outcome`] through
106/// [`Run::finish`].
107///
108/// **Dropping a `Run` kills the agent.** That is the safe default for the hosts
109/// this crate targets: closing a window or cancelling a request should stop the
110/// work, not leave an agent running invisibly, spending quota and touching
111/// files with nobody watching. Call [`Run::detach`] when background execution is
112/// genuinely what you want.
113///
114/// On Unix, dropping **synchronously signals** the run's process group and then
115/// aborts the driver task. What it cannot do is *wait*: `Drop` cannot await, so
116/// it does not block until the child has exited or its readers have been
117/// joined. Use [`Run::cancel`] when you need to know the tree has actually gone
118/// before continuing, such as before touching the files it was working on. On
119/// Windows only the direct child is signalled.
120#[derive(Debug)]
121pub struct Run {
122    events: mpsc::Receiver<Event>,
123    /// Which agent this is, so `respond` can name it in an error.
124    agent: crate::Agent,
125    /// The typed command line, kept so both the plain and redacted views come
126    /// from the same source.
127    typed: Vec<crate::agent::Arg>,
128    /// The child's pid, so `Drop` can tear the group down itself rather than
129    /// depending on an aborted task being polled.
130    pid: Option<u32>,
131    /// Set by the driver once the child has been reaped, so `Drop` never
132    /// signals a pid the OS may since have handed to someone else.
133    reaped: std::sync::Arc<std::sync::atomic::AtomicBool>,
134    /// Lines on the way back to the agent: follow-up messages and approval
135    /// decisions share one channel because they share one stdin. `None` unless
136    /// the request opened it, which is what lets [`Run::send`] and
137    /// [`Run::respond`] refuse rather than silently do nothing.
138    to_agent: Option<mpsc::Sender<Control>>,
139    /// Dropping or firing this asks the driver to tear down in order. Held as
140    /// an `Option` so `detach` can discard it without signalling.
141    cancel: Option<tokio::sync::oneshot::Sender<()>>,
142    /// `None` only after [`Run::finish`], [`Run::cancel`] or [`Run::detach`]
143    /// has taken ownership, which is what stops `Drop` from aborting a run that
144    /// was already settled deliberately.
145    task: Option<tokio::task::JoinHandle<Result<Outcome>>>,
146    argv: Vec<String>,
147}
148
149impl Run {
150    /// The next event, or `None` once the agent has finished producing them.
151    pub async fn recv(&mut self) -> Option<Event> {
152        self.events.recv().await
153    }
154
155    /// Send another message while the agent is still working.
156    ///
157    /// The whole point of [`crate::Request::interactive`]: a user who types a
158    /// correction mid-turn should not have to wait for the turn to finish.
159    ///
160    /// The agent takes it at its **next step boundary**, not mid-token, so an
161    /// answer already being written finishes first and a long tool-using task
162    /// changes course at its next step. Verified against claude 2.1.212 and
163    /// codex-cli 0.145.0.
164    ///
165    /// # Ordering, and why there is no acknowledgement
166    ///
167    /// The caller already knows what it sent, so the intended pattern is to
168    /// append the message to the transcript immediately, below the user's
169    /// previous one, and carry on. This deliberately does not ask the agent to
170    /// echo the message back for sequencing: an echo would only tell a UI
171    /// something it already knew, and waiting for one would delay the very
172    /// thing this exists to make immediate.
173    ///
174    /// # Errors
175    /// [`Error::Unsupported`] on a run that did not open the channel with
176    /// [`crate::Request::interactive`]. [`Error::Cancelled`] once the channel
177    /// has closed, which happens when the turn settles or the run is torn down:
178    /// **a message sent after the turn ends is too late** and belongs in a new
179    /// run resuming the session, so this reports it rather than dropping it.
180    pub async fn send(&self, message: &str) -> Result<()> {
181        let Some(channel) = &self.to_agent else {
182            return Err(Error::Unsupported {
183                agent: self.agent,
184                what: "sending a follow-up on a run that is not interactive",
185            });
186        };
187        channel
188            .send(Control::Message(message.to_string()))
189            .await
190            .map_err(|_| Error::Cancelled {
191                bin: self.argv.first().cloned().unwrap_or_default(),
192            })
193    }
194
195    /// Answer an [`Event::ApprovalRequest`].
196    ///
197    /// The agent is blocked until this is called, so a consumer that receives an
198    /// approval request and never responds stalls the run until its timeout.
199    ///
200    /// The id must be the one from the request. The agent ignores an answer
201    /// carrying any other id and keeps waiting, so a mismatch presents as a
202    /// hang rather than an error; this passes the id straight through and does
203    /// not invent one.
204    ///
205    /// # Errors
206    /// [`Error::Unsupported`] on a run that did not ask for approvals, since
207    /// there is no channel to answer on. [`Error::Cancelled`] if the run has
208    /// already finished or been torn down, which is the same reason a decision
209    /// can no longer be delivered.
210    pub async fn respond(&self, id: &str, decision: &crate::Decision) -> Result<()> {
211        let Some(channel) = &self.to_agent else {
212            return Err(Error::Unsupported {
213                agent: self.agent,
214                what: "answering an approval on a run that did not request them",
215            });
216        };
217        channel
218            .send(Control::Approval {
219                id: id.to_string(),
220                decision: decision.clone(),
221            })
222            .await
223            .map_err(|_| Error::Cancelled {
224                bin: self.argv.first().cloned().unwrap_or_default(),
225            })
226    }
227
228    /// The exact command line that was spawned.
229    ///
230    /// **This contains the prompt and any session id.** Treat it as sensitive:
231    /// logging it verbatim puts user content into your logs. Use
232    /// [`Run::redacted_argv`] for diagnostics.
233    #[must_use]
234    pub fn argv(&self) -> &[String] {
235        &self.argv
236    }
237
238    /// The command line with every non-public value replaced by a placeholder.
239    ///
240    /// Prompts, system prompts, session ids and anything from
241    /// [`crate::Request::unchecked_args`] are removed; flag names are kept so
242    /// the command stays recognisable. Sensitivity is recorded where each
243    /// argument is built rather than inferred from the finished line, so a
244    /// bare positional prompt or an opaque raw argument is covered too.
245    #[must_use]
246    pub fn redacted_argv(&self) -> Vec<String> {
247        redact(&self.typed)
248    }
249
250    /// Wait for the run to finish.
251    ///
252    /// Drains any events still queued, so a caller that only wants the result
253    /// can call this without having consumed the stream.
254    ///
255    /// # Errors
256    /// Whatever the run failed with. See [`Error`].
257    pub async fn finish(mut self) -> Result<Outcome> {
258        // The driver owns teardown from here; `Drop` must not also fire.
259        self.pid = None;
260        while self.events.recv().await.is_some() {}
261        // Taking the handle disarms the `Drop` guard: this run is settling
262        // normally, not being abandoned.
263        let Some(task) = self.task.take() else {
264            unreachable!("the handle is only taken by a consuming method")
265        };
266        match task.await {
267            Ok(result) => result,
268            // The driver task panicked or was cancelled. The process itself
269            // started fine, so this is not a spawn failure and must not claim
270            // to be one.
271            Err(join) => Err(Error::Interrupted {
272                bin: self.argv.first().cloned().unwrap_or_default(),
273                detail: if join.is_panic() {
274                    "the driver task panicked".into()
275                } else {
276                    "the driver task was cancelled".into()
277                },
278            }),
279        }
280    }
281
282    /// Stop the run and wait until the agent is actually gone.
283    ///
284    /// Cooperative rather than an abort: the driver is asked to stop, signals
285    /// the process group, reaps the child and joins its readers, and only then
286    /// does this return. So when it returns the tree really has exited, which
287    /// matters if the next thing you do touches the files it was working on.
288    ///
289    /// Returns the partial [`Outcome`] if the run happened to finish first,
290    /// otherwise [`Error::Cancelled`].
291    ///
292    /// # Errors
293    /// [`Error::Cancelled`] in the normal case, or whatever the run failed with
294    /// if it failed before the request arrived.
295    pub async fn cancel(mut self) -> Result<Outcome> {
296        // The driver tears down cooperatively and this awaits it, so `Drop`
297        // must not race that with a kill of its own.
298        self.pid = None;
299        // Dropping the sender is itself the signal, so this cannot fail in a
300        // way that leaves the driver waiting.
301        drop(self.cancel.take());
302        let Some(task) = self.task.take() else {
303            unreachable!("the handle is only taken by a consuming method")
304        };
305        match task.await {
306            Ok(result) => result,
307            Err(join) => Err(Error::Interrupted {
308                bin: self.argv.first().cloned().unwrap_or_default(),
309                detail: if join.is_panic() {
310                    "the driver task panicked".into()
311                } else {
312                    "the driver task was cancelled".into()
313                },
314            }),
315        }
316    }
317
318    /// Let the run continue after this handle goes away.
319    ///
320    /// The opposite of the default. Nothing can observe or stop the agent
321    /// afterwards, so reach for this only when an unsupervised background run
322    /// is genuinely intended.
323    pub fn detach(mut self) {
324        // Disarm `Drop` before it runs, or detaching would immediately kill the
325        // run it exists to keep alive.
326        self.pid = None;
327        // Leak the cancel signal rather than dropping it: a dropped sender is
328        // read by the driver as "stop", which is the opposite of detaching.
329        if let Some(cancel) = self.cancel.take() {
330            std::mem::forget(cancel);
331        }
332        // Dropping the handle without aborting is what detaches a tokio task.
333        drop(self.task.take());
334    }
335}
336
337impl Drop for Run {
338    fn drop(&mut self) {
339        // Abandoned rather than finished, cancelled or detached.
340        //
341        // Kill the group here, directly. Signalling the driver and aborting it
342        // is not enough on its own: that leaves teardown waiting on the runtime
343        // to poll the aborted task so its guard runs, and a dropped `Run` was
344        // observed leaving grandchildren alive and sleeping on Linux while the
345        // same teardown worked from `cancel`. `Drop` cannot await, so it does
346        // the one thing it can do synchronously.
347        if let Some(pid) = self.pid
348            && !self.reaped.load(std::sync::atomic::Ordering::SeqCst)
349        {
350            kill_group_by_pid(pid);
351        }
352        drop(self.cancel.take());
353        if let Some(task) = self.task.take() {
354            task.abort();
355        }
356    }
357}
358
359/// Placeholder substituted for a sensitive argv value.
360const REDACTED: &str = "<redacted>";
361
362/// Render a typed command line for logging, keeping flag names and replacing
363/// every value that is not `Public`.
364///
365/// Derived from the sensitivity recorded where each argument was built, so it
366/// cannot miss a case the way matching on flag names and positions can.
367fn redact(argv: &[crate::agent::Arg]) -> Vec<String> {
368    use crate::agent::Sensitivity;
369
370    argv.iter()
371        .map(|arg| match arg.sensitivity {
372            Sensitivity::Public => arg.value.clone(),
373            _ => REDACTED.to_string(),
374        })
375        .collect()
376}
377
378/// Run `request` to completion, discarding the intermediate events.
379///
380/// # Errors
381/// See [`Error`]; notably [`Error::NotInstalled`], [`Error::Timeout`],
382/// [`Error::RateLimited`] and [`Error::Failed`].
383///
384/// [`Error::Unsupported`] for a request that asked for approvals: this entry
385/// point discards events, so an approval request would reach nobody and the run
386/// would sit blocked until its timeout. Use [`stream`] instead.
387pub async fn run(request: &Request) -> Result<Outcome> {
388    if request.plan().approvals {
389        return Err(Error::Unsupported {
390            agent: request.agent,
391            what: "approvals on a run whose events are discarded; use `stream`",
392        });
393    }
394    stream(request)?.finish().await
395}
396
397/// Start `request`, returning a handle that streams its events.
398///
399/// Returns as soon as the child is spawned; the work proceeds on a task.
400///
401/// # Errors
402/// [`Error::NotInstalled`] if the binary is missing, [`Error::Unsupported`] if
403/// the agent cannot honour the request, or [`Error::Spawn`] on an OS failure.
404#[allow(
405    clippy::too_many_lines,
406    reason = "one spawn boundary keeps command posture, pipes, process group, and driver selection together"
407)]
408pub fn stream(request: &Request) -> Result<Run> {
409    // `tokio::spawn` panics outside a runtime. A fallible signature must not
410    // hide that, so the context is checked and reported as an ordinary error.
411    let runtime = tokio::runtime::Handle::try_current().map_err(|_| Error::NoRuntime)?;
412
413    let initial_plan = request.plan();
414    let codex_app_server =
415        request.agent == crate::Agent::Codex && (initial_plan.duplex || initial_plan.approvals);
416
417    // Written before the argv is built, because the argv has to name it. The
418    // app-server protocol accepts the schema inline instead.
419    let schema_file = match (&request.schema, request.agent.caps().schema) {
420        (Some(_), _) if codex_app_server => None,
421        (Some(schema), crate::agent::SchemaSupport::File) => {
422            Some(SchemaFile::write(schema).map_err(|source| Error::Spawn {
423                bin: request.agent.bin().to_string(),
424                source,
425            })?)
426        }
427        _ => None,
428    };
429    let mut request = request.clone();
430    if let Some(file) = &schema_file {
431        request.schema_file = Some(file.0.display().to_string());
432    }
433    let request = &request;
434
435    let plan = request.plan();
436    let typed = request.typed_argv()?;
437    let argv: Vec<String> = typed.iter().map(|a| a.value.clone()).collect();
438
439    let mut command = Command::new(&argv[0]);
440    command
441        .args(&argv[1..])
442        .stdin(if plan.stdin_prompt || plan.duplex || plan.approvals {
443            // An interactive run needs stdin for the whole turn, not just to
444            // deliver a prompt: it is the channel follow-up messages and
445            // approval decisions travel back on.
446            Stdio::piped()
447        } else {
448            // Close stdin so an agent that would otherwise wait on it exits
449            // instead of hanging forever with nothing to read.
450            Stdio::null()
451        })
452        .stdout(Stdio::piped())
453        .stderr(Stdio::piped())
454        // Without this a killed run can leave the child alive holding the pipes.
455        .kill_on_drop(true);
456    if let Some(cwd) = &request.cwd {
457        command.current_dir(cwd);
458    }
459    // Narrow the environment first, then apply explicit variables, so an
460    // explicit `env()` always wins over the policy.
461    match &request.env_policy {
462        EnvPolicy::Inherit => {}
463        EnvPolicy::Minimal => {
464            command.env_clear();
465            inherit_named(&mut command, &request.agent.essential_env());
466        }
467        EnvPolicy::Only(names) => {
468            command.env_clear();
469            inherit_named(&mut command, names);
470        }
471    }
472    for (key, value) in &request.env {
473        command.env(key, value);
474    }
475
476    // Put the agent in its own process group so the whole tree can be signalled
477    // together. Killing only the CLI leaves the commands *it* spawned running:
478    // a build, a test run, a server, still holding files and credentials after
479    // the run is supposedly over.
480    // 0 means "make this child its own group leader". `tokio::process::Command`
481    // exposes this directly on unix.
482    #[cfg(unix)]
483    command.process_group(0);
484
485    // Reserve an assigned session id before the child exists. Doing it inside
486    // the driver leaves a window where a spawn that half-succeeds loses the
487    // binding, and this is the id the caller may already be showing in a UI.
488    if let Some(token) = preassigned_token(request) {
489        persist_session(request, &token)?;
490    }
491
492    let child = command.spawn().map_err(|source| {
493        // A missing binary is the common case and deserves an actionable error
494        // with an install hint. Reading it off the spawn avoids resolving PATH
495        // twice, and with it the window where the resolved path is replaced
496        // between the check and the exec.
497        if source.kind() == std::io::ErrorKind::NotFound {
498            Error::NotInstalled {
499                agent: request.agent,
500                bin: plan.bin.clone(),
501                hint: request.agent.install_hint(),
502            }
503        } else {
504            Error::Spawn {
505                bin: plan.bin.clone(),
506                source,
507            }
508        }
509    })?;
510
511    let request_agent = request.agent;
512    let pid = child.id();
513    let (tx, rx) = mpsc::channel(EVENT_BUFFER);
514    // Only created for an approvals run, so `respond` can tell "no channel" from
515    // "channel closed" and refuse the first rather than hanging on it.
516    let (decisions_tx, decisions_rx) = if plan.duplex || plan.approvals {
517        let (tx, rx) = mpsc::channel::<Control>(APPROVAL_BUFFER);
518        (Some(tx), Some(rx))
519    } else {
520        (None, None)
521    };
522    let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
523    let reaped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
524    let reaped_for_task = std::sync::Arc::clone(&reaped);
525    let request = request.clone();
526    let task = runtime.spawn(async move {
527        // Moved in so the file outlives the run and is removed with it.
528        let _schema_file = schema_file;
529        if codex_app_server {
530            drive_codex_app_server(child, request, tx, cancel_rx, reaped_for_task, decisions_rx)
531                .await
532        } else {
533            drive(child, request, tx, cancel_rx, reaped_for_task, decisions_rx).await
534        }
535    });
536    Ok(Run {
537        events: rx,
538        agent: request_agent,
539        typed,
540        pid,
541        reaped,
542        cancel: Some(cancel_tx),
543        to_agent: decisions_tx,
544        task: Some(task),
545        argv,
546    })
547}
548
549/// Copy the named variables from this process into `command`, skipping any that
550/// are unset so nothing is invented.
551fn inherit_named<S: AsRef<str>>(command: &mut Command, names: &[S]) {
552    for name in names {
553        if let Some(value) = std::env::var_os(name.as_ref()) {
554            command.env(name.as_ref(), value);
555        }
556    }
557}
558
559/// A schema file written for one run, removed when the run ends.
560///
561/// Codex reads its schema from disk, so the file has to outlive the spawn and
562/// not outlive the process. Tying it to a guard means every exit path removes
563/// it, including a cancel or a timeout, without each one remembering.
564struct SchemaFile(std::path::PathBuf);
565
566impl SchemaFile {
567    /// Write `schema` somewhere the agent can read it.
568    fn write(schema: &str) -> std::io::Result<SchemaFile> {
569        use std::io::Write as _;
570        use std::sync::atomic::{AtomicU64, Ordering};
571        static COUNTER: AtomicU64 = AtomicU64::new(0);
572
573        let path = std::env::temp_dir().join(format!(
574            "agent-abstraction-schema-{}-{}.json",
575            std::process::id(),
576            COUNTER.fetch_add(1, Ordering::Relaxed)
577        ));
578        let mut options = std::fs::OpenOptions::new();
579        options.write(true).create_new(true);
580        // A schema can encode what a caller is looking for, so it is no more
581        // public than the prompt.
582        #[cfg(unix)]
583        {
584            use std::os::unix::fs::OpenOptionsExt as _;
585            options.mode(0o600);
586        }
587        options.open(&path)?.write_all(schema.as_bytes())?;
588        Ok(SchemaFile(path))
589    }
590}
591
592impl Drop for SchemaFile {
593    fn drop(&mut self) {
594        let _ = std::fs::remove_file(&self.0);
595    }
596}
597
598/// Owns the child and tears down its whole process group when dropped.
599///
600/// `kill_on_drop` alone is not enough: it kills the CLI, leaving the commands
601/// *it* spawned running. Since aborting the driver task drops this guard, the
602/// same teardown covers cancellation, a dropped [`Run`] and a timeout, without
603/// each path having to remember to do it.
604struct ChildGuard {
605    child: Child,
606    /// Cleared once the child has been reaped, so a pid the OS may since have
607    /// recycled is never signalled.
608    armed: bool,
609}
610
611impl Drop for ChildGuard {
612    fn drop(&mut self) {
613        if self.armed {
614            kill_process_group(&self.child);
615        }
616    }
617}
618
619/// Feed the child, read both its pipes, and assemble the outcome.
620#[allow(
621    clippy::too_many_lines,
622    reason = "one linear lifecycle: feed, read, wait, classify. Splitting it \
623              would thread the child, parser, buffers and cancellation state \
624              through helpers and obscure the ordering that matters, such as \
625              killing the group before reaping."
626)]
627async fn drive(
628    child: Child,
629    request: Request,
630    events: mpsc::Sender<Event>,
631    cancel: tokio::sync::oneshot::Receiver<()>,
632    reaped: std::sync::Arc<std::sync::atomic::AtomicBool>,
633    decisions: Option<mpsc::Receiver<Control>>,
634) -> Result<Outcome> {
635    // From here on the child is owned by a guard, so every exit path from this
636    // task, including an abort, takes the process group with it.
637    let mut child = ChildGuard { child, armed: true };
638    let plan = request.plan();
639    let bin = plan.bin.clone();
640
641    // An approvals run owns stdin for the whole turn: the handshake and the
642    // prompt go out first, then it stays open carrying decisions until the run
643    // ends. Closing it after the prompt, as the plain piped path does, would
644    // take the answer channel with it.
645    let mut decision_task = None;
646    let mut close_stdin = None;
647    if plan.duplex || plan.approvals {
648        let Some(mut stdin) = child.child.stdin.take() else {
649            return Err(Error::Spawn {
650                bin: bin.clone(),
651                source: std::io::Error::other("stdin was not piped for an interactive run"),
652            });
653        };
654        let opening = format!(
655            "{}{}",
656            crate::approval::handshake(),
657            crate::approval::user_message(&request.agent.effective_prompt(&plan)),
658        );
659        stdin
660            .write_all(opening.as_bytes())
661            .await
662            .map_err(|source| Error::Spawn {
663                bin: bin.clone(),
664                source,
665            })?;
666        let _ = stdin.flush().await;
667        // Forwarding runs on its own task so a decision can be written while
668        // stdout is being read. It ends on whichever comes first: the channel
669        // closing, or the turn settling.
670        let (close_tx, mut close_rx) = tokio::sync::oneshot::channel::<()>();
671        close_stdin = Some(close_tx);
672        decision_task = decisions.map(|mut rx| {
673            tokio::spawn(async move {
674                loop {
675                    tokio::select! {
676                        reply = rx.recv() => {
677                            let Some(control) = reply else { break };
678                            let reply = match control {
679                                Control::Message(message) => {
680                                    crate::approval::user_message(&message)
681                                }
682                                Control::Approval { id, decision } => decision.wire(&id),
683                            };
684                            if stdin.write_all(reply.as_bytes()).await.is_err() {
685                                break;
686                            }
687                            let _ = stdin.flush().await;
688                        }
689                        // The turn is over. Dropping stdin is what lets claude
690                        // exit rather than wait for another message.
691                        _ = &mut close_rx => break,
692                    }
693                }
694                drop(stdin);
695            })
696        });
697    }
698
699    // Deliver a piped prompt and close the pipe, or the agent waits on EOF.
700    if plan.stdin_prompt {
701        if let Some(mut stdin) = child.child.stdin.take() {
702            let prompt = request.agent.effective_prompt(&plan);
703            stdin
704                .write_all(prompt.as_bytes())
705                .await
706                .map_err(|source| Error::Spawn {
707                    bin: bin.clone(),
708                    source,
709                })?;
710            drop(stdin);
711        }
712    }
713
714    // Drain stderr on its own task: a full stderr pipe blocks the child even
715    // while stdout still has room.
716    // Aborted on every exit path from here, so a forwarder never survives the
717    // run it belongs to.
718    let _decision_guard = decision_task.map(AbortOnDrop);
719
720    let stderr = child.child.stderr.take();
721    let stderr_task = tokio::spawn(async move {
722        let mut buf = String::new();
723        if let Some(handle) = stderr {
724            let mut reader = BufReader::new(handle);
725            let mut line = String::new();
726            // Keep draining after the cap is hit: an undrained pipe blocks the
727            // child even though we no longer want the bytes.
728            while let Ok(Some(_)) = read_bounded_line(&mut reader, &mut line).await {
729                append_capped(&mut buf, &line);
730            }
731        }
732        buf
733    });
734
735    let stdout = child.child.stdout.take();
736    let mut parser = Parser::new(request.agent, plan.format);
737    // Raw stdout is retained only as a fallback answer for a run that exited
738    // cleanly without producing a structured one, and as evidence when
739    // classifying a failure. It is capped for the same reason as everything
740    // else here: an agent can stream for hours.
741    let mut raw = String::new();
742    // Tracks the first `Started`, so the binding is written once, and carries a
743    // store failure back out instead of discarding it.
744    let mut bound = false;
745    let mut persist_result: Result<()> = Ok(());
746
747    let read_stdout = async {
748        if let Some(handle) = stdout {
749            let mut reader = BufReader::new(handle);
750            let mut line = String::new();
751            while read_bounded_line(&mut reader, &mut line).await?.is_some() {
752                append_capped(&mut raw, &line);
753                let parsed = parser.push(&line);
754                // Close stdin as soon as the turn settles. Under stream-json
755                // input claude waits for another message otherwise, so the run
756                // would only end at its timeout even though the answer already
757                // arrived.
758                if parser.saw_terminal()
759                    && let Some(close) = close_stdin.take()
760                {
761                    let _ = close.send(());
762                }
763                for event in parsed {
764                    // Bind a printed id the moment it appears rather than at the
765                    // end. Codex announces its thread before answering, so a
766                    // turn killed mid-answer stays resumable.
767                    if let Event::Started { session, .. } = &event
768                        && !bound
769                    {
770                        bound = true;
771                        persist_result = persist_session(&request, session);
772                    }
773                    // A receiver that went away is not a failure: the run should
774                    // still finish and produce its outcome.
775                    if events.send(event).await.is_err() {
776                        break;
777                    }
778                }
779            }
780        }
781        Ok::<_, std::io::Error>(())
782    };
783
784    // Race three outcomes: the run finishing, the deadline, and a cancellation
785    // request. Reading and waiting are one future so a child that produces
786    // output forever is still bounded by the timeout.
787    let work = async {
788        read_stdout.await?;
789        child.child.wait().await
790    };
791    // A timeout is optional; `pending()` makes the un-timed case the same shape
792    // rather than duplicating the whole select.
793    let deadline = async {
794        match request.timeout {
795            Some(limit) => tokio::time::sleep(limit).await,
796            None => std::future::pending().await,
797        }
798    };
799
800    let status = tokio::select! {
801        // Biased so a finished run is reported as finished even if a deadline
802        // or cancellation lands in the same tick.
803        biased;
804        result = work => result,
805        () = deadline => {
806            // Order matters: signal the group *before* reaping. Reaping clears
807            // the child's pid, and the group kill needs that pid to target the
808            // group, so the other order silently leaves grandchildren running.
809            let partial = shut_down(&mut child, stderr_task).await;
810            reaped.store(true, std::sync::atomic::Ordering::SeqCst);
811            return Err(Error::Timeout {
812                bin,
813                timeout: request.timeout.unwrap_or_default(),
814                partial: parser.finish().text,
815            })
816            .inspect_err(|_| drop(partial));
817        }
818        _ = cancel => {
819            // Cooperative teardown: the caller is waiting on this, so the tree
820            // is signalled, reaped and joined before returning.
821            shut_down(&mut child, stderr_task).await;
822            reaped.store(true, std::sync::atomic::Ordering::SeqCst);
823            return Err(Error::Cancelled { bin });
824        }
825    }
826    .map_err(|source| Error::Spawn {
827        bin: bin.clone(),
828        source,
829    })?;
830
831    // The child has been reaped, so its pid must not be signalled again, by the
832    // guard here or by `Run::drop` racing this.
833    child.armed = false;
834    reaped.store(true, std::sync::atomic::Ordering::SeqCst);
835
836    drop(events);
837    let stderr = stderr_task.await.unwrap_or_default();
838    let saw_structured = parser.saw_structured_record();
839    let saw_terminal = parser.saw_terminal_record();
840    let terminal = parser.finish();
841    let exit_code = status.code().unwrap_or(-1);
842
843    // Under a structured format, silently handing back raw stdout would turn a
844    // protocol failure into a plausible-looking answer. A run that recognized
845    // nothing, or never reached its terminal record, did not produce a result
846    // this crate can vouch for, so it is reported rather than papered over.
847    let structured = plan.format != crate::Format::Text;
848    if structured && exit_code == 0 {
849        if !saw_structured {
850            return Err(Error::Parse {
851                agent: request.agent,
852                detail: format!(
853                    "no recognizable {} records in {} lines of output;                      the CLI's output shape has probably changed",
854                    request.agent,
855                    raw.lines().count()
856                ),
857            });
858        }
859        if !saw_terminal {
860            return Err(Error::Parse {
861                agent: request.agent,
862                detail: "the stream ended without its terminal record, so the turn                          did not complete"
863                    .into(),
864            });
865        }
866    }
867
868    // Plain text has no structure to validate: the stream is the answer.
869    let mut terminal = terminal;
870    if terminal.text.is_empty() && !structured {
871        terminal.text = raw.trim().to_string();
872    }
873
874    // A provider refusal is not always an exit code. Claude can report a
875    // blocking `rate_limit_event` and still exit 0, and the crate promises that
876    // quota refusals surface as `Error::RateLimited`, so the terminal state is
877    // checked regardless of how the process exited.
878    let quota_blocked = terminal
879        .rate_limit
880        .as_ref()
881        .is_some_and(crate::outcome::RateLimit::is_blocking);
882    // An unauthenticated Claude run exits 0 and reports the problem in its
883    // result text, so checking only the exit code would hand back a successful
884    // Outcome whose answer is "Please run /login".
885    //
886    // Read from stderr and the agent's own prose rather than the raw stream, for
887    // the reason `classify` does the same with quota wording: a phrase hunted
888    // through structured output matches ids and field names, not statements.
889    //
890    // The answer is read at its opening only, by the same rule and the same
891    // helper `classify_run` uses. This gate used to read `terminal.text` whole
892    // while the classifier it guards read three lines, so the two could
893    // disagree: a healthy answer that merely discussed logging in opened the
894    // error path, no classifier would name it, and the turn fell out the far
895    // end as `Error::Failed` with exit code 0 and nothing to report. One rule,
896    // one helper, so that disagreement cannot exist.
897    let unauthenticated =
898        answer_reports_no_credentials(&terminal.text) || looks_unauthenticated(&stderr);
899    // The agent saying its turn failed is as much a failure as a non-zero exit,
900    // and Claude reports an unknown model exactly this way: exit 0, `is_error`
901    // true, and the explanation where the answer would be.
902    let turn_failed = terminal.stop == Stop::Error;
903    if exit_code != 0 || quota_blocked || unauthenticated || turn_failed {
904        let error = classify_run(request.agent, &bin, exit_code, &stderr, &raw, &terminal);
905        /*
906         * The backstop, and the reason a false positive can no longer cost an
907         * answer.
908         *
909         * Everything above is a heuristic reading of text the agent wrote, and
910         * a heuristic will be wrong eventually: these phrases are ordinary
911         * English, and an agent asked about rate limits or logging in answers
912         * in exactly the vocabulary that describes being rate limited or
913         * logged out. What must never follow from being wrong is discarding a
914         * finished answer.
915         *
916         * So a run whose process exited cleanly, whose terminal record says
917         * the turn completed, and which carries no parsed quota block is only
918         * ever failed by a classifier that can *name* the failure. A generic
919         * `Failed` on that run is the classifiers disagreeing with the gate,
920         * not evidence, and the answer stands.
921         */
922        let exited_clean = exit_code == 0 && !quota_blocked && !turn_failed;
923        if !exited_clean || names_a_failure(&error) {
924            return Err(error);
925        }
926    }
927
928    // A fork lands on a *new* id the agent only reveals at the end, so the name
929    // has to be repointed once the run settles. Everything else was bound above.
930    persist_result?;
931    // Resolved before the terminal is consumed by the Outcome below.
932    let structured = terminal.structured.clone().or_else(|| {
933        request
934            .schema
935            .as_ref()
936            .and_then(|_| serde_json::from_str(&terminal.text).ok())
937    });
938    if let Some(token) = &terminal.session
939        && !bound
940    {
941        persist_session(&request, token)?;
942    }
943    Ok(Outcome {
944        agent: request.agent,
945        session: terminal.session,
946        text: terminal.text,
947        usage: terminal.usage,
948        stop: terminal.stop,
949        rate_limit: terminal.rate_limit,
950        exit_code,
951        stderr,
952        unparsed: terminal.unparsed,
953        first_unparsed: terminal.first_unparsed,
954        // Claude reports the conforming value separately; Codex returns it as
955        // the answer text, so that is parsed only when a schema was asked for.
956        // Prose is never reinterpreted as data.
957        structured,
958    })
959}
960
961/// Drive one interactive Codex turn over app-server's JSON-RPC transport.
962///
963/// Unlike `codex exec`, app-server remains alive after a turn completes. This
964/// driver therefore treats `turn/completed` as the terminal record, closes the
965/// protocol pipe, and reaps the service process itself.
966#[allow(
967    clippy::too_many_lines,
968    reason = "one select loop owns the protocol, control channel, deadline, and child lifecycle"
969)]
970async fn drive_codex_app_server(
971    child: Child,
972    request: Request,
973    events: mpsc::Sender<Event>,
974    cancel: tokio::sync::oneshot::Receiver<()>,
975    reaped: std::sync::Arc<std::sync::atomic::AtomicBool>,
976    controls: Option<mpsc::Receiver<Control>>,
977) -> Result<Outcome> {
978    let mut child = ChildGuard { child, armed: true };
979    let plan = request.plan();
980    let bin = plan.bin.clone();
981    let Some(mut stdin) = child.child.stdin.take() else {
982        return Err(Error::Spawn {
983            bin,
984            source: std::io::Error::other("stdin was not piped for Codex app-server"),
985        });
986    };
987    let Some(stdout) = child.child.stdout.take() else {
988        return Err(Error::Spawn {
989            bin,
990            source: std::io::Error::other("stdout was not piped for Codex app-server"),
991        });
992    };
993    let Some(mut controls) = controls else {
994        return Err(Error::Spawn {
995            bin,
996            source: std::io::Error::other("Codex app-server has no host control channel"),
997        });
998    };
999
1000    let stderr = child.child.stderr.take();
1001    let stderr_task = tokio::spawn(async move {
1002        let mut buf = String::new();
1003        if let Some(handle) = stderr {
1004            let mut reader = BufReader::new(handle);
1005            let mut line = String::new();
1006            while let Ok(Some(_)) = read_bounded_line(&mut reader, &mut line).await {
1007                append_capped(&mut buf, &line);
1008            }
1009        }
1010        buf
1011    });
1012
1013    let mut protocol = crate::codex_app_server::Protocol::new(request.clone());
1014    for opening in protocol.opening() {
1015        stdin
1016            .write_all(opening.as_bytes())
1017            .await
1018            .map_err(|source| Error::Spawn {
1019                bin: bin.clone(),
1020                source,
1021            })?;
1022    }
1023    stdin.flush().await.map_err(|source| Error::Spawn {
1024        bin: bin.clone(),
1025        source,
1026    })?;
1027
1028    let mut reader = BufReader::new(stdout);
1029    let mut line = String::new();
1030    let mut raw = String::new();
1031    let mut pending = VecDeque::new();
1032    let mut bound = false;
1033    let mut persist_result: Result<()> = Ok(());
1034    let deadline = async {
1035        match request.timeout {
1036            Some(limit) => tokio::time::sleep(limit).await,
1037            None => std::future::pending().await,
1038        }
1039    };
1040    tokio::pin!(deadline);
1041    tokio::pin!(cancel);
1042
1043    while !protocol.finished {
1044        tokio::select! {
1045            biased;
1046            // User steering and approval answers outrank the agent's output.
1047            // app-server can keep stdout continuously ready with reasoning and
1048            // text deltas; reading it first in a biased select could starve a
1049            // correction precisely while Codex was busiest.
1050            control = controls.recv() => {
1051                let Some(control) = control else {
1052                    continue;
1053                };
1054                pending.push_back(control);
1055                flush_codex_controls(&mut protocol, &mut pending, &mut stdin, &bin).await?;
1056                stdin.flush().await.map_err(|source| Error::Spawn {
1057                    bin: bin.clone(), source
1058                })?;
1059            }
1060            record = read_bounded_line(&mut reader, &mut line) => {
1061                if record.map_err(|source| Error::Spawn { bin: bin.clone(), source })?.is_some() {
1062                    append_capped(&mut raw, &line);
1063                    if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
1064                        let step = protocol.push(&value);
1065                        for event in step.events {
1066                            if let Event::Started { session, .. } = &event
1067                                && !bound
1068                            {
1069                                bound = true;
1070                                persist_result = persist_session(&request, session);
1071                            }
1072                            let _ = events.send(event).await;
1073                        }
1074                        for write in step.writes {
1075                            stdin.write_all(write.as_bytes()).await.map_err(|source| {
1076                                Error::Spawn { bin: bin.clone(), source }
1077                            })?;
1078                        }
1079                        flush_codex_controls(&mut protocol, &mut pending, &mut stdin, &bin)
1080                            .await?;
1081                        stdin.flush().await.map_err(|source| Error::Spawn {
1082                            bin: bin.clone(), source
1083                        })?;
1084                    } else {
1085                        protocol.terminal.unparsed += 1;
1086                        if protocol.terminal.first_unparsed.is_none() {
1087                            protocol.terminal.first_unparsed = Some(line.clone());
1088                        }
1089                    }
1090                } else {
1091                    protocol.failure.get_or_insert_with(|| {
1092                        "app-server closed stdout before turn/completed".to_string()
1093                    });
1094                    protocol.finished = true;
1095                }
1096            }
1097            () = &mut deadline => {
1098                let partial = protocol.terminal.text.clone();
1099                shut_down(&mut child, stderr_task).await;
1100                reaped.store(true, std::sync::atomic::Ordering::SeqCst);
1101                return Err(Error::Timeout {
1102                    bin,
1103                    timeout: request.timeout.unwrap_or_default(),
1104                    partial,
1105                });
1106            }
1107            _ = &mut cancel => {
1108                shut_down(&mut child, stderr_task).await;
1109                reaped.store(true, std::sync::atomic::Ordering::SeqCst);
1110                return Err(Error::Cancelled { bin });
1111            }
1112        }
1113    }
1114
1115    // app-server is a service rather than a one-shot process. EOF asks it to
1116    // stop cleanly; the short fallback prevents a completed turn from hanging
1117    // because a future CLI release keeps serving after its input closes.
1118    drop(stdin);
1119    if tokio::time::timeout(std::time::Duration::from_secs(2), child.child.wait())
1120        .await
1121        .is_err()
1122    {
1123        kill_process_group(&child.child);
1124        let _ = child.child.kill().await;
1125    }
1126    child.armed = false;
1127    reaped.store(true, std::sync::atomic::Ordering::SeqCst);
1128    drop(events);
1129    let stderr = stderr_task.await.unwrap_or_default();
1130
1131    persist_result?;
1132    if let Some(detail) = protocol.failure {
1133        return Err(Error::Parse {
1134            agent: request.agent,
1135            detail,
1136        });
1137    }
1138
1139    let terminal = protocol.terminal;
1140    if terminal.stop == Stop::Error {
1141        return Err(classify_run(
1142            request.agent,
1143            &bin,
1144            0,
1145            &stderr,
1146            &raw,
1147            &terminal,
1148        ));
1149    }
1150    let structured = terminal.structured.clone().or_else(|| {
1151        request
1152            .schema
1153            .as_ref()
1154            .and_then(|_| serde_json::from_str(&terminal.text).ok())
1155    });
1156    Ok(Outcome {
1157        agent: request.agent,
1158        session: terminal.session,
1159        text: terminal.text,
1160        usage: terminal.usage,
1161        stop: terminal.stop,
1162        rate_limit: terminal.rate_limit,
1163        exit_code: 0,
1164        stderr,
1165        unparsed: terminal.unparsed,
1166        first_unparsed: terminal.first_unparsed,
1167        structured,
1168    })
1169}
1170
1171/// Write every control whose protocol ids are available, preserving earlier
1172/// messages until thread and turn startup have both completed.
1173async fn flush_codex_controls(
1174    protocol: &mut crate::codex_app_server::Protocol,
1175    pending: &mut VecDeque<Control>,
1176    stdin: &mut tokio::process::ChildStdin,
1177    bin: &str,
1178) -> Result<()> {
1179    let mut waiting = VecDeque::new();
1180    while let Some(control) = pending.pop_front() {
1181        let encoded = match &control {
1182            Control::Message(message) => protocol.steer(message),
1183            Control::Approval { id, decision } => protocol.respond(id, decision),
1184        };
1185        if let Some(encoded) = encoded {
1186            stdin
1187                .write_all(encoded.as_bytes())
1188                .await
1189                .map_err(|source| Error::Spawn {
1190                    bin: bin.to_string(),
1191                    source,
1192                })?;
1193        } else {
1194            waiting.push_back(control);
1195        }
1196    }
1197    pending.append(&mut waiting);
1198    Ok(())
1199}
1200
1201/// Kill the process group, reap the child, and join the stderr reader.
1202///
1203/// The orderly teardown both cancellation and timeout share. Returns whatever
1204/// stderr had been captured, so a caller can still report why a run was stopped.
1205async fn shut_down(child: &mut ChildGuard, stderr_task: tokio::task::JoinHandle<String>) -> String {
1206    kill_process_group(&child.child);
1207    // Reap, so the caller is not left with a zombie once this returns.
1208    let _ = child.child.kill().await;
1209    child.armed = false;
1210    // The pipes are closed now that the child is gone, so this finishes
1211    // promptly rather than hanging the cancellation.
1212    stderr_task.await.unwrap_or_default()
1213}
1214
1215/// Turn a failure into the most specific error available, agent included so an
1216/// auth failure can carry the right login command.
1217fn classify_run(
1218    agent: crate::Agent,
1219    bin: &str,
1220    code: i32,
1221    stderr: &str,
1222    stdout: &str,
1223    terminal: &Terminal,
1224) -> Error {
1225    // Checked before quota and before a plain failure: a login problem is the
1226    // most specific reading of the output, and the only one a user can act on
1227    // directly.
1228    let named = |source: &str| Error::NotAuthenticated {
1229        agent,
1230        bin: bin.to_string(),
1231        message: first_meaningful_line(source).unwrap_or_default(),
1232        hint: agent.login_hint(),
1233    };
1234
1235    // The CLI's own channel, read whole: Copilot's notice runs to five lines.
1236    if looks_unauthenticated(stderr) {
1237        return named(stderr);
1238    }
1239
1240    /*
1241     * The agent's own answer, read only at the top.
1242     *
1243     * An agent with no credentials has nothing to say but the notice, so the
1244     * phrase is in its opening lines and the whole answer is those lines.
1245     * An agent that *writes about* logging in buries the same words in
1246     * paragraphs, and reading the whole answer counted that as a login
1247     * failure: a reply explaining why a publish had been refused mentioned
1248     * not being authenticated, so the run was reported as an auth error, the
1249     * hint told the user to run `/login`, and the answer itself was replaced
1250     * by the report. An agent's prose is not a diagnosis of the agent.
1251     */
1252    for source in [terminal.text.as_str(), stdout] {
1253        if answer_reports_no_credentials(source) {
1254            return named(&opening_lines(source, OPENING_LINES));
1255        }
1256    }
1257    classify(agent, bin, code, stderr, stdout, terminal)
1258}
1259
1260/// The longest an agent's answer may be and still be read as a notice.
1261///
1262/// A CLI that has been stopped says so briefly: Claude's is one sentence and a
1263/// reset time. An answer that *discusses* limits runs to paragraphs and uses
1264/// exactly the same words, so length is the only thing separating them.
1265const NOTICE_MAX: usize = 240;
1266
1267/// How far into an agent's own output a diagnosis may be read from.
1268///
1269/// Three rather than one, because a CLI is entitled to a banner line before it
1270/// says what is wrong, and three rather than more, because past that an agent
1271/// is answering the question it was asked.
1272const OPENING_LINES: usize = 3;
1273
1274/// The first `count` non-blank lines, trimmed and rejoined.
1275fn opening_lines(text: &str, count: usize) -> String {
1276    text.lines()
1277        .map(str::trim)
1278        .filter(|line| !line.is_empty())
1279        .take(count)
1280        .collect::<Vec<_>>()
1281        .join("\n")
1282}
1283
1284/// Whether an agent's own answer is a credentials notice rather than an answer
1285/// that happens to discuss credentials.
1286///
1287/// The single rule for reading an answer as a diagnosis of the run, shared by
1288/// the gate in `run` and by `classify_run`. They read the same text for the
1289/// same phrases and used to apply different rules to it: whole text at the
1290/// gate, opening lines in the classifier. A healthy answer about logging in
1291/// satisfied one and not the other, which opened the error path for a run no
1292/// classifier would then name.
1293///
1294/// Short *and* at the top, which is the same rule the quota branch applies,
1295/// and it takes both halves. Lines alone were not enough: asked to explain the
1296/// difference between a rate limit and an auth failure, a live Claude answered
1297/// in one 900-character paragraph, so "the first three lines" was the entire
1298/// essay and the phrase inside it convicted the run. Prose wraps at the
1299/// window, not at a newline, so length is what distinguishes a notice from an
1300/// answer. A real notice is a sentence: `Not logged in, please run /login`.
1301fn answer_reports_no_credentials(text: &str) -> bool {
1302    let opening = opening_lines(text, OPENING_LINES);
1303    opening.len() <= NOTICE_MAX && looks_unauthenticated(&opening)
1304}
1305
1306/// Whether a classifier named the failure rather than falling through to the
1307/// generic one.
1308///
1309/// `Error::Failed` is what `classify` returns when nothing more specific fits.
1310/// On a run that exited cleanly that is not a diagnosis, it is the absence of
1311/// one, and an answer must not be discarded for it.
1312fn names_a_failure(error: &Error) -> bool {
1313    !matches!(error, Error::Failed { .. })
1314}
1315
1316/// Whether text is an agent saying it has no usable credentials.
1317///
1318/// Narrow on purpose. Mislabelling an ordinary failure as an auth problem sends
1319/// someone to re-login over something unrelated, so these are phrases the CLIs
1320/// actually emit rather than every string containing "auth".
1321fn looks_unauthenticated(text: &str) -> bool {
1322    const PHRASES: &[&str] = &[
1323        // Claude, verified: an unauthenticated run answers exactly this.
1324        "not logged in",
1325        "please run /login",
1326        // Copilot, verified: it exits 1 with plain text, and none of the other
1327        // phrases here appear in it. Its wording shares no vocabulary with the
1328        // other two, which is why this had to be observed rather than guessed.
1329        "no authentication information",
1330        "invalid api key",
1331        "authentication_error",
1332        "unauthorized",
1333        "not authenticated",
1334        "no credentials",
1335        "credentials not found",
1336        "please log in",
1337    ];
1338    let lower = text.to_ascii_lowercase();
1339    PHRASES.iter().any(|needle| lower.contains(needle)) || mentions_status(&lower, "401")
1340}
1341
1342/// Whether `code` appears as a standalone token rather than inside a longer run
1343/// of characters.
1344///
1345/// `401` was previously matched as a bare substring, which made any Copilot
1346/// failure an auth failure whenever one of the UUIDs it prints happened to
1347/// contain those three digits: `"id":"1b0b1401-cb86-..."` was enough. That is
1348/// not rare, since a run emits several ids, so the misdiagnosis was
1349/// intermittent and told someone to re-login over an unrelated failure.
1350///
1351/// A status code is a word. Requiring non-alphanumeric neighbours keeps
1352/// `HTTP 401` and `(status 401)` while rejecting every hex blob, and a UUID
1353/// cannot produce a standalone `401` at all because its groups are four, eight
1354/// or twelve characters long.
1355fn mentions_status(haystack: &str, code: &str) -> bool {
1356    haystack.match_indices(code).any(|(at, _)| {
1357        let before = haystack[..at].chars().next_back();
1358        let after = haystack[at + code.len()..].chars().next();
1359        let free = |c: Option<char>| c.is_none_or(|c| !c.is_alphanumeric());
1360        free(before) && free(after)
1361    })
1362}
1363
1364/// Turn a non-zero exit into the most specific error available.
1365fn classify(
1366    agent: crate::Agent,
1367    bin: &str,
1368    code: i32,
1369    stderr: &str,
1370    stdout: &str,
1371    terminal: &Terminal,
1372) -> Error {
1373    let quota_signalled = terminal
1374        .rate_limit
1375        .as_ref()
1376        .is_some_and(crate::outcome::RateLimit::is_blocking);
1377    // Scanning the *raw* stream for quota wording is a false-positive machine:
1378    // under `stream-json` Claude prints a `rate_limit_event` record on every
1379    // run, including one whose status is `allowed`, so the substring
1380    // `rate_limit` is present in perfectly healthy output. Where the stream
1381    // parsed, the parsed signal and the agent's own prose decide; the raw scan
1382    // is only the fallback for output that produced neither.
1383    /*
1384     * The agent's own answer is evidence about the *topic*, not about the run.
1385     *
1386     * `terminal.text` is what the agent said. A turn that discusses quotas at
1387     * any length contains the vocabulary this function searches for, so a
1388     * finished, successful answer on that subject classified its own run as
1389     * blocked and replaced itself with a banner quoting one of its own
1390     * sentences. The same shape as the auth misclassification fixed in 0.4.2,
1391     * one branch further down the same function.
1392     *
1393     * So the run's own channels stay authoritative. `error_message` is the
1394     * CLI's own field rather than the model's words, and is read whole. The
1395     * answer is read only when it is short enough to *be* a notice: a run that
1396     * was really stopped has the notice and nothing else to say, in a couple
1397     * of lines, while an answer that discusses the subject runs to paragraphs.
1398     * Length is the one thing that separates them, because the vocabulary is
1399     * identical by definition.
1400     */
1401    let reported = terminal.error_message.clone().unwrap_or_default();
1402    let answered = if terminal.text.len() <= NOTICE_MAX {
1403        opening_lines(&terminal.text, OPENING_LINES)
1404    } else {
1405        String::new()
1406    };
1407    let prose = if terminal.text.is_empty() {
1408        format!("{reported}\n{}", opening_lines(stdout, OPENING_LINES))
1409    } else {
1410        format!("{reported}\n{answered}")
1411    };
1412    if quota_signalled || looks_rate_limited(stderr) || looks_rate_limited(&prose) {
1413        return Error::RateLimited {
1414            bin: bin.to_string(),
1415            message: first_meaningful_line(stderr)
1416                .or_else(|| first_meaningful_line(&prose))
1417                .unwrap_or_else(|| "usage limit reached".to_string()),
1418        };
1419    }
1420    // A rejected flag is not a failed request, it is this crate and the CLI
1421    // disagreeing about what the CLI accepts. Naming that is the difference
1422    // between "the run failed" and "your codex is a different version".
1423    if let Some(detail) = rejected_flag(stderr).or_else(|| rejected_flag(stdout)) {
1424        return Error::FlagRejected {
1425            bin: bin.to_string(),
1426            detail,
1427        };
1428    }
1429    // Checked before the generic failure but after quota and a rejected flag,
1430    // which are more specific readings of the same output.
1431    if terminal.stop == Stop::Error {
1432        return Error::AgentError {
1433            agent,
1434            bin: bin.to_string(),
1435            status: terminal.error_status,
1436            // Codex reports the reason apart from the answer; Claude puts it
1437            // where the answer would be.
1438            message: terminal
1439                .error_message
1440                .clone()
1441                .or_else(|| first_meaningful_line(&terminal.text))
1442                .or_else(|| first_meaningful_line(stderr))
1443                .unwrap_or_else(|| "the agent reported a failure without explaining it".into()),
1444        };
1445    }
1446
1447    Error::Failed {
1448        bin: bin.to_string(),
1449        code,
1450        // Fall back to stdout when stderr explains nothing. Codex reports a
1451        // rejected schema as an `{"type":"error"}` event on *stdout* while
1452        // stderr carries only "Reading additional input from stdin...", so
1453        // reporting stderr alone describes the failure as a status message.
1454        stderr: first_meaningful_line(stderr)
1455            .filter(|line| looks_explanatory(line))
1456            .or_else(|| first_meaningful_line(stdout))
1457            .or_else(|| first_meaningful_line(stderr))
1458            .unwrap_or_default(),
1459    }
1460}
1461
1462/// Whether a line plausibly explains a failure rather than narrating progress.
1463fn looks_explanatory(line: &str) -> bool {
1464    const NOISE: &[&str] = &[
1465        "reading additional input",
1466        "reading prompt",
1467        "waiting",
1468        "connecting",
1469        "loading",
1470    ];
1471    let lower = line.to_ascii_lowercase();
1472    !NOISE.iter().any(|noise| lower.contains(noise))
1473}
1474
1475/// The CLI's complaint, if it refused an argument.
1476///
1477/// The phrasings are clap's and commander's, which is what all three CLIs are
1478/// built on. Matched narrowly: a false positive would relabel a genuine failure
1479/// as a version problem and send someone chasing the wrong thing.
1480fn rejected_flag(text: &str) -> Option<String> {
1481    const REJECTIONS: &[&str] = &[
1482        "unexpected argument",
1483        "unknown option",
1484        "unrecognized option",
1485        "unknown flag",
1486        "invalid option",
1487        "unexpected option",
1488    ];
1489    let lower = text.to_ascii_lowercase();
1490    REJECTIONS
1491        .iter()
1492        .any(|needle| lower.contains(needle))
1493        .then(|| first_meaningful_line(text).unwrap_or_default())
1494}
1495
1496/// Whether text carries a provider quota refusal.
1497///
1498/// Deliberately a small set of unambiguous phrases: a false positive here would
1499/// relabel an ordinary failure as a quota problem and send a caller into a
1500/// pointless backoff.
1501fn looks_rate_limited(text: &str) -> bool {
1502    let lower = text.to_ascii_lowercase();
1503    [
1504        "rate limit",
1505        "rate_limit",
1506        "usage limit",
1507        "quota exceeded",
1508        "too many requests",
1509    ]
1510    .iter()
1511    .any(|needle| lower.contains(needle))
1512        // A status code is a word, and `429` as a bare substring is in every
1513        // line number, byte count, sha fragment and identifier that happens to
1514        // contain those digits. `401` was already given this treatment after it
1515        // matched inside a UUID and sent someone to re-login; this is the same
1516        // rule, applied to the code that had been left as a substring.
1517        || mentions_status(&lower, "429")
1518}
1519
1520/// The most useful line of a CLI's output for an error message.
1521///
1522/// Not simply the first non-blank one. CLIs open with progress and status
1523/// chatter, so the first line is often "Reading additional input from stdin..."
1524/// while the actual cause is further down. That turns a report into a
1525/// misdirection: it looks like an explanation and is not one.
1526///
1527/// So a line that looks like an error wins, and the first non-blank line is the
1528/// fallback when nothing does.
1529fn first_meaningful_line(text: &str) -> Option<String> {
1530    const ERROR_MARKERS: &[&str] = &[
1531        "error",
1532        "failed",
1533        "fatal",
1534        "panic",
1535        "denied",
1536        "invalid",
1537        "unexpected",
1538        "cannot",
1539        "unable",
1540    ];
1541    let lines: Vec<&str> = text
1542        .lines()
1543        .map(str::trim)
1544        .filter(|line| !line.is_empty())
1545        .collect();
1546
1547    lines
1548        .iter()
1549        .find(|line| {
1550            let lower = line.to_ascii_lowercase();
1551            ERROR_MARKERS.iter().any(|marker| lower.contains(marker))
1552        })
1553        .or_else(|| lines.first())
1554        .map(|line| (*line).to_string())
1555}
1556
1557/// Write the session binding back, reporting any store failure.
1558///
1559/// Called as soon as an id is known rather than only on a clean exit. Waiting
1560/// for success would lose the binding for exactly the runs where continuity
1561/// matters most: a timeout, a crash, or a cancelled turn.
1562fn persist_session(request: &Request, token: &str) -> Result<()> {
1563    let Some(binding) = &request.binding else {
1564        return Ok(());
1565    };
1566    binding
1567        .store
1568        .bind(request.agent, &binding.project, &binding.name, token)
1569        .map(|_| ())
1570}
1571
1572/// The id this run is already known by before it starts, if any.
1573///
1574/// Only a caller-assigned id qualifies: a printed id does not exist yet. This
1575/// is what makes an assigned session survive a run that never finishes.
1576fn preassigned_token(request: &Request) -> Option<String> {
1577    match &request.plan().cont {
1578        Continue::NewWith(id) => Some(id.clone()),
1579        _ => None,
1580    }
1581}
1582
1583/// Reported by an agent that exited cleanly but said nothing useful.
1584impl Outcome {
1585    /// Whether the agent produced any answer at all.
1586    #[must_use]
1587    pub fn is_empty(&self) -> bool {
1588        self.text.trim().is_empty() && self.stop == Stop::Completed
1589    }
1590}
1591
1592#[cfg(test)]
1593mod tests {
1594    use super::*;
1595    use crate::agent::Agent;
1596
1597    #[test]
1598    fn quota_phrases_are_recognized_and_ordinary_errors_are_not() {
1599        assert!(looks_rate_limited("Error: rate limit exceeded"));
1600        assert!(looks_rate_limited("HTTP 429 Too Many Requests"));
1601        assert!(looks_rate_limited("You have hit your usage limit"));
1602        // A plain failure must not be mistaken for a quota problem.
1603        assert!(!looks_rate_limited("error: no such file or directory"));
1604        assert!(!looks_rate_limited("model not found"));
1605    }
1606
1607    #[test]
1608    fn a_blocking_rate_limit_event_classifies_as_rate_limited() {
1609        let terminal = Terminal {
1610            rate_limit: Some(crate::outcome::RateLimit {
1611                status: "rejected".into(),
1612                window: Some("five_hour".into()),
1613                resets_at: None,
1614                overage_status: None,
1615                is_using_overage: None,
1616            }),
1617            ..Terminal::default()
1618        };
1619        assert!(matches!(
1620            classify(Agent::Claude, "claude", 1, "", "", &terminal),
1621            Error::RateLimited { .. }
1622        ));
1623    }
1624
1625    #[test]
1626    fn an_allowed_rate_limit_event_is_not_a_failure_cause() {
1627        let terminal = Terminal {
1628            rate_limit: Some(crate::outcome::RateLimit {
1629                status: "allowed".into(),
1630                window: None,
1631                resets_at: None,
1632                overage_status: None,
1633                is_using_overage: None,
1634            }),
1635            ..Terminal::default()
1636        };
1637        assert!(matches!(
1638            classify(Agent::Claude, "claude", 1, "boom", "", &terminal),
1639            Error::Failed { .. }
1640        ));
1641    }
1642
1643    /// The exact shape that made a Copilot run look unauthenticated: a UUID
1644    /// carrying the digits 401. Copilot prints several ids per run, so this
1645    /// misfired intermittently and told the user to re-login over a failure
1646    /// that had nothing to do with credentials.
1647    #[test]
1648    fn an_id_containing_401_is_not_an_auth_failure() {
1649        let line = r#"{"type":"session.mcp_server_status_changed","id":"1b0b1401-cb86-4276-9874-e84b94c96499"}"#;
1650        assert!(
1651            !looks_unauthenticated(line),
1652            "a hex blob is not a status code"
1653        );
1654    }
1655
1656    /// The needle still has to work where it was meant to. A status code is a
1657    /// word, and these are the forms an agent actually prints.
1658    #[test]
1659    fn a_real_401_is_still_recognized() {
1660        for text in [
1661            "HTTP 401",
1662            "request failed (status 401)",
1663            "401: unauthorized",
1664            "got a 401 from the API",
1665        ] {
1666            assert!(looks_unauthenticated(text), "should match: {text}");
1667        }
1668    }
1669
1670    /// Neighbouring digits mean it is part of some longer number, not a status.
1671    #[test]
1672    fn digits_around_401_keep_it_from_matching() {
1673        for text in ["error 4010", "code 1401", "seq 24019"] {
1674            assert!(!looks_unauthenticated(text), "should not match: {text}");
1675        }
1676    }
1677
1678    /// Verbatim from a healthy claude 2.1.205 run. Every `stream-json` run
1679    /// carries this record, and its status is `allowed`: nothing is refused.
1680    /// Scanning the raw stream for `rate_limit` matched it anyway, so any
1681    /// Claude failure was reported as a quota refusal, sending a caller to back
1682    /// off when the real cause was something they could fix.
1683    #[test]
1684    fn a_healthy_rate_limit_heartbeat_is_not_a_refusal() {
1685        let stdout = r#"{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1785331800,"rateLimitType":"five_hour","overageStatus":"rejected","isUsingOverage":false}}"#;
1686        let terminal = Terminal {
1687            stop: Stop::Error,
1688            error_status: Some(404),
1689            text: "There's an issue with the selected model (bogus-model-xyz).".into(),
1690            rate_limit: Some(crate::outcome::RateLimit {
1691                status: "allowed".into(),
1692                window: Some("five_hour".into()),
1693                resets_at: Some(1_785_331_800),
1694                overage_status: None,
1695                is_using_overage: None,
1696            }),
1697            ..Terminal::default()
1698        };
1699        let err = classify_run(Agent::Claude, "claude", 0, "", stdout, &terminal);
1700        assert!(
1701            matches!(err, Error::AgentError { .. }),
1702            "the heartbeat must not mask the real cause: {err:?}"
1703        );
1704    }
1705
1706    /// The counterpart: a refusal the parser did read must still be one, even
1707    /// though it arrives with the same zero exit code.
1708    #[test]
1709    fn a_rejected_quota_signal_is_still_a_refusal() {
1710        let terminal = Terminal {
1711            rate_limit: Some(crate::outcome::RateLimit {
1712                status: "rejected".into(),
1713                window: Some("five_hour".into()),
1714                resets_at: None,
1715                overage_status: None,
1716                is_using_overage: None,
1717            }),
1718            ..Terminal::default()
1719        };
1720        assert!(matches!(
1721            classify_run(Agent::Claude, "claude", 0, "", "", &terminal),
1722            Error::RateLimited { .. }
1723        ));
1724    }
1725
1726    /// Verbatim from a real run with an unknown model. Claude exits **0** with
1727    /// `subtype: "success"` while `is_error` is true and the explanation sits
1728    /// where the answer would be, so a caller checking only `Result::is_ok`
1729    /// renders "There's an issue with the selected model" as the answer.
1730    #[test]
1731    fn a_failed_turn_is_an_error_even_though_the_process_exited_cleanly() {
1732        let terminal = Terminal {
1733            stop: Stop::Error,
1734            error_status: Some(404),
1735            text: "There's an issue with the selected model (bogus-model-xyz). \
1736                   It may not exist or you may not have access to it."
1737                .into(),
1738            ..Terminal::default()
1739        };
1740        let err = classify_run(Agent::Claude, "claude", 0, "", "", &terminal);
1741        let Error::AgentError {
1742            agent,
1743            status,
1744            message,
1745            ..
1746        } = &err
1747        else {
1748            panic!("expected AgentError, got {err:?}")
1749        };
1750        assert_eq!(*agent, Agent::Claude);
1751        assert_eq!(*status, Some(404), "the provider status must survive");
1752        assert!(message.contains("selected model"), "{message}");
1753    }
1754
1755    /// A quota refusal and a missing login are more specific readings of the
1756    /// same shape, so they must not be swallowed by the general case.
1757    #[test]
1758    fn a_failed_turn_does_not_mask_a_more_specific_cause() {
1759        let auth = Terminal {
1760            stop: Stop::Error,
1761            text: "Not logged in · Please run /login".into(),
1762            ..Terminal::default()
1763        };
1764        assert!(
1765            classify_run(Agent::Claude, "claude", 0, "", "", &auth).is_auth_failure(),
1766            "an unauthenticated failed turn must stay an auth failure"
1767        );
1768
1769        let quota = Terminal {
1770            stop: Stop::Error,
1771            rate_limit: Some(crate::outcome::RateLimit {
1772                status: "rejected".into(),
1773                window: None,
1774                resets_at: None,
1775                overage_status: None,
1776                is_using_overage: None,
1777            }),
1778            ..Terminal::default()
1779        };
1780        assert!(
1781            matches!(
1782                classify_run(Agent::Claude, "claude", 0, "", "", &quota),
1783                Error::RateLimited { .. }
1784            ),
1785            "a quota-blocked failed turn must stay a rate limit"
1786        );
1787    }
1788
1789    /// Verified against the real CLI: with `USER` withheld, claude answers
1790    /// "Not logged in · Please run /login" and exits **0**. Checking only the
1791    /// exit code hands back a successful Outcome whose answer is a login
1792    /// prompt.
1793    #[test]
1794    fn an_unauthenticated_run_is_named_even_though_it_exits_zero() {
1795        let terminal = Terminal {
1796            text: "Not logged in · Please run /login".into(),
1797            ..Terminal::default()
1798        };
1799        let err = classify_run(Agent::Claude, "claude", 0, "", "", &terminal);
1800        let Error::NotAuthenticated { agent, hint, .. } = &err else {
1801            panic!("expected NotAuthenticated, got {err:?}")
1802        };
1803        assert_eq!(*agent, Agent::Claude);
1804        assert!(hint.contains("/login"), "{hint}");
1805        assert!(err.is_auth_failure());
1806    }
1807
1808    /// Verbatim from an unauthenticated Copilot run, captured by pointing it at
1809    /// an empty HOME. Its wording shares no phrase with Claude's or Codex's, so
1810    /// before this was observed the phrase list did not match it at all and a
1811    /// missing Copilot login was reported as a generic failure.
1812    #[test]
1813    fn copilots_own_unauthenticated_wording_is_recognized() {
1814        let stderr = "Error: No authentication information found.\n\n\
1815                      Copilot can be authenticated with GitHub using an OAuth Token or a \
1816                      Fine-Grained Personal Access Token.\n\n\
1817                      To authenticate, you can use any of the following methods:\n\
1818                      \u{2022} Start 'copilot' and run the '/login' command\n\
1819                      \u{2022} Set the COPILOT_GITHUB_TOKEN, GH_TOKEN, or GITHUB_TOKEN \
1820                      environment variable";
1821        let err = classify_run(
1822            Agent::Copilot,
1823            "copilot",
1824            1,
1825            stderr,
1826            "",
1827            &Terminal::default(),
1828        );
1829        let Error::NotAuthenticated { agent, hint, .. } = &err else {
1830            panic!("expected NotAuthenticated, got {err:?}")
1831        };
1832        assert_eq!(*agent, Agent::Copilot);
1833        assert!(hint.contains("copilot login"), "{hint}");
1834    }
1835
1836    /// Each agent's hint has to name its own login route, since they differ:
1837    /// Codex and Copilot have `login` subcommands, Claude does not.
1838    #[test]
1839    fn every_agent_offers_its_own_login_route() {
1840        for (agent, expected) in [
1841            (Agent::Claude, "setup-token"),
1842            (Agent::Codex, "codex login"),
1843            (Agent::Copilot, "copilot login"),
1844        ] {
1845            let err = classify_run(
1846                agent,
1847                agent.bin(),
1848                1,
1849                "error: unauthorized",
1850                "",
1851                &Terminal::default(),
1852            );
1853            let Error::NotAuthenticated { hint, .. } = &err else {
1854                panic!("{agent}: expected NotAuthenticated, got {err:?}")
1855            };
1856            assert!(hint.contains(expected), "{agent}: {hint}");
1857        }
1858    }
1859
1860    /// Reported from the field: a run was stopped, the user was told `claude`
1861    /// was not authenticated, and the answer was replaced by a login hint. The
1862    /// agent had been explaining why a `cargo publish` was refused, and its own
1863    /// prose contained the phrases this classifier looks for. An answer is not
1864    /// a diagnosis of the thing that produced it.
1865    #[test]
1866    fn an_agent_writing_about_authentication_is_not_an_auth_failure() {
1867        let answer = "The publish was refused before it ran.\n\n\
1868                      What denied it was the auto mode classifier, not a missing \
1869                      credential.\n\
1870                      In auto mode there is no human to receive the prompt, so an \
1871                      ask collapses into a refusal.\n\
1872                      The message said the CLI was not authenticated, which is \
1873                      unrelated: an unauthorized upload is exactly what the rule \
1874                      is there to stop.";
1875        let terminal = Terminal {
1876            text: answer.into(),
1877            ..Terminal::default()
1878        };
1879        let err = classify_run(Agent::Claude, "claude", 1, "", answer, &terminal);
1880        assert!(
1881            !err.is_auth_failure(),
1882            "an answer that discusses auth was read as an auth failure: {err:?}"
1883        );
1884    }
1885
1886    /// The other half of the same rule: the notice itself still has to be
1887    /// caught, and it arrives as the agent's entire answer.
1888    #[test]
1889    fn the_notice_is_still_caught_when_it_is_the_whole_answer() {
1890        for text in [
1891            "Not logged in · Please run /login",
1892            // A banner first, which is why the opening is three lines deep.
1893            "claude 2.1.212\n\nNot logged in · Please run /login",
1894        ] {
1895            let terminal = Terminal {
1896                text: text.into(),
1897                ..Terminal::default()
1898            };
1899            let err = classify_run(Agent::Claude, "claude", 0, "", "", &terminal);
1900            assert!(
1901                err.is_auth_failure(),
1902                "{text:?} was not read as auth: {err:?}"
1903            );
1904        }
1905    }
1906
1907    /// The gate into the error path and the classifier behind it must read an
1908    /// answer by the same rule.
1909    ///
1910    /// Shaped after the report from the field: a healthy, finished turn about
1911    /// a stalled crate release, which mentions an auth error in a later
1912    /// paragraph because that was the subject. Read whole, as the gate used
1913    /// to, the phrase convicts the run; read at its opening, as everything
1914    /// now does, the answer is an answer. An agent with no credentials leads
1915    /// with the notice, which is what makes the opening the honest place to
1916    /// look.
1917    #[test]
1918    fn an_answer_mentioning_auth_late_does_not_open_the_error_path() {
1919        let answer = "So the duplicate pastes cost nothing.\n\
1920                      The publish chain is done: 0.4.1 and 0.4.2 are both on the \
1921                      registry and tagged.\n\
1922                      Everything downstream already consumes them.\n\
1923                      The only thing still open anywhere is the crate PR, \
1924                      `pathscale/RustAgentAbstraction#18`, which is the auth error \
1925                      that ate your reply: the run was reported as `not \
1926                      authenticated` and the hint sent you to /login, while the \
1927                      credentials were fine the whole time.";
1928        assert!(
1929            !answer_reports_no_credentials(answer),
1930            "an answer discussing auth opened the error path"
1931        );
1932        // And the notice itself, which is what the rule exists to catch.
1933        assert!(answer_reports_no_credentials(
1934            "Not logged in \u{b7} Please run /login"
1935        ));
1936    }
1937
1938    /// The backstop, which is what makes a false positive survivable at all.
1939    ///
1940    /// Every phrase check here is a heuristic over ordinary English and will
1941    /// be wrong eventually. When it is, the run reaches a classifier that
1942    /// cannot name any failure and returns the generic one. On a process that
1943    /// exited cleanly with a completed turn, that verdict is the absence of
1944    /// evidence rather than evidence, and the finished answer must stand.
1945    #[test]
1946    fn a_generic_failure_does_not_name_a_failure() {
1947        let unnamed = Error::Failed {
1948            bin: "claude".into(),
1949            code: 0,
1950            stderr: String::new(),
1951        };
1952        assert!(
1953            !names_a_failure(&unnamed),
1954            "a generic failure was treated as a diagnosis, which discards the answer"
1955        );
1956        // Everything a classifier can actually name still stands on its own.
1957        assert!(names_a_failure(&Error::RateLimited {
1958            bin: "claude".into(),
1959            message: "usage limit reached".into(),
1960        }));
1961        assert!(names_a_failure(&Error::NotAuthenticated {
1962            agent: Agent::Claude,
1963            bin: "claude".into(),
1964            message: "Not logged in".into(),
1965            hint: Agent::Claude.login_hint(),
1966        }));
1967    }
1968
1969    /// Reported from the field: a finished, successful turn that happened to be
1970    /// *about* usage limits classified its own run as blocked, and the banner
1971    /// quoted one of the answer's own sentences back as the provider's message.
1972    /// An answer is evidence about its topic, not about the run that produced it.
1973    #[test]
1974    fn an_agent_writing_about_limits_is_not_a_limit() {
1975        let answer = "The three retries cost nothing extra, so that is not where it \
1976                      came from.\n\n\
1977                      Providers do not rate limit on repetition: the limit is on \
1978                      tokens per window, and a 429 is what you would see if one had \
1979                      actually been reached. Each retry does re-send the whole \
1980                      conversation, which is real spend, but spend is not the same \
1981                      thing as a block and the run reported no blocking signal at \
1982                      all.\n\
1983                      Nothing here suggests the usage limit was reached, and the \
1984                      banner quoted a sentence of this answer back as though a \
1985                      provider had written it.";
1986        let terminal = Terminal {
1987            text: answer.into(),
1988            ..Terminal::default()
1989        };
1990        let err = classify(Agent::Claude, "claude", 1, "", answer, &terminal);
1991        assert!(
1992            !matches!(err, Error::RateLimited { .. }),
1993            "an answer discussing limits was read as one: {err:?}"
1994        );
1995    }
1996
1997    /// A status code is a word. These are the shapes that used to trip it.
1998    #[test]
1999    fn a_bare_429_in_prose_is_not_a_status_code() {
2000        assert!(!looks_rate_limited("see run.rs:4291 for the caller"));
2001        assert!(!looks_rate_limited("sha 8f429ac"));
2002        assert!(looks_rate_limited("HTTP 429"));
2003        assert!(looks_rate_limited("(status 429)"));
2004        assert!(looks_rate_limited("Error: too many requests"));
2005    }
2006
2007    /// Auth is the most specific reading, so it wins over a generic failure,
2008    /// but must not swallow unrelated errors.
2009    #[test]
2010    fn ordinary_failures_are_not_mistaken_for_auth_problems() {
2011        for stderr in [
2012            "error: no such file or directory",
2013            "model not found",
2014            "rate limit exceeded",
2015            "error: unexpected argument '--sandbox' found",
2016        ] {
2017            let err = classify_run(Agent::Codex, "codex", 1, stderr, "", &Terminal::default());
2018            assert!(
2019                !err.is_auth_failure(),
2020                "{stderr:?} was misread as an auth failure: {err:?}"
2021            );
2022        }
2023    }
2024
2025    /// The exact failure that cost a round of debugging: `codex exec resume`
2026    /// rejects `--sandbox`, which `Error::Failed` reported as a generic
2027    /// non-zero exit naming a flag rather than a version mismatch.
2028    #[test]
2029    fn a_rejected_flag_is_named_as_a_version_mismatch() {
2030        let err = classify(
2031            Agent::Codex,
2032            "codex",
2033            2,
2034            "error: unexpected argument '--sandbox' found",
2035            "",
2036            &Terminal::default(),
2037        );
2038        let Error::FlagRejected { bin, detail } = err else {
2039            panic!("expected FlagRejected, got {err:?}")
2040        };
2041        assert_eq!(bin, "codex");
2042        assert!(detail.contains("--sandbox"), "{detail}");
2043    }
2044
2045    #[test]
2046    fn ordinary_failures_are_not_mistaken_for_version_drift() {
2047        for stderr in [
2048            "error: no such file or directory",
2049            "model not found",
2050            "permission denied",
2051        ] {
2052            assert!(
2053                matches!(
2054                    classify(Agent::Codex, "codex", 1, stderr, "", &Terminal::default()),
2055                    Error::Failed { .. }
2056                ),
2057                "{stderr:?} should stay a plain failure"
2058            );
2059        }
2060    }
2061
2062    /// Real output from a failing codex run: the first line is status, the
2063    /// cause is below it. Reporting the first line looks like an explanation
2064    /// while pointing at the wrong thing.
2065    #[test]
2066    fn a_status_line_does_not_masquerade_as_the_cause() {
2067        let stderr = "Reading additional input from stdin...\n\
2068                      error: invalid value 'nope' for '--sandbox <SANDBOX_MODE>'";
2069        let err = classify_run(Agent::Codex, "codex", 1, stderr, "", &Terminal::default());
2070        let Error::Failed {
2071            stderr: reported, ..
2072        } = err
2073        else {
2074            panic!("expected Failed, got {err:?}")
2075        };
2076        assert!(reported.contains("invalid value"), "reported {reported:?}");
2077    }
2078
2079    /// Codex reports a rejected schema as a JSON error event on **stdout**
2080    /// while stderr carries only a status line. Reporting stderr alone
2081    /// described the failure as "Reading additional input from stdin...",
2082    /// which is not what went wrong.
2083    #[test]
2084    fn a_cause_on_stdout_is_reported_when_stderr_only_narrates() {
2085        let stdout = r#"{"type":"error","message":"invalid_json_schema: 'additionalProperties' is required to be supplied and to be false."}"#;
2086        let err = classify_run(
2087            Agent::Codex,
2088            "codex",
2089            1,
2090            "Reading additional input from stdin...",
2091            stdout,
2092            &Terminal::default(),
2093        );
2094        let Error::Failed {
2095            stderr: reported, ..
2096        } = err
2097        else {
2098            panic!("expected Failed, got {err:?}")
2099        };
2100        assert!(
2101            reported.contains("additionalProperties"),
2102            "reported {reported:?}, which explains nothing"
2103        );
2104    }
2105
2106    #[test]
2107    fn failures_report_the_first_useful_line() {
2108        let err = classify(
2109            Agent::Claude,
2110            "claude",
2111            2,
2112            "\n\n  real problem  \nstack",
2113            "",
2114            &Terminal::default(),
2115        );
2116        let Error::Failed { code, stderr, .. } = err else {
2117            panic!("expected a plain failure")
2118        };
2119        assert_eq!(code, 2);
2120        assert_eq!(stderr, "real problem");
2121    }
2122
2123    /// Prompts and session ids ride the argv, and `Run::argv` invites logging
2124    /// it. The redacted form must keep the shape while dropping the content.
2125    #[test]
2126    fn redaction_removes_prompts_and_session_ids_but_keeps_flags() {
2127        let request = crate::Request::new(Agent::Claude, "my secret prompt")
2128            .system("secret system")
2129            .session_id("11111111-2222-3333-4444-555555555555");
2130        let safe = redact(&request.typed_argv().unwrap());
2131
2132        for secret in [
2133            "my secret prompt",
2134            "secret system",
2135            "11111111-2222-3333-4444-555555555555",
2136        ] {
2137            assert!(
2138                !safe.iter().any(|a| a.contains(secret)),
2139                "{secret:?} survived redaction: {safe:?}"
2140            );
2141        }
2142        // Still recognisable as the same command.
2143        assert_eq!(safe[0], "claude");
2144        assert!(safe.contains(&"--permission-mode".to_string()));
2145        assert!(safe.contains(&"--session-id".to_string()));
2146    }
2147
2148    #[test]
2149    fn codex_trailing_prompt_is_redacted_even_without_a_flag() {
2150        let request = crate::Request::new(Agent::Codex, "my secret prompt");
2151        let safe = redact(&request.typed_argv().unwrap());
2152        assert_eq!(safe.last().unwrap(), REDACTED);
2153        assert_eq!(safe[1], "exec", "the subcommand must survive");
2154    }
2155
2156    /// Redaction must cover the two shapes positional guesswork misses: Codex's
2157    /// bare trailing prompt, and raw arguments whose contents are unknowable.
2158    #[test]
2159    fn redaction_covers_positional_prompts_and_unchecked_arguments() {
2160        let request = crate::Request::new(Agent::Codex, "my secret prompt")
2161            .unchecked_args(["-c", "api_key=hunter2"]);
2162        let safe = redact(&request.typed_argv().unwrap());
2163        assert!(!safe.iter().any(|a| a.contains("my secret prompt")));
2164        assert!(
2165            !safe.iter().any(|a| a.contains("hunter2")),
2166            "unchecked arguments may hold secrets: {safe:?}"
2167        );
2168        assert_eq!(safe[1], "exec", "the subcommand must survive");
2169    }
2170
2171    /// A resume id is a capability: it continues someone's conversation.
2172    #[test]
2173    fn redaction_covers_the_codex_positional_resume_id() {
2174        let request = crate::Request::new(Agent::Codex, "hi").resume("thread-secret-9");
2175        let safe = redact(&request.typed_argv().unwrap());
2176        assert!(
2177            !safe.iter().any(|a| a.contains("thread-secret-9")),
2178            "{safe:?}"
2179        );
2180        assert!(safe.contains(&"resume".to_string()));
2181    }
2182
2183    /// `stream` is synchronous but spawns a task. Outside a runtime that would
2184    /// panic, which a `Result`-returning function must not do.
2185    #[test]
2186    fn stream_outside_a_runtime_errors_instead_of_panicking() {
2187        let err = stream(&crate::Request::new(Agent::Claude, "hi")).unwrap_err();
2188        assert!(matches!(err, Error::NoRuntime), "got {err:?}");
2189    }
2190
2191    #[tokio::test]
2192    async fn a_missing_binary_names_the_install_command() {
2193        let request = Request::new(Agent::Claude, "hi").bin("definitely-not-a-real-binary-xyz");
2194        let err = run(&request).await.unwrap_err();
2195        let Error::NotInstalled { hint, agent, .. } = err else {
2196            panic!("expected NotInstalled, got {err:?}")
2197        };
2198        assert_eq!(agent, Agent::Claude);
2199        assert!(hint.contains("claude-code"));
2200    }
2201
2202    #[test]
2203    fn transient_errors_are_distinguished_from_permanent_ones() {
2204        assert!(
2205            Error::RateLimited {
2206                bin: "claude".into(),
2207                message: String::new()
2208            }
2209            .is_transient()
2210        );
2211        assert!(
2212            !Error::NotInstalled {
2213                agent: Agent::Claude,
2214                bin: "claude".into(),
2215                hint: ""
2216            }
2217            .is_transient()
2218        );
2219    }
2220}