use std::process::Stdio;
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::mpsc;
use crate::agent::{Continue, EnvPolicy};
use crate::error::{Error, Result};
use crate::event::{Event, MAX_LINE, Parser, Terminal, append_capped};
use crate::outcome::{Outcome, Stop};
use crate::proc::{kill_group_by_pid, kill_process_group};
use crate::request::Request;
async fn read_bounded_line<R>(reader: &mut R, buf: &mut String) -> std::io::Result<Option<bool>>
where
R: tokio::io::AsyncBufRead + Unpin,
{
buf.clear();
let mut bytes = Vec::new();
let mut truncated = false;
loop {
let mut byte = [0u8; 1];
match reader.read(&mut byte).await? {
0 => {
if bytes.is_empty() {
return Ok(None);
}
break;
}
_ if byte[0] == b'\n' => break,
_ => {
if bytes.len() < MAX_LINE {
bytes.push(byte[0]);
} else {
truncated = true;
}
}
}
}
buf.push_str(&String::from_utf8_lossy(&bytes));
Ok(Some(truncated))
}
const EVENT_BUFFER: usize = 256;
#[derive(Debug)]
pub struct Run {
events: mpsc::Receiver<Event>,
typed: Vec<crate::agent::Arg>,
pid: Option<u32>,
reaped: std::sync::Arc<std::sync::atomic::AtomicBool>,
cancel: Option<tokio::sync::oneshot::Sender<()>>,
task: Option<tokio::task::JoinHandle<Result<Outcome>>>,
argv: Vec<String>,
}
impl Run {
pub async fn recv(&mut self) -> Option<Event> {
self.events.recv().await
}
#[must_use]
pub fn argv(&self) -> &[String] {
&self.argv
}
#[must_use]
pub fn redacted_argv(&self) -> Vec<String> {
redact(&self.typed)
}
pub async fn finish(mut self) -> Result<Outcome> {
self.pid = None;
while self.events.recv().await.is_some() {}
let Some(task) = self.task.take() else {
unreachable!("the handle is only taken by a consuming method")
};
match task.await {
Ok(result) => result,
Err(join) => Err(Error::Interrupted {
bin: self.argv.first().cloned().unwrap_or_default(),
detail: if join.is_panic() {
"the driver task panicked".into()
} else {
"the driver task was cancelled".into()
},
}),
}
}
pub async fn cancel(mut self) -> Result<Outcome> {
self.pid = None;
drop(self.cancel.take());
let Some(task) = self.task.take() else {
unreachable!("the handle is only taken by a consuming method")
};
match task.await {
Ok(result) => result,
Err(join) => Err(Error::Interrupted {
bin: self.argv.first().cloned().unwrap_or_default(),
detail: if join.is_panic() {
"the driver task panicked".into()
} else {
"the driver task was cancelled".into()
},
}),
}
}
pub fn detach(mut self) {
self.pid = None;
if let Some(cancel) = self.cancel.take() {
std::mem::forget(cancel);
}
drop(self.task.take());
}
}
impl Drop for Run {
fn drop(&mut self) {
if let Some(pid) = self.pid
&& !self.reaped.load(std::sync::atomic::Ordering::SeqCst)
{
kill_group_by_pid(pid);
}
drop(self.cancel.take());
if let Some(task) = self.task.take() {
task.abort();
}
}
}
const REDACTED: &str = "<redacted>";
fn redact(argv: &[crate::agent::Arg]) -> Vec<String> {
use crate::agent::Sensitivity;
argv.iter()
.map(|arg| match arg.sensitivity {
Sensitivity::Public => arg.value.clone(),
_ => REDACTED.to_string(),
})
.collect()
}
pub async fn run(request: &Request) -> Result<Outcome> {
stream(request)?.finish().await
}
pub fn stream(request: &Request) -> Result<Run> {
let runtime = tokio::runtime::Handle::try_current().map_err(|_| Error::NoRuntime)?;
let plan = request.plan();
let typed = request.typed_argv()?;
let argv: Vec<String> = typed.iter().map(|a| a.value.clone()).collect();
let mut command = Command::new(&argv[0]);
command
.args(&argv[1..])
.stdin(if plan.stdin_prompt {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(cwd) = &request.cwd {
command.current_dir(cwd);
}
match &request.env_policy {
EnvPolicy::Inherit => {}
EnvPolicy::Minimal => {
command.env_clear();
inherit_named(&mut command, &request.agent.essential_env());
}
EnvPolicy::Only(names) => {
command.env_clear();
inherit_named(&mut command, names);
}
}
for (key, value) in &request.env {
command.env(key, value);
}
#[cfg(unix)]
command.process_group(0);
if let Some(token) = preassigned_token(request) {
persist_session(request, &token)?;
}
let child = command.spawn().map_err(|source| {
if source.kind() == std::io::ErrorKind::NotFound {
Error::NotInstalled {
agent: request.agent,
bin: plan.bin.clone(),
hint: request.agent.install_hint(),
}
} else {
Error::Spawn {
bin: plan.bin.clone(),
source,
}
}
})?;
let pid = child.id();
let (tx, rx) = mpsc::channel(EVENT_BUFFER);
let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
let reaped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let request = request.clone();
let task = runtime.spawn(drive(
child,
request,
tx,
cancel_rx,
std::sync::Arc::clone(&reaped),
));
Ok(Run {
events: rx,
typed,
pid,
reaped,
cancel: Some(cancel_tx),
task: Some(task),
argv,
})
}
fn inherit_named<S: AsRef<str>>(command: &mut Command, names: &[S]) {
for name in names {
if let Some(value) = std::env::var_os(name.as_ref()) {
command.env(name.as_ref(), value);
}
}
}
struct ChildGuard {
child: Child,
armed: bool,
}
impl Drop for ChildGuard {
fn drop(&mut self) {
if self.armed {
kill_process_group(&self.child);
}
}
}
#[allow(
clippy::too_many_lines,
reason = "one linear lifecycle: feed, read, wait, classify. Splitting it \
would thread the child, parser, buffers and cancellation state \
through helpers and obscure the ordering that matters, such as \
killing the group before reaping."
)]
async fn drive(
child: Child,
request: Request,
events: mpsc::Sender<Event>,
cancel: tokio::sync::oneshot::Receiver<()>,
reaped: std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> Result<Outcome> {
let mut child = ChildGuard { child, armed: true };
let plan = request.plan();
let bin = plan.bin.clone();
if plan.stdin_prompt {
if let Some(mut stdin) = child.child.stdin.take() {
let prompt = request.agent.effective_prompt(&plan);
stdin
.write_all(prompt.as_bytes())
.await
.map_err(|source| Error::Spawn {
bin: bin.clone(),
source,
})?;
drop(stdin);
}
}
let stderr = child.child.stderr.take();
let stderr_task = tokio::spawn(async move {
let mut buf = String::new();
if let Some(handle) = stderr {
let mut reader = BufReader::new(handle);
let mut line = String::new();
while let Ok(Some(_)) = read_bounded_line(&mut reader, &mut line).await {
append_capped(&mut buf, &line);
}
}
buf
});
let stdout = child.child.stdout.take();
let mut parser = Parser::new(request.agent, plan.format);
let mut raw = String::new();
let mut bound = false;
let mut persist_result: Result<()> = Ok(());
let read_stdout = async {
if let Some(handle) = stdout {
let mut reader = BufReader::new(handle);
let mut line = String::new();
while read_bounded_line(&mut reader, &mut line).await?.is_some() {
append_capped(&mut raw, &line);
for event in parser.push(&line) {
if let Event::Started { session, .. } = &event
&& !bound
{
bound = true;
persist_result = persist_session(&request, session);
}
if events.send(event).await.is_err() {
break;
}
}
}
}
Ok::<_, std::io::Error>(())
};
let work = async {
read_stdout.await?;
child.child.wait().await
};
let deadline = async {
match request.timeout {
Some(limit) => tokio::time::sleep(limit).await,
None => std::future::pending().await,
}
};
let status = tokio::select! {
biased;
result = work => result,
() = deadline => {
let partial = shut_down(&mut child, stderr_task).await;
reaped.store(true, std::sync::atomic::Ordering::SeqCst);
return Err(Error::Timeout {
bin,
timeout: request.timeout.unwrap_or_default(),
partial: parser.finish().text,
})
.inspect_err(|_| drop(partial));
}
_ = cancel => {
shut_down(&mut child, stderr_task).await;
reaped.store(true, std::sync::atomic::Ordering::SeqCst);
return Err(Error::Cancelled { bin });
}
}
.map_err(|source| Error::Spawn {
bin: bin.clone(),
source,
})?;
child.armed = false;
reaped.store(true, std::sync::atomic::Ordering::SeqCst);
drop(events);
let stderr = stderr_task.await.unwrap_or_default();
let saw_structured = parser.saw_structured_record();
let saw_terminal = parser.saw_terminal_record();
let terminal = parser.finish();
let exit_code = status.code().unwrap_or(-1);
let structured = plan.format != crate::Format::Text;
if structured && exit_code == 0 {
if !saw_structured {
return Err(Error::Parse {
agent: request.agent,
detail: format!(
"no recognizable {} records in {} lines of output; the CLI's output shape has probably changed",
request.agent,
raw.lines().count()
),
});
}
if !saw_terminal {
return Err(Error::Parse {
agent: request.agent,
detail: "the stream ended without its terminal record, so the turn did not complete"
.into(),
});
}
}
let mut terminal = terminal;
if terminal.text.is_empty() && !structured {
terminal.text = raw.trim().to_string();
}
let quota_blocked = terminal
.rate_limit
.as_ref()
.is_some_and(crate::outcome::RateLimit::is_blocking);
let unauthenticated = looks_unauthenticated(&terminal.text);
if exit_code != 0 || quota_blocked || unauthenticated {
return Err(classify_run(
request.agent,
&bin,
exit_code,
&stderr,
&raw,
&terminal,
));
}
persist_result?;
if let Some(token) = &terminal.session
&& !bound
{
persist_session(&request, token)?;
}
Ok(Outcome {
agent: request.agent,
session: terminal.session,
text: terminal.text,
usage: terminal.usage,
stop: terminal.stop,
rate_limit: terminal.rate_limit,
exit_code,
stderr,
unparsed: terminal.unparsed,
first_unparsed: terminal.first_unparsed,
})
}
async fn shut_down(child: &mut ChildGuard, stderr_task: tokio::task::JoinHandle<String>) -> String {
kill_process_group(&child.child);
let _ = child.child.kill().await;
child.armed = false;
stderr_task.await.unwrap_or_default()
}
fn classify_run(
agent: crate::Agent,
bin: &str,
code: i32,
stderr: &str,
stdout: &str,
terminal: &Terminal,
) -> Error {
for source in [terminal.text.as_str(), stderr, stdout] {
if looks_unauthenticated(source) {
return Error::NotAuthenticated {
agent,
bin: bin.to_string(),
message: first_meaningful_line(source).unwrap_or_default(),
hint: agent.login_hint(),
};
}
}
classify(bin, code, stderr, stdout, terminal)
}
fn looks_unauthenticated(text: &str) -> bool {
const PHRASES: &[&str] = &[
"not logged in",
"please run /login",
"invalid api key",
"authentication_error",
"unauthorized",
"not authenticated",
"no credentials",
"credentials not found",
"please log in",
"401",
];
let lower = text.to_ascii_lowercase();
PHRASES.iter().any(|needle| lower.contains(needle))
}
fn classify(bin: &str, code: i32, stderr: &str, stdout: &str, terminal: &Terminal) -> Error {
let quota_signalled = terminal
.rate_limit
.as_ref()
.is_some_and(crate::outcome::RateLimit::is_blocking);
if quota_signalled || looks_rate_limited(stderr) || looks_rate_limited(stdout) {
return Error::RateLimited {
bin: bin.to_string(),
message: first_meaningful_line(stderr)
.or_else(|| first_meaningful_line(stdout))
.unwrap_or_else(|| "usage limit reached".to_string()),
};
}
if let Some(detail) = rejected_flag(stderr).or_else(|| rejected_flag(stdout)) {
return Error::FlagRejected {
bin: bin.to_string(),
detail,
};
}
Error::Failed {
bin: bin.to_string(),
code,
stderr: first_meaningful_line(stderr).unwrap_or_default(),
}
}
fn rejected_flag(text: &str) -> Option<String> {
const REJECTIONS: &[&str] = &[
"unexpected argument",
"unknown option",
"unrecognized option",
"unknown flag",
"invalid option",
"unexpected option",
];
let lower = text.to_ascii_lowercase();
REJECTIONS
.iter()
.any(|needle| lower.contains(needle))
.then(|| first_meaningful_line(text).unwrap_or_default())
}
fn looks_rate_limited(text: &str) -> bool {
let lower = text.to_ascii_lowercase();
[
"rate limit",
"rate_limit",
"usage limit",
"quota exceeded",
"too many requests",
"429",
]
.iter()
.any(|needle| lower.contains(needle))
}
fn first_meaningful_line(text: &str) -> Option<String> {
text.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(str::to_string)
}
fn persist_session(request: &Request, token: &str) -> Result<()> {
let Some(binding) = &request.binding else {
return Ok(());
};
binding
.store
.bind(request.agent, &binding.project, &binding.name, token)
.map(|_| ())
}
fn preassigned_token(request: &Request) -> Option<String> {
match &request.plan().cont {
Continue::NewWith(id) => Some(id.clone()),
_ => None,
}
}
impl Outcome {
#[must_use]
pub fn is_empty(&self) -> bool {
self.text.trim().is_empty() && self.stop == Stop::Completed
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent::Agent;
#[test]
fn quota_phrases_are_recognized_and_ordinary_errors_are_not() {
assert!(looks_rate_limited("Error: rate limit exceeded"));
assert!(looks_rate_limited("HTTP 429 Too Many Requests"));
assert!(looks_rate_limited("You have hit your usage limit"));
assert!(!looks_rate_limited("error: no such file or directory"));
assert!(!looks_rate_limited("model not found"));
}
#[test]
fn a_blocking_rate_limit_event_classifies_as_rate_limited() {
let terminal = Terminal {
rate_limit: Some(crate::outcome::RateLimit {
status: "rejected".into(),
window: Some("five_hour".into()),
resets_at: None,
}),
..Terminal::default()
};
assert!(matches!(
classify("claude", 1, "", "", &terminal),
Error::RateLimited { .. }
));
}
#[test]
fn an_allowed_rate_limit_event_is_not_a_failure_cause() {
let terminal = Terminal {
rate_limit: Some(crate::outcome::RateLimit {
status: "allowed".into(),
window: None,
resets_at: None,
}),
..Terminal::default()
};
assert!(matches!(
classify("claude", 1, "boom", "", &terminal),
Error::Failed { .. }
));
}
#[test]
fn an_unauthenticated_run_is_named_even_though_it_exits_zero() {
let terminal = Terminal {
text: "Not logged in · Please run /login".into(),
..Terminal::default()
};
let err = classify_run(Agent::Claude, "claude", 0, "", "", &terminal);
let Error::NotAuthenticated { agent, hint, .. } = &err else {
panic!("expected NotAuthenticated, got {err:?}")
};
assert_eq!(*agent, Agent::Claude);
assert!(hint.contains("/login"), "{hint}");
assert!(err.is_auth_failure());
}
#[test]
fn every_agent_offers_its_own_login_route() {
for (agent, expected) in [
(Agent::Claude, "setup-token"),
(Agent::Codex, "codex login"),
(Agent::Copilot, "copilot login"),
] {
let err = classify_run(
agent,
agent.bin(),
1,
"error: unauthorized",
"",
&Terminal::default(),
);
let Error::NotAuthenticated { hint, .. } = &err else {
panic!("{agent}: expected NotAuthenticated, got {err:?}")
};
assert!(hint.contains(expected), "{agent}: {hint}");
}
}
#[test]
fn ordinary_failures_are_not_mistaken_for_auth_problems() {
for stderr in [
"error: no such file or directory",
"model not found",
"rate limit exceeded",
"error: unexpected argument '--sandbox' found",
] {
let err = classify_run(Agent::Codex, "codex", 1, stderr, "", &Terminal::default());
assert!(
!err.is_auth_failure(),
"{stderr:?} was misread as an auth failure: {err:?}"
);
}
}
#[test]
fn a_rejected_flag_is_named_as_a_version_mismatch() {
let err = classify(
"codex",
2,
"error: unexpected argument '--sandbox' found",
"",
&Terminal::default(),
);
let Error::FlagRejected { bin, detail } = err else {
panic!("expected FlagRejected, got {err:?}")
};
assert_eq!(bin, "codex");
assert!(detail.contains("--sandbox"), "{detail}");
}
#[test]
fn ordinary_failures_are_not_mistaken_for_version_drift() {
for stderr in [
"error: no such file or directory",
"model not found",
"permission denied",
] {
assert!(
matches!(
classify("codex", 1, stderr, "", &Terminal::default()),
Error::Failed { .. }
),
"{stderr:?} should stay a plain failure"
);
}
}
#[test]
fn failures_report_the_first_useful_line() {
let err = classify(
"claude",
2,
"\n\n real problem \nstack",
"",
&Terminal::default(),
);
let Error::Failed { code, stderr, .. } = err else {
panic!("expected a plain failure")
};
assert_eq!(code, 2);
assert_eq!(stderr, "real problem");
}
#[test]
fn redaction_removes_prompts_and_session_ids_but_keeps_flags() {
let request = crate::Request::new(Agent::Claude, "my secret prompt")
.system("secret system")
.session_id("11111111-2222-3333-4444-555555555555");
let safe = redact(&request.typed_argv().unwrap());
for secret in [
"my secret prompt",
"secret system",
"11111111-2222-3333-4444-555555555555",
] {
assert!(
!safe.iter().any(|a| a.contains(secret)),
"{secret:?} survived redaction: {safe:?}"
);
}
assert_eq!(safe[0], "claude");
assert!(safe.contains(&"--permission-mode".to_string()));
assert!(safe.contains(&"--session-id".to_string()));
}
#[test]
fn codex_trailing_prompt_is_redacted_even_without_a_flag() {
let request = crate::Request::new(Agent::Codex, "my secret prompt");
let safe = redact(&request.typed_argv().unwrap());
assert_eq!(safe.last().unwrap(), REDACTED);
assert_eq!(safe[1], "exec", "the subcommand must survive");
}
#[test]
fn redaction_covers_positional_prompts_and_unchecked_arguments() {
let request = crate::Request::new(Agent::Codex, "my secret prompt")
.unchecked_args(["-c", "api_key=hunter2"]);
let safe = redact(&request.typed_argv().unwrap());
assert!(!safe.iter().any(|a| a.contains("my secret prompt")));
assert!(
!safe.iter().any(|a| a.contains("hunter2")),
"unchecked arguments may hold secrets: {safe:?}"
);
assert_eq!(safe[1], "exec", "the subcommand must survive");
}
#[test]
fn redaction_covers_the_codex_positional_resume_id() {
let request = crate::Request::new(Agent::Codex, "hi").resume("thread-secret-9");
let safe = redact(&request.typed_argv().unwrap());
assert!(
!safe.iter().any(|a| a.contains("thread-secret-9")),
"{safe:?}"
);
assert!(safe.contains(&"resume".to_string()));
}
#[test]
fn stream_outside_a_runtime_errors_instead_of_panicking() {
let err = stream(&crate::Request::new(Agent::Claude, "hi")).unwrap_err();
assert!(matches!(err, Error::NoRuntime), "got {err:?}");
}
#[tokio::test]
async fn a_missing_binary_names_the_install_command() {
let request = Request::new(Agent::Claude, "hi").bin("definitely-not-a-real-binary-xyz");
let err = run(&request).await.unwrap_err();
let Error::NotInstalled { hint, agent, .. } = err else {
panic!("expected NotInstalled, got {err:?}")
};
assert_eq!(agent, Agent::Claude);
assert!(hint.contains("claude-code"));
}
#[test]
fn transient_errors_are_distinguished_from_permanent_ones() {
assert!(
Error::RateLimited {
bin: "claude".into(),
message: String::new()
}
.is_transient()
);
assert!(
!Error::NotInstalled {
agent: Agent::Claude,
bin: "claude".into(),
hint: ""
}
.is_transient()
);
}
}