use std::collections::HashMap;
use std::ops::Deref;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize, Serializer};
use serde_json::{Map, Value, json};
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStderr, ChildStdout, Command};
use tokio::sync::{Notify, mpsc, oneshot};
use tracing::{Instrument, debug, warn};
use crate::Codex;
use crate::error::{Error, OutputStream, Result};
use crate::exec::{GroupKillGuard, SpanOutcome};
use crate::types::{ApprovalPolicy, SandboxMode};
const STDERR_TAIL_BYTES: usize = 16 * 1024;
const STARTUP_EXIT_WAIT: Duration = Duration::from_secs(2);
const STDERR_SETTLE: Duration = Duration::from_millis(500);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestId {
Number(i64),
String(String),
}
impl std::fmt::Display for RequestId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Number(n) => write!(f, "{n}"),
Self::String(s) => f.write_str(s),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Notification {
pub method: String,
pub params: Value,
}
impl Notification {
#[must_use]
pub fn agent_message(&self) -> Option<AgentMessage> {
if self.method != "item/completed" {
return None;
}
let item = self.params.get("item")?;
if item.get("type")?.as_str()? != "agentMessage" {
return None;
}
Some(AgentMessage {
thread_id: self.params.get("threadId")?.as_str()?.to_string(),
turn_id: self.params.get("turnId")?.as_str()?.to_string(),
text: item.get("text")?.as_str()?.to_string(),
phase: item
.get("phase")
.and_then(Value::as_str)
.map(str::to_string),
})
}
#[must_use]
pub fn turn_completed(&self) -> Option<TurnCompleted> {
if self.method != "turn/completed" {
return None;
}
serde_json::from_value(self.params.clone()).ok()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentMessage {
pub thread_id: String,
pub turn_id: String,
pub text: String,
pub phase: Option<String>,
}
impl AgentMessage {
#[must_use]
pub fn is_final_answer(&self) -> bool {
self.phase.as_deref() == Some("final_answer")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ServerRequest {
pub id: RequestId,
pub method: String,
pub params: Value,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ServerMessage {
Notification(Notification),
Request(ServerRequest),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum TurnStatus {
InProgress,
Completed,
Interrupted,
Failed,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Turn {
pub id: String,
pub status: TurnStatus,
#[serde(default)]
pub items: Vec<Value>,
#[serde(default)]
pub error: Option<Value>,
#[serde(default)]
pub duration_ms: Option<i64>,
}
impl Turn {
#[must_use]
pub fn final_message(&self) -> Option<&str> {
self.items
.iter()
.rev()
.filter(|item| {
item.get("type").and_then(Value::as_str) == Some("agentMessage")
&& item.get("phase").and_then(Value::as_str) == Some("final_answer")
})
.find_map(|item| item.get("text").and_then(Value::as_str))
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TurnCompleted {
pub thread_id: String,
pub turn: Turn,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Thread {
pub id: String,
pub model: Option<String>,
pub raw: Value,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ServerInfo {
pub user_agent: String,
pub codex_home: Option<String>,
pub platform_family: Option<String>,
pub platform_os: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum UserInput {
Text(String),
Raw(Value),
}
impl UserInput {
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self::Text(text.into())
}
}
impl Serialize for UserInput {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
match self {
Self::Text(text) => {
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("type", "text")?;
map.serialize_entry("text", text)?;
map.serialize_entry("text_elements", &Vec::<Value>::new())?;
map.end()
}
Self::Raw(value) => value.serialize(serializer),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadStartParams {
#[serde(skip_serializing_if = "Option::is_none")]
cwd: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
approval_policy: Option<ApprovalPolicy>,
#[serde(skip_serializing_if = "Option::is_none")]
sandbox: Option<SandboxMode>,
#[serde(skip_serializing_if = "Option::is_none")]
ephemeral: Option<bool>,
#[serde(flatten)]
extra: Map<String, Value>,
}
impl ThreadStartParams {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
self.cwd = Some(dir.into());
self
}
#[must_use]
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
#[must_use]
pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
self.approval_policy = Some(policy);
self
}
#[must_use]
pub fn sandbox(mut self, mode: SandboxMode) -> Self {
self.sandbox = Some(mode);
self
}
#[must_use]
pub fn ephemeral(mut self, ephemeral: bool) -> Self {
self.ephemeral = Some(ephemeral);
self
}
#[must_use]
pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
self.extra.insert(name.into(), value);
self
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TurnStartParams {
thread_id: String,
input: Vec<UserInput>,
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
effort: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
output_schema: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
cwd: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
approval_policy: Option<ApprovalPolicy>,
#[serde(flatten)]
extra: Map<String, Value>,
}
impl TurnStartParams {
#[must_use]
pub fn new(thread_id: impl Into<String>, input: Vec<UserInput>) -> Self {
Self {
thread_id: thread_id.into(),
input,
model: None,
effort: None,
output_schema: None,
cwd: None,
approval_policy: None,
extra: Map::new(),
}
}
#[must_use]
pub fn text(thread_id: impl Into<String>, prompt: impl Into<String>) -> Self {
Self::new(thread_id, vec![UserInput::text(prompt)])
}
#[must_use]
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
#[must_use]
pub fn effort(mut self, effort: impl Into<String>) -> Self {
self.effort = Some(effort.into());
self
}
#[must_use]
pub fn output_schema(mut self, schema: Value) -> Self {
self.output_schema = Some(schema);
self
}
#[must_use]
pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
self.cwd = Some(dir.into());
self
}
#[must_use]
pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
self.approval_policy = Some(policy);
self
}
#[must_use]
pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
self.extra.insert(name.into(), value);
self
}
}
struct RpcFailure {
code: i64,
message: String,
data: Option<Value>,
}
#[derive(Debug, Clone)]
enum Closed {
Eof,
OutputLimit { limit_bytes: usize },
Broken(String),
Terminated,
}
enum Reply {
Result(Value),
Rpc(RpcFailure),
Malformed,
Closed(Closed),
}
enum Event {
Message(ServerMessage),
Closed(Closed),
}
enum Outgoing {
Line(Vec<u8>),
Close,
}
struct State {
pending: HashMap<i64, oneshot::Sender<Reply>>,
closed: Option<Closed>,
}
struct Shared {
state: Mutex<State>,
next_id: AtomicI64,
stderr_tail: Mutex<Vec<u8>>,
stderr_done: AtomicBool,
stderr_finished: Notify,
kill: Mutex<Option<KillTarget>>,
events: mpsc::UnboundedSender<Event>,
}
fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
impl Shared {
fn fail(&self, reason: Closed) {
let pending = {
let mut state = locked(&self.state);
if state.closed.is_some() {
return;
}
state.closed = Some(reason.clone());
std::mem::take(&mut state.pending)
};
for (_, waiter) in pending {
let _ = waiter.send(Reply::Closed(reason.clone()));
}
let _ = self.events.send(Event::Closed(reason));
}
fn new(events: mpsc::UnboundedSender<Event>, kill: Option<KillTarget>) -> Self {
Self {
state: Mutex::new(State {
pending: HashMap::new(),
closed: None,
}),
next_id: AtomicI64::new(0),
stderr_tail: Mutex::new(Vec::new()),
stderr_done: AtomicBool::new(false),
stderr_finished: Notify::new(),
kill: Mutex::new(kill),
events,
}
}
fn fire_kill(&self) {
if let Some(target) = *locked(&self.kill) {
target.signal();
}
}
fn revoke_kill(&self) {
*locked(&self.kill) = None;
}
async fn stderr_settled(&self) {
let wait = async {
loop {
let notified = self.stderr_finished.notified();
if self.stderr_done.load(Ordering::Acquire) {
return;
}
notified.await;
}
};
let _ = tokio::time::timeout(STDERR_SETTLE, wait).await;
}
fn stderr_summary(&self) -> String {
let tail = locked(&self.stderr_tail);
let text = strip_ansi(&String::from_utf8_lossy(&tail));
let lines: Vec<&str> = text
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.collect();
let start = lines.len().saturating_sub(5);
lines[start..].join("\n")
}
fn error_for(&self, reason: &Closed, method: Option<&str>) -> Error {
let protocol = |message: String| Error::AppServerProtocol { message };
match reason {
Closed::OutputLimit { limit_bytes } => Error::OutputLimitExceeded {
stream: OutputStream::Stdout,
limit_bytes: *limit_bytes,
},
Closed::Terminated => protocol("the app-server session was ended by the client".into()),
Closed::Broken(message) => protocol(message.clone()),
Closed::Eof => {
let stderr = self.stderr_summary();
let while_waiting =
method.map_or_else(String::new, |m| format!(" before answering `{m}`"));
if stderr.is_empty() {
protocol(format!("codex app-server closed its output{while_waiting}"))
} else {
protocol(format!(
"codex app-server closed its output{while_waiting}; stderr: {stderr}"
))
}
}
}
}
}
fn strip_ansi(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '\u{1b}' && chars.peek() == Some(&'[') {
chars.next();
for c in chars.by_ref() {
if c.is_ascii_alphabetic() {
break;
}
}
} else {
out.push(c);
}
}
out
}
struct PendingSlot<'a> {
shared: &'a Shared,
id: i64,
}
impl Drop for PendingSlot<'_> {
fn drop(&mut self) {
locked(&self.shared.state).pending.remove(&self.id);
}
}
fn json_error(context: &str, source: serde_json::Error) -> Error {
Error::Json {
message: format!("{context}: {source}"),
source,
}
}
fn request_line(id: i64, method: &str, params: &Value) -> Result<Vec<u8>> {
let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
let mut line = format!("{{\"id\":{id},\"method\":{method}");
if !params.is_null() {
let params = serde_json::to_string(params).map_err(|e| json_error("request params", e))?;
line.push_str(",\"params\":");
line.push_str(¶ms);
}
line.push_str("}\n");
Ok(line.into_bytes())
}
fn notification_line(method: &str, params: &Value) -> Result<Vec<u8>> {
let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
let mut line = format!("{{\"method\":{method}");
if !params.is_null() {
let params =
serde_json::to_string(params).map_err(|e| json_error("notification params", e))?;
line.push_str(",\"params\":");
line.push_str(¶ms);
}
line.push_str("}\n");
Ok(line.into_bytes())
}
fn reply_line(id: &RequestId, body_key: &str, body: &Value) -> Result<Vec<u8>> {
let id = serde_json::to_string(id).map_err(|e| json_error("request id", e))?;
let body = serde_json::to_string(body).map_err(|e| json_error("reply body", e))?;
Ok(format!("{{\"id\":{id},\"{body_key}\":{body}}}\n").into_bytes())
}
#[derive(Clone)]
pub struct AppServerHandle {
shared: Arc<Shared>,
writer: mpsc::UnboundedSender<Outgoing>,
timeout: Option<Duration>,
}
impl std::fmt::Debug for AppServerHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AppServerHandle")
.field("timeout", &self.timeout)
.finish_non_exhaustive()
}
}
impl AppServerHandle {
fn closed_error(&self, method: Option<&str>) -> Error {
let reason = locked(&self.shared.state).closed.clone();
match reason {
Some(reason) => self.shared.error_for(&reason, method),
None => Error::AppServerProtocol {
message: "codex app-server is no longer accepting messages (its stdin is closed)"
.into(),
},
}
}
fn enqueue(&self, line: Vec<u8>, method: Option<&str>) -> Result<()> {
if let Some(reason) = &locked(&self.shared.state).closed {
return Err(self.shared.error_for(reason, method));
}
self.writer
.send(Outgoing::Line(line))
.map_err(|_| self.closed_error(method))
}
pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
let line = request_line(id, method, ¶ms)?;
let (waiter, answer) = oneshot::channel();
{
let mut state = locked(&self.shared.state);
if let Some(reason) = &state.closed {
return Err(self.shared.error_for(reason, Some(method)));
}
state.pending.insert(id, waiter);
}
let _slot = PendingSlot {
shared: &self.shared,
id,
};
self.writer
.send(Outgoing::Line(line))
.map_err(|_| self.closed_error(Some(method)))?;
let reply = match self.timeout {
Some(limit) => {
tokio::time::timeout(limit, answer)
.await
.map_err(|_| Error::Timeout {
timeout_seconds: limit.as_secs(),
})?
}
None => answer.await,
};
match reply {
Ok(Reply::Result(result)) => Ok(result),
Ok(Reply::Rpc(failure)) => Err(Error::AppServerRpc {
method: method.to_string(),
code: failure.code,
message: failure.message,
data: failure.data,
}),
Ok(Reply::Malformed) => Err(Error::AppServerProtocol {
message: format!(
"codex app-server answered `{method}` with neither result nor error"
),
}),
Ok(Reply::Closed(reason)) => Err(self.shared.error_for(&reason, Some(method))),
Err(_) => Err(self.closed_error(Some(method))),
}
}
pub fn notify(&self, method: &str, params: Value) -> Result<()> {
self.enqueue(notification_line(method, ¶ms)?, Some(method))
}
pub fn respond(&self, id: RequestId, result: Value) -> Result<()> {
self.enqueue(reply_line(&id, "result", &result)?, None)
}
pub fn respond_error(
&self,
id: RequestId,
code: i64,
message: impl Into<String>,
) -> Result<()> {
let body = json!({ "code": code, "message": message.into() });
self.enqueue(reply_line(&id, "error", &body)?, None)
}
pub async fn thread_start(&self, params: ThreadStartParams) -> Result<Thread> {
let params =
serde_json::to_value(params).map_err(|e| json_error("thread/start params", e))?;
let raw = self.request("thread/start", params).await?;
let id = raw
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| Error::AppServerProtocol {
message: "thread/start returned no thread id".into(),
})?
.to_string();
let model = raw.get("model").and_then(Value::as_str).map(str::to_string);
Ok(Thread { id, model, raw })
}
pub async fn turn_start(&self, params: TurnStartParams) -> Result<Turn> {
let params =
serde_json::to_value(params).map_err(|e| json_error("turn/start params", e))?;
let result = self.request("turn/start", params).await?;
let turn = result.get("turn").cloned().unwrap_or(Value::Null);
serde_json::from_value(turn).map_err(|e| Error::AppServerProtocol {
message: format!("turn/start returned no usable turn: {e}"),
})
}
pub async fn turn_steer(
&self,
thread_id: &str,
expected_turn_id: &str,
input: Vec<UserInput>,
) -> Result<String> {
let params = json!({
"threadId": thread_id,
"expectedTurnId": expected_turn_id,
"input": input,
});
let result = self.request("turn/steer", params).await?;
result
.get("turnId")
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| Error::AppServerProtocol {
message: "turn/steer returned no turn id".into(),
})
}
pub async fn turn_interrupt(&self, thread_id: &str, turn_id: &str) -> Result<()> {
let params = json!({ "threadId": thread_id, "turnId": turn_id });
self.request("turn/interrupt", params).await.map(|_| ())
}
}
#[derive(Debug, Clone)]
pub struct AppServerBuilder<'a> {
codex: &'a Codex,
client_name: String,
client_version: String,
opt_out: Vec<String>,
}
impl<'a> AppServerBuilder<'a> {
#[must_use]
pub fn client_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
self.client_name = name.into();
self.client_version = version.into();
self
}
#[must_use]
pub fn opt_out_notification(mut self, method: impl Into<String>) -> Self {
self.opt_out.push(method.into());
self
}
#[must_use]
pub fn args(&self) -> Vec<String> {
vec!["app-server".into(), "--listen".into(), "stdio://".into()]
}
#[must_use]
pub fn to_command_string(&self) -> String {
crate::exec::command_string(self.codex, self.args())
}
pub async fn start(self) -> Result<AppServer> {
let codex = self.codex;
let operation_args = self.args();
let span = crate::exec::command_span("codex.app_server", codex, &operation_args);
let args = crate::exec::assemble_args(codex, operation_args);
let command_text = format!("{} {}", codex.binary.display(), args.join(" "));
debug!(arg_count = args.len(), "starting codex app-server");
let mut outcome = SpanOutcome::start(span.clone());
let mut command = Command::new(&codex.binary);
command.args(&args);
command.stdin(std::process::Stdio::piped());
command.stdout(std::process::Stdio::piped());
command.stderr(std::process::Stdio::piped());
command.kill_on_drop(true);
crate::exec::own_process_group(&mut command, codex.process_group);
crate::exec::apply_die_with_parent(&mut command, codex.die_with_parent);
if let Some(dir) = &codex.working_dir {
command.current_dir(dir);
}
crate::exec::apply_child_environment(&mut command, codex.clear_env, &codex.env);
let mut child = match command.spawn() {
Ok(child) => child,
Err(e) => {
outcome.settle("error", None);
return Err(Error::Io {
message: format!("failed to spawn codex app-server: {e}"),
source: e,
working_dir: codex.working_dir.clone(),
});
}
};
let group = crate::exec::arm_and_notify(
codex.process_group,
codex.termination_signal,
child.id(),
codex.on_spawn.as_ref(),
);
let pid = child.id();
let stdin = child.stdin.take().expect("stdin was configured as piped");
let stdout = child.stdout.take().expect("stdout was configured as piped");
let stderr = child.stderr.take().expect("stderr was configured as piped");
let (events_tx, events_rx) = mpsc::unbounded_channel();
let (writer_tx, writer_rx) = mpsc::unbounded_channel();
let shared = Arc::new(Shared::new(
events_tx,
Some(KillTarget {
pid,
group: codex.process_group,
}),
));
tokio::spawn(read_stdout(
stdout,
Arc::clone(&shared),
codex.output_limit,
codex.working_dir.clone(),
));
tokio::spawn(drain_stderr(stderr, Arc::clone(&shared)));
tokio::spawn(write_stdin(stdin, writer_rx, Arc::clone(&shared)));
let handle = AppServerHandle {
shared,
writer: writer_tx,
timeout: codex.timeout,
};
let mut server = AppServer {
handle,
events: events_rx,
finished: false,
child,
group,
outcome,
termination_grace: codex.termination_grace,
working_dir: codex.working_dir.clone(),
command: command_text,
info: ServerInfo::default(),
};
let handshake = initialize(
&server.handle,
&self.client_name,
&self.client_version,
&self.opt_out,
)
.instrument(span)
.await;
match handshake {
Ok(info) => {
server.info = info;
Ok(server)
}
Err(error) => Err(server.abandon(error).await),
}
}
}
async fn initialize(
handle: &AppServerHandle,
name: &str,
version: &str,
opt_out: &[String],
) -> Result<ServerInfo> {
let mut params = json!({ "clientInfo": { "name": name, "version": version } });
if !opt_out.is_empty() {
params["capabilities"] = json!({ "optOutNotificationMethods": opt_out });
}
let result = handle.request("initialize", params).await?;
let info = serde_json::from_value(result).map_err(|e| Error::AppServerProtocol {
message: format!("initialize returned an unexpected response: {e}"),
})?;
handle.notify("initialized", Value::Null)?;
Ok(info)
}
#[derive(Clone, Copy)]
struct KillTarget {
pid: Option<u32>,
group: bool,
}
impl KillTarget {
fn signal(self) {
#[cfg(unix)]
if let Some(pid) = self.pid {
if self.group {
crate::exec::signal_group(pid, libc::SIGKILL);
} else if let Ok(pid) = i32::try_from(pid) {
unsafe {
libc::kill(pid, libc::SIGKILL);
}
}
}
#[cfg(not(unix))]
let _ = (self.pid, self.group);
}
}
async fn read_stdout(
stdout: ChildStdout,
shared: Arc<Shared>,
output_limit: Option<usize>,
working_dir: Option<PathBuf>,
) {
let mut reader = BufReader::new(stdout);
let mut captured = 0usize;
let reason = loop {
let line = match crate::streaming::read_bounded_line(
&mut reader,
&mut captured,
output_limit,
OutputStream::Stdout,
&working_dir,
)
.await
{
Ok(Some(line)) => line,
Ok(None) => {
shared.stderr_settled().await;
break Closed::Eof;
}
Err(Error::OutputLimitExceeded { limit_bytes, .. }) => {
shared.fire_kill();
break Closed::OutputLimit { limit_bytes };
}
Err(error) => {
shared.fire_kill();
break Closed::Broken(error.to_string());
}
};
if !line.trim_start().starts_with('{') {
debug!(
bytes = line.len(),
"ignoring a non-JSON line from codex app-server"
);
continue;
}
if let Err(reason) = route(&line, &shared) {
shared.fire_kill();
break reason;
}
};
shared.fail(reason);
}
fn route(line: &str, shared: &Shared) -> std::result::Result<(), Closed> {
let value: Value = serde_json::from_str(line).map_err(|e| {
let head: String = line.chars().take(120).collect();
Closed::Broken(format!("codex app-server sent invalid JSON ({e}): {head}"))
})?;
let method = value.get("method").and_then(Value::as_str);
let id = value.get("id");
match (method, id) {
(Some(method), Some(id)) => {
let Ok(id) = serde_json::from_value::<RequestId>(id.clone()) else {
warn!(
method_bytes = method.len(),
"ignoring a server request with an unusable id"
);
return Ok(());
};
let request = ServerRequest {
id,
method: method.to_string(),
params: value.get("params").cloned().unwrap_or(Value::Null),
};
let _ = shared
.events
.send(Event::Message(ServerMessage::Request(request)));
}
(Some(method), None) => {
let notification = Notification {
method: method.to_string(),
params: value.get("params").cloned().unwrap_or(Value::Null),
};
let _ = shared
.events
.send(Event::Message(ServerMessage::Notification(notification)));
}
(None, Some(id)) if value.get("result").is_some() || value.get("error").is_some() => {
deliver_answer(&value, id, shared);
}
(None, Some(id)) => {
let waiter = id
.as_i64()
.and_then(|id| locked(&shared.state).pending.remove(&id));
match waiter {
Some(waiter) => {
let _ = waiter.send(Reply::Malformed);
}
None => warn!("ignoring an answer with neither result nor error"),
}
}
_ => warn!("ignoring a JSON object from codex app-server that is not a message"),
}
Ok(())
}
fn deliver_answer(value: &Value, id: &Value, shared: &Shared) {
let Some(id) = id.as_i64() else {
debug!("ignoring an answer with no request id");
return;
};
let waiter = locked(&shared.state).pending.remove(&id);
let Some(waiter) = waiter else {
debug!(id, "ignoring an answer nobody is waiting for");
return;
};
let reply = match value.get("error") {
Some(error) => Reply::Rpc(RpcFailure {
code: error.get("code").and_then(Value::as_i64).unwrap_or(0),
message: error
.get("message")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
data: error.get("data").cloned(),
}),
None => Reply::Result(value.get("result").cloned().unwrap_or(Value::Null)),
};
let _ = waiter.send(reply);
}
async fn drain_stderr(mut stderr: ChildStderr, shared: Arc<Shared>) {
let mut buffer = [0u8; 4096];
loop {
match stderr.read(&mut buffer).await {
Ok(0) | Err(_) => {
shared.stderr_done.store(true, Ordering::Release);
shared.stderr_finished.notify_waiters();
break;
}
Ok(read) => {
let mut tail = locked(&shared.stderr_tail);
tail.extend_from_slice(&buffer[..read]);
if tail.len() > STDERR_TAIL_BYTES {
let excess = tail.len() - STDERR_TAIL_BYTES;
tail.drain(..excess);
}
}
}
}
}
async fn write_stdin<W: AsyncWrite + Unpin>(
mut stdin: W,
mut lines: mpsc::UnboundedReceiver<Outgoing>,
shared: Arc<Shared>,
) {
while let Some(outgoing) = lines.recv().await {
match outgoing {
Outgoing::Line(line) => {
let written = async {
stdin.write_all(&line).await?;
stdin.flush().await
}
.await;
if let Err(error) = written {
if error.kind() == std::io::ErrorKind::BrokenPipe {
debug!("codex app-server closed its stdin");
} else {
shared.fail(Closed::Broken(format!(
"failed to write to codex app-server stdin: {error}"
)));
}
break;
}
}
Outgoing::Close => break,
}
}
}
pub struct AppServer {
handle: AppServerHandle,
events: mpsc::UnboundedReceiver<Event>,
finished: bool,
child: Child,
group: GroupKillGuard,
outcome: SpanOutcome,
termination_grace: Duration,
working_dir: Option<PathBuf>,
command: String,
info: ServerInfo,
}
impl std::fmt::Debug for AppServer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AppServer")
.field("pid", &self.child.id())
.field("info", &self.info)
.finish_non_exhaustive()
}
}
impl Deref for AppServer {
type Target = AppServerHandle;
fn deref(&self) -> &AppServerHandle {
&self.handle
}
}
impl AppServer {
#[must_use]
pub fn builder(codex: &Codex) -> AppServerBuilder<'_> {
AppServerBuilder {
codex,
client_name: "codex-wrapper".to_string(),
client_version: env!("CARGO_PKG_VERSION").to_string(),
opt_out: Vec::new(),
}
}
#[must_use]
pub fn server_info(&self) -> &ServerInfo {
&self.info
}
#[must_use]
pub fn pid(&self) -> Option<u32> {
self.child.id()
}
#[must_use]
pub fn handle(&self) -> AppServerHandle {
self.handle.clone()
}
pub async fn next_message(&mut self) -> Result<Option<ServerMessage>> {
if self.finished {
return Ok(None);
}
match self.events.recv().await {
Some(Event::Message(message)) => Ok(Some(message)),
Some(Event::Closed(reason)) => {
self.finished = true;
match reason {
Closed::Eof | Closed::Terminated => Ok(None),
reason => {
let _ = self.child.start_kill();
Err(self.handle.shared.error_for(&reason, None))
}
}
}
None => {
self.finished = true;
Ok(None)
}
}
}
pub async fn shutdown(mut self) -> Result<()> {
self.handle.shared.revoke_kill();
let _ = self.handle.writer.send(Outgoing::Close);
match tokio::time::timeout(self.termination_grace, self.child.wait()).await {
Ok(Ok(status)) => {
self.group.disarm();
self.handle.shared.stderr_settled().await;
self.handle.shared.fail(Closed::Terminated);
let code = status.code().unwrap_or(-1);
if status.success() {
self.outcome.settle("ok", Some(code));
return Ok(());
}
self.outcome.settle("failed", Some(code));
Err(Error::from_command_failure(
self.command.clone(),
code,
String::new(),
self.handle.shared.stderr_summary(),
self.working_dir.clone(),
))
}
Ok(Err(error)) => Err(Error::Io {
message: format!("failed to wait on codex app-server: {error}"),
source: error,
working_dir: self.working_dir.clone(),
}),
Err(_) => self.terminate().await,
}
}
pub async fn terminate(mut self) -> Result<()> {
self.handle.shared.revoke_kill();
self.handle.shared.fail(Closed::Terminated);
let result = crate::exec::terminate_and_reap(
&mut self.child,
&mut self.group,
self.termination_grace,
self.working_dir.as_deref(),
)
.await;
self.outcome.settle("cancelled", None);
result
}
async fn abandon(mut self, error: Error) -> Error {
self.handle.shared.revoke_kill();
let outcome = if matches!(error, Error::Timeout { .. }) {
"timeout"
} else {
"failed"
};
let by_server = matches!(locked(&self.handle.shared.state).closed, Some(Closed::Eof));
let ended = if by_server {
tokio::time::timeout(STARTUP_EXIT_WAIT, self.child.wait())
.await
.ok()
} else {
self.child.try_wait().transpose()
};
if let Some(Ok(status)) = ended {
self.group.disarm();
self.handle.shared.stderr_settled().await;
let code = status.code().unwrap_or(-1);
self.outcome.settle(outcome, Some(code));
if by_server && !status.success() {
return Error::from_command_failure(
self.command.clone(),
code,
String::new(),
self.handle.shared.stderr_summary(),
self.working_dir.clone(),
);
}
return error;
}
self.handle.shared.fail(Closed::Terminated);
let _ = crate::exec::terminate_and_reap(
&mut self.child,
&mut self.group,
self.termination_grace,
self.working_dir.as_deref(),
)
.await;
self.outcome.settle(outcome, None);
error
}
}
impl Drop for AppServer {
fn drop(&mut self) {
self.handle.shared.revoke_kill();
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::CodexBuilder;
use crate::test_support::{PidFile, is_running_for_test, wait_until_gone};
fn fake(mode: &str) -> CodexBuilder {
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-app-server.sh");
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().expect("fixture path is utf-8"))
.env("FAKE_APP_SERVER_MODE", mode)
.termination_grace(Duration::from_millis(100))
.timeout(Duration::from_secs(20))
}
async fn started(mode: &str) -> AppServer {
let codex = fake(mode).build().expect("bash must exist");
AppServer::builder(&codex)
.start()
.await
.expect("the fake server starts")
}
async fn until_turn_completed(server: &mut AppServer) -> (TurnCompleted, Vec<ServerMessage>) {
let mut seen = Vec::new();
loop {
let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
.await
.expect("the turn should finish")
.expect("no stream error")
.expect("the server should not close first");
let done = match &message {
ServerMessage::Notification(n) => n.turn_completed(),
_ => None,
};
seen.push(message);
if let Some(done) = done {
return (done, seen);
}
}
}
fn methods(seen: &[ServerMessage]) -> Vec<&str> {
seen.iter()
.map(|message| match message {
ServerMessage::Notification(n) => n.method.as_str(),
ServerMessage::Request(r) => r.method.as_str(),
})
.collect()
}
#[tokio::test]
async fn the_handshake_reports_the_server_and_delivers_unsolicited_notifications() {
let mut server = started("turn").await;
assert!(server.server_info().user_agent.contains("0.149.0"));
assert_eq!(
server.server_info().codex_home.as_deref(),
Some("/home/user/.codex")
);
let first = server.next_message().await.unwrap().unwrap();
let ServerMessage::Notification(notification) = first else {
panic!("expected a notification, got {first:?}");
};
assert_eq!(notification.method, "remoteControl/status/changed");
assert_eq!(notification.params["status"], "disabled");
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn a_turn_runs_to_completion_and_yields_its_final_message() {
let mut server = started("turn").await;
let thread = server
.thread_start(
ThreadStartParams::new()
.cwd("/tmp/fixture")
.ephemeral(true)
.approval_policy(ApprovalPolicy::Never)
.sandbox(SandboxMode::ReadOnly),
)
.await
.unwrap();
assert_eq!(thread.id, "01a0d1a2-5f2e-7263-a97b-cabf3e78caff");
assert_eq!(thread.model.as_deref(), Some("gpt-5.6-sol"));
let turn = server
.turn_start(TurnStartParams::text(&thread.id, "say ok"))
.await
.unwrap();
assert_eq!(turn.status, TurnStatus::InProgress);
assert_eq!(turn.id, "01a0d1a2-5f9f-75c1-9305-fa382e7b37bc");
let (done, seen) = until_turn_completed(&mut server).await;
assert_eq!(done.thread_id, thread.id);
assert_eq!(done.turn.id, turn.id);
assert_eq!(done.turn.status, TurnStatus::Completed);
assert_eq!(done.turn.final_message(), Some("ok"));
let methods = methods(&seen);
assert!(methods.contains(&"thread/started"));
assert!(methods.contains(&"turn/started"));
assert!(methods.contains(&"item/agentMessage/delta"));
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn steering_adds_input_to_the_running_turn() {
let mut server = started("held").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
let turn = server
.turn_start(TurnStartParams::text(&thread.id, "sleep, then say DONE"))
.await
.unwrap();
let steered = server
.turn_steer(
&thread.id,
&turn.id,
vec![UserInput::text("Also append STEERED")],
)
.await
.unwrap();
assert_eq!(steered, turn.id);
let (done, seen) = until_turn_completed(&mut server).await;
assert_eq!(done.turn.final_message(), Some("DONE STEERED"));
let echoed = seen.iter().any(|message| match message {
ServerMessage::Notification(n) => {
n.method == "item/completed"
&& n.params.pointer("/item/content/0/text")
== Some(&json!("Also append STEERED"))
}
_ => false,
});
assert!(echoed, "the server never saw the steered text: {seen:?}");
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn steering_from_another_task_while_events_are_read() {
let mut server = started("held").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
let turn = server
.turn_start(TurnStartParams::text(&thread.id, "go"))
.await
.unwrap();
let handle = server.handle();
let (thread_id, turn_id) = (thread.id.clone(), turn.id.clone());
let steer = tokio::spawn(async move {
handle
.turn_steer(&thread_id, &turn_id, vec![UserInput::text("more")])
.await
});
let (done, _) = until_turn_completed(&mut server).await;
assert_eq!(done.turn.status, TurnStatus::Completed);
assert_eq!(steer.await.unwrap().unwrap(), turn.id);
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn steering_the_wrong_turn_is_an_rpc_error_that_names_both_ids() {
let server = started("held").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
let turn = server
.turn_start(TurnStartParams::text(&thread.id, "go"))
.await
.unwrap();
let error = server
.turn_steer(&thread.id, "not-the-turn", vec![UserInput::text("x")])
.await
.unwrap_err();
match error {
Error::AppServerRpc {
method,
code,
message,
..
} => {
assert_eq!(method, "turn/steer");
assert_eq!(code, -32600);
assert_eq!(
message,
format!(
"expected active turn id `not-the-turn` but found `{}`",
turn.id
)
);
}
other => panic!("expected an rpc error, got {other:?}"),
}
let error = server
.turn_interrupt(&thread.id, "not-the-turn")
.await
.unwrap_err();
assert!(
matches!(&error, Error::AppServerRpc { message, .. }
if message == &format!("expected active turn id not-the-turn but found {}", turn.id)),
"{error:?}"
);
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn steering_or_interrupting_with_no_active_turn_is_an_rpc_error() {
let server = started("held").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
let error = server
.turn_steer(&thread.id, "any", vec![UserInput::text("x")])
.await
.unwrap_err();
assert!(
matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to steer"),
"{error:?}"
);
let error = server.turn_interrupt(&thread.id, "any").await.unwrap_err();
assert!(
matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to interrupt"),
"{error:?}"
);
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn the_final_answer_is_available_when_turn_completed_carries_no_items() {
let codex = fake("turn")
.env("FAKE_APP_SERVER_ITEMS", "legacy")
.build()
.unwrap();
let mut server = AppServer::builder(&codex).start().await.unwrap();
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
server
.turn_start(TurnStartParams::text(&thread.id, "say ok"))
.await
.unwrap();
let (done, seen) = until_turn_completed(&mut server).await;
assert_eq!(done.turn.status, TurnStatus::Completed);
assert!(done.turn.items.is_empty());
assert_eq!(done.turn.final_message(), None);
let answer = seen
.iter()
.filter_map(|message| match message {
ServerMessage::Notification(n) => n.agent_message(),
_ => None,
})
.rfind(AgentMessage::is_final_answer)
.expect("the item stream carries the answer");
assert_eq!(answer.text, "ok");
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn interrupting_ends_the_turn_as_interrupted_with_no_final_message() {
let mut server = started("held").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
let turn = server
.turn_start(TurnStartParams::text(&thread.id, "go"))
.await
.unwrap();
server.turn_interrupt(&thread.id, &turn.id).await.unwrap();
let (done, _) = until_turn_completed(&mut server).await;
assert_eq!(done.turn.status, TurnStatus::Interrupted);
assert!(done.turn.items.is_empty());
assert_eq!(done.turn.final_message(), None);
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn a_server_request_is_delivered_and_the_reply_reaches_the_server() {
let mut server = started("approval").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
server
.turn_start(TurnStartParams::text(&thread.id, "touch a file"))
.await
.unwrap();
let mut seen = Vec::new();
let request = loop {
let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
.await
.unwrap()
.unwrap()
.unwrap();
if let ServerMessage::Request(request) = message {
break request;
}
seen.push(message);
};
assert_eq!(request.method, "item/commandExecution/requestApproval");
assert_eq!(request.id, RequestId::Number(0));
assert_eq!(
request.params["command"],
"/bin/zsh -lc 'touch created.txt'"
);
server
.respond(request.id, json!({ "decision": "decline" }))
.unwrap();
let (done, after) = until_turn_completed(&mut server).await;
assert_eq!(done.turn.final_message(), Some("decision: decline"));
assert!(methods(&after).contains(&"serverRequest/resolved"));
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn concurrent_requests_are_matched_to_their_answers_by_id() {
let server = started("turn").await;
let (first, second, unknown) = tokio::join!(
server.thread_start(ThreadStartParams::new()),
server.request("thread/start", json!({})),
server.request("no/such/method", json!({})),
);
assert!(first.is_ok());
assert!(second.unwrap().pointer("/thread/id").is_some());
match unknown.unwrap_err() {
Error::AppServerRpc { message, .. } => {
assert!(
message.contains("unknown variant `no/such/method`"),
"{message}"
);
}
other => panic!("expected an rpc error, got {other:?}"),
}
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn a_second_initialize_is_rejected_by_the_server() {
let server = started("turn").await;
let error = server
.request(
"initialize",
json!({ "clientInfo": { "name": "x", "version": "0" } }),
)
.await
.unwrap_err();
assert!(
matches!(&error, Error::AppServerRpc { message, .. } if message == "Already initialized"),
"{error:?}"
);
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn requests_are_written_as_the_server_expects_them() {
let log = std::env::temp_dir().join(format!(
"codex-wrapper-{}-app-server-wire.log",
std::process::id()
));
let _ = std::fs::remove_file(&log);
let codex = fake("held")
.env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
.build()
.unwrap();
let mut server = AppServer::builder(&codex)
.client_info("probe", "1.2.3")
.opt_out_notification("item/agentMessage/delta")
.opt_out_notification("mcpServer/startupStatus/updated")
.start()
.await
.unwrap();
let thread = server
.thread_start(
ThreadStartParams::new()
.cwd("/tmp/fixture")
.model("gpt-5.6-sol")
.approval_policy(ApprovalPolicy::Never)
.sandbox(SandboxMode::ReadOnly)
.ephemeral(true),
)
.await
.unwrap();
let schema = json!({ "type": "object", "required": ["answer"] });
let turn = server
.turn_start(
TurnStartParams::text(&thread.id, "hi")
.model("gpt-5.6-sol")
.effort("low")
.output_schema(schema.clone())
.cwd("/tmp/fixture")
.approval_policy(ApprovalPolicy::Never)
.param("summary", json!("none")),
)
.await
.unwrap();
server
.turn_steer(&thread.id, &turn.id, vec![UserInput::text("more")])
.await
.unwrap();
let _ = until_turn_completed(&mut server).await;
server.shutdown().await.unwrap();
let lines: Vec<Value> = std::fs::read_to_string(&log)
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).expect("every client line is JSON"))
.collect();
let _ = std::fs::remove_file(&log);
assert_eq!(
lines[0],
json!({
"id": 0,
"method": "initialize",
"params": {
"clientInfo": { "name": "probe", "version": "1.2.3" },
"capabilities": {
"optOutNotificationMethods": [
"item/agentMessage/delta",
"mcpServer/startupStatus/updated"
]
}
}
})
);
assert_eq!(lines[1], json!({ "method": "initialized" }));
assert_eq!(
lines[2],
json!({
"id": 1,
"method": "thread/start",
"params": {
"cwd": "/tmp/fixture",
"model": "gpt-5.6-sol",
"approvalPolicy": "never",
"sandbox": "read-only",
"ephemeral": true
}
})
);
assert_eq!(
lines[3],
json!({
"id": 2,
"method": "turn/start",
"params": {
"threadId": thread.id,
"input": [{ "type": "text", "text": "hi", "text_elements": [] }],
"model": "gpt-5.6-sol",
"effort": "low",
"outputSchema": schema,
"cwd": "/tmp/fixture",
"approvalPolicy": "never",
"summary": "none"
}
})
);
assert_eq!(
lines[4],
json!({
"id": 3,
"method": "turn/steer",
"params": {
"threadId": thread.id,
"expectedTurnId": turn.id,
"input": [{ "type": "text", "text": "more", "text_elements": [] }]
}
})
);
}
#[tokio::test]
async fn a_server_that_exits_cleanly_before_answering_fails_the_start_without_waiting() {
let codex = fake("exit-clean")
.termination_grace(Duration::from_secs(4))
.build()
.unwrap();
let started_at = std::time::Instant::now();
let error = AppServer::builder(&codex).start().await.unwrap_err();
assert!(
matches!(error, Error::AppServerProtocol { .. }),
"{error:?}"
);
assert!(
started_at.elapsed() < Duration::from_secs(3),
"start waited out the grace period for a server that had already exited"
);
}
#[tokio::test]
async fn invalid_json_during_the_handshake_is_reported_as_invalid_json() {
let codex = fake("bad-init").build().unwrap();
let error = AppServer::builder(&codex).start().await.unwrap_err();
assert!(
matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
"{error:?}"
);
assert_eq!(error.exit_code(), None);
}
#[tokio::test]
async fn a_response_with_neither_result_nor_error_fails_the_request_it_names() {
let server = started("no-result").await;
let error = server
.thread_start(ThreadStartParams::new())
.await
.unwrap_err();
assert!(
matches!(&error, Error::AppServerProtocol { message }
if message.contains("neither result nor error") && message.contains("thread/start")),
"{error:?}"
);
assert!(server.notify("initialized", Value::Null).is_ok());
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn the_readers_kill_switch_is_revoked_when_the_client_is_done_with_the_child() {
let sleeper = |seconds: &str| {
std::process::Command::new("sleep")
.arg(seconds)
.spawn()
.unwrap()
};
let (events, _received) = mpsc::unbounded_channel();
let mut live = sleeper("60");
let shared = Shared::new(
events.clone(),
Some(KillTarget {
pid: Some(live.id()),
group: false,
}),
);
shared.fire_kill();
assert!(
live.wait().unwrap().code().is_none(),
"the switch should have killed the process it was armed with"
);
let mut revoked = sleeper("60");
let shared = Shared::new(
events,
Some(KillTarget {
pid: Some(revoked.id()),
group: false,
}),
);
shared.revoke_kill();
shared.fire_kill();
std::thread::sleep(Duration::from_millis(200));
assert!(
revoked.try_wait().unwrap().is_none(),
"a revoked switch still killed the process"
);
revoked.kill().unwrap();
revoked.wait().unwrap();
}
#[tokio::test]
async fn every_way_of_ending_the_session_revokes_the_kill_switch() {
let armed = |shared: &Shared| locked(&shared.kill).is_some();
let server = started("turn").await;
let shared = Arc::clone(&server.handle.shared);
assert!(armed(&shared));
server.shutdown().await.unwrap();
assert!(!armed(&shared), "shutdown left the switch armed");
let server = started("turn").await;
let shared = Arc::clone(&server.handle.shared);
server.terminate().await.unwrap();
assert!(!armed(&shared), "terminate left the switch armed");
let server = started("turn").await;
let shared = Arc::clone(&server.handle.shared);
drop(server);
assert!(!armed(&shared), "dropping left the switch armed");
}
#[test]
fn the_previewed_command_includes_the_clients_global_args() {
let codex = Codex::builder()
.binary("/bin/echo")
.config("model=\"o3\"")
.build()
.unwrap();
let builder = AppServer::builder(&codex);
assert_eq!(builder.args(), ["app-server", "--listen", "stdio://"]);
assert_eq!(
builder.to_command_string(),
"/bin/echo -c 'model=\"o3\"' app-server --listen stdio://"
);
}
#[tokio::test]
async fn a_silent_server_times_out_the_handshake_and_is_stopped() {
let pid = Arc::new(Mutex::new(None));
let observed = Arc::clone(&pid);
let codex = fake("silent")
.timeout(Duration::from_millis(300))
.on_spawn(Arc::new(move |info| {
*observed.lock().unwrap() = Some(info.pid);
}))
.build()
.unwrap();
let error = AppServer::builder(&codex).start().await.unwrap_err();
assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
let pid = pid.lock().unwrap().expect("the server was spawned");
assert!(
wait_until_gone(pid).await,
"the silent server ({pid}) survived a failed start"
);
}
#[tokio::test]
async fn a_server_that_exits_at_startup_is_reported_with_its_stderr() {
let codex = fake("exit-on-start").build().unwrap();
let error = AppServer::builder(&codex).start().await.unwrap_err();
assert_eq!(error.exit_code(), Some(1), "{error:?}");
assert_eq!(
error.failure_kind(),
Some(crate::FailureKind::Config),
"{error:?}"
);
assert!(error.to_string().contains("bogus_key"), "{error}");
}
#[tokio::test]
async fn a_broken_stdin_pipe_leaves_the_verdict_to_the_reader() {
let (stdin, server_end) = tokio::io::duplex(64);
drop(server_end);
let (events, _received) = mpsc::unbounded_channel();
let shared = Arc::new(Shared::new(events, None));
let (lines, receiver) = mpsc::unbounded_channel();
lines.send(Outgoing::Line(b"{}\n".to_vec())).unwrap();
tokio::time::timeout(
Duration::from_secs(10),
write_stdin(stdin, receiver, Arc::clone(&shared)),
)
.await
.expect("the write to a closed pipe did not fail");
assert!(
locked(&shared.state).closed.is_none(),
"a write to a closed pipe was recorded as the session's failure"
);
drop(lines);
}
#[tokio::test]
async fn a_server_that_closes_its_input_and_then_fails_is_reported_by_its_exit_status() {
let codex = fake("close-stdin").build().unwrap();
let error = AppServer::builder(&codex).start().await.unwrap_err();
assert_eq!(error.exit_code(), Some(1), "{error:?}");
assert_eq!(
error.failure_kind(),
Some(crate::FailureKind::Config),
"{error:?}"
);
assert!(error.to_string().contains("bogus_key"), "{error}");
}
#[tokio::test]
async fn heavy_stderr_does_not_stall_the_session() {
let codex = fake("noisy-stderr").build().unwrap();
let server =
tokio::time::timeout(Duration::from_secs(20), AppServer::builder(&codex).start())
.await
.expect("the handshake stalled behind an undrained stderr pipe")
.unwrap();
server.shutdown().await.unwrap();
}
#[tokio::test]
async fn a_server_that_exits_mid_request_fails_it_with_the_stderr() {
let mut server = started("exit-on-turn").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
let error = server
.turn_start(TurnStartParams::text(&thread.id, "go"))
.await
.unwrap_err();
let text = error.to_string();
assert!(text.contains("turn/start"), "{text}");
assert!(
text.contains("connection to the model provider was lost"),
"{text}"
);
while server.next_message().await.unwrap().is_some() {}
assert!(server.next_message().await.unwrap().is_none());
let again = server.request("thread/start", json!({})).await.unwrap_err();
assert!(
matches!(again, Error::AppServerProtocol { .. }),
"{again:?}"
);
let error = server.shutdown().await.unwrap_err();
assert_eq!(error.exit_code(), Some(5), "{error:?}");
}
#[tokio::test]
async fn the_output_limit_ends_the_session_and_kills_the_server() {
let pid = Arc::new(Mutex::new(None));
let observed = Arc::clone(&pid);
let codex = fake("flood")
.output_limit(2048)
.on_spawn(Arc::new(move |info| {
*observed.lock().unwrap() = Some(info.pid);
}))
.build()
.unwrap();
let mut server = AppServer::builder(&codex).start().await.unwrap();
let error = loop {
match server.next_message().await {
Ok(Some(_)) => {}
Ok(None) => panic!("the limit error was swallowed"),
Err(error) => break error,
}
};
assert!(
matches!(
error,
Error::OutputLimitExceeded {
stream: OutputStream::Stdout,
limit_bytes: 2048
}
),
"{error:?}"
);
assert!(server.next_message().await.unwrap().is_none());
let pid = pid.lock().unwrap().expect("the server was spawned");
assert!(
wait_until_gone(pid).await,
"the server ({pid}) kept running after the output limit"
);
}
#[tokio::test]
async fn invalid_json_ends_the_session() {
let mut server = started("bad-json").await;
let error = loop {
match server.next_message().await {
Ok(Some(_)) => {}
Ok(None) => panic!("the malformed line was swallowed"),
Err(error) => break error,
}
};
assert!(
matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
"{error:?}"
);
}
#[tokio::test]
async fn terminate_stops_the_whole_process_group() {
let pid_file = PidFile::new("app-server-terminate");
let codex = fake("spawns-child")
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.termination_grace(Duration::from_secs(1))
.build()
.unwrap();
let server = AppServer::builder(&codex).start().await.unwrap();
let (parent, child) = read_pids(&pid_file).await;
assert!(is_running_for_test(parent) && is_running_for_test(child));
server.terminate().await.unwrap();
assert!(
wait_until_gone(parent).await,
"the server ({parent}) survived"
);
assert!(
wait_until_gone(child).await,
"the server's subprocess ({child}) survived terminate"
);
let marker = term_marker(&pid_file);
assert!(
marker.exists(),
"terminate killed the server without asking it to stop first"
);
let _ = std::fs::remove_file(marker);
}
#[tokio::test]
async fn dropping_during_app_server_termination_grace_kills_the_group() {
let fixture = crate::test_support::GracePeriodFixture::new("app-server-grace-drop");
let codex = fixture.configure(fake("ignores-eof")).build().unwrap();
let server = AppServer::builder(&codex).start().await.unwrap();
fixture.assert_drop_during_grace(server.terminate()).await;
}
#[tokio::test]
async fn dropping_the_client_kills_the_process_group() {
let pid_file = PidFile::new("app-server-drop");
let codex = fake("spawns-child")
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.build()
.unwrap();
let server = AppServer::builder(&codex).start().await.unwrap();
let (parent, child) = read_pids(&pid_file).await;
drop(server);
assert!(
wait_until_gone(parent).await,
"the server ({parent}) survived"
);
assert!(
wait_until_gone(child).await,
"the server's subprocess ({child}) survived the drop"
);
assert!(!term_marker(&pid_file).exists());
}
#[tokio::test]
async fn shutdown_lets_a_server_that_exits_on_eof_finish_by_itself() {
let codex = fake("turn")
.termination_grace(Duration::from_secs(4))
.build()
.unwrap();
let server = AppServer::builder(&codex).start().await.unwrap();
let pid = server.pid().expect("running");
let started_at = std::time::Instant::now();
server.shutdown().await.unwrap();
assert!(
started_at.elapsed() < Duration::from_secs(3),
"shutdown waited out the grace instead of seeing the exit"
);
assert!(wait_until_gone(pid).await);
}
#[tokio::test]
async fn shutdown_falls_back_to_termination_when_the_server_ignores_eof() {
let pid_file = PidFile::new("app-server-ignores-eof");
let codex = fake("ignores-eof")
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.termination_grace(Duration::from_secs(1))
.build()
.unwrap();
let server = AppServer::builder(&codex).start().await.unwrap();
let (parent, child) = read_pids(&pid_file).await;
server.shutdown().await.unwrap();
let marker = term_marker(&pid_file);
assert!(
marker.exists(),
"shutdown killed the server without asking it to stop"
);
let _ = std::fs::remove_file(marker);
assert!(
wait_until_gone(parent).await,
"the server ({parent}) survived"
);
assert!(
wait_until_gone(child).await,
"the server's subprocess ({child}) survived shutdown"
);
}
#[tokio::test]
async fn requests_after_shutdown_fail_on_a_surviving_handle() {
let server = started("turn").await;
let handle = server.handle();
server.shutdown().await.unwrap();
let error = handle.request("thread/start", json!({})).await.unwrap_err();
assert!(
matches!(error, Error::AppServerProtocol { .. }),
"{error:?}"
);
assert!(handle.notify("initialized", Value::Null).is_err());
}
fn term_marker(pid_file: &PidFile) -> std::path::PathBuf {
let mut path = pid_file.path().as_os_str().to_owned();
path.push(".term");
std::path::PathBuf::from(path)
}
async fn read_pids(pid_file: &PidFile) -> (u32, u32) {
for _ in 0..1000 {
if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
let field = |key: &str| {
contents
.lines()
.find_map(|line| line.strip_prefix(key))
.and_then(|value| value.trim().parse::<u32>().ok())
};
if let (Some(parent), Some(child)) = (field("parent="), field("child=")) {
return (parent, child);
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the fake server never recorded its pids");
}
#[tokio::test]
async fn a_request_that_times_out_leaves_the_session_usable_and_no_entry_behind() {
let server = started("mute-after-init").await;
let mut handle = server.handle();
handle.timeout = Some(Duration::from_millis(150));
for _ in 0..2 {
let error = handle.request("thread/start", json!({})).await.unwrap_err();
assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
}
assert!(
locked(&handle.shared.state).pending.is_empty(),
"a timed-out request left its slot behind"
);
assert!(handle.notify("initialized", Value::Null).is_ok());
server.terminate().await.unwrap();
}
#[tokio::test]
async fn dropping_a_request_future_does_not_corrupt_the_wire() {
let log = std::env::temp_dir().join(format!(
"codex-wrapper-{}-app-server-dropped.log",
std::process::id()
));
let _ = std::fs::remove_file(&log);
let codex = fake("turn")
.env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
.build()
.unwrap();
let server = AppServer::builder(&codex).start().await.unwrap();
for _ in 0..20 {
let request = server.request("thread/start", json!({ "ephemeral": true }));
let mut request = std::pin::pin!(request);
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
assert!(request.as_mut().poll(&mut context).is_pending());
}
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
assert!(!thread.id.is_empty());
server.shutdown().await.unwrap();
let text = std::fs::read_to_string(&log).unwrap();
let _ = std::fs::remove_file(&log);
let mut count = 0;
for line in text.lines() {
serde_json::from_str::<Value>(line).expect("the server received a partial line");
count += 1;
}
assert_eq!(count, 23, "{text}");
}
#[tokio::test]
async fn next_message_loses_nothing_when_its_future_is_dropped() {
let mut server = started("turn").await;
let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
server
.turn_start(TurnStartParams::text(&thread.id, "go"))
.await
.unwrap();
let mut seen = Vec::new();
let mut finished = false;
let deadline = std::time::Instant::now() + Duration::from_secs(20);
while std::time::Instant::now() < deadline {
if let Ok(next) =
tokio::time::timeout(Duration::from_micros(200), server.next_message()).await
{
let message = next.unwrap().expect("the stream ended early");
if let ServerMessage::Notification(n) = &message {
finished |= n.turn_completed().is_some();
}
seen.push(message);
}
if finished {
break;
}
}
assert!(
finished,
"never saw the turn complete: {:?}",
methods(&seen)
);
let methods = methods(&seen);
let expected = [
"remoteControl/status/changed",
"thread/started",
"thread/status/changed",
"turn/started",
"item/started",
"item/agentMessage/delta",
"item/completed",
"thread/tokenUsage/updated",
"thread/status/changed",
"turn/completed",
];
assert_eq!(methods, expected);
server.shutdown().await.unwrap();
}
#[test]
fn turn_final_message_takes_the_last_final_answer_and_ignores_commentary() {
let turn: Turn = serde_json::from_value(json!({
"id": "t",
"status": "completed",
"items": [
{ "type": "agentMessage", "text": "working", "phase": "commentary" },
{ "type": "commandExecution", "text": "not a message", "phase": "final_answer" },
{ "type": "agentMessage", "text": "first", "phase": "final_answer" },
{ "type": "agentMessage", "text": "last", "phase": "final_answer" }
]
}))
.unwrap();
assert_eq!(turn.final_message(), Some("last"));
}
#[test]
fn agent_messages_are_decoded_from_item_completed_only() {
let message = |phase: Option<&str>| Notification {
method: "item/completed".into(),
params: json!({
"item": {
"type": "agentMessage",
"id": "m",
"text": "DONE STEERED",
"phase": phase,
},
"threadId": "th",
"turnId": "tu",
}),
};
let answer = message(Some("final_answer")).agent_message().unwrap();
assert_eq!(answer.text, "DONE STEERED");
assert_eq!(
(answer.thread_id.as_str(), answer.turn_id.as_str()),
("th", "tu")
);
assert!(answer.is_final_answer());
assert!(
!message(Some("commentary"))
.agent_message()
.unwrap()
.is_final_answer()
);
assert!(!message(None).agent_message().unwrap().is_final_answer());
let mut command = message(None);
command.params["item"]["type"] = json!("commandExecution");
assert!(command.agent_message().is_none());
let mut delta = message(None);
delta.method = "item/agentMessage/delta".into();
assert!(delta.agent_message().is_none());
}
#[test]
fn an_unknown_turn_status_is_kept_apart_from_the_known_ones() {
let turn: Turn =
serde_json::from_value(json!({ "id": "t", "status": "someFutureStatus" })).unwrap();
assert_eq!(turn.status, TurnStatus::Unknown);
}
#[test]
fn only_a_well_formed_turn_completed_notification_decodes() {
let other = Notification {
method: "turn/started".into(),
params: json!({}),
};
assert!(other.turn_completed().is_none());
let malformed = Notification {
method: "turn/completed".into(),
params: json!({ "threadId": "x" }),
};
assert!(malformed.turn_completed().is_none());
}
#[test]
fn request_ids_round_trip_as_numbers_and_strings() {
assert_eq!(serde_json::to_string(&RequestId::Number(7)).unwrap(), "7");
assert_eq!(
serde_json::to_string(&RequestId::String("a".into())).unwrap(),
"\"a\""
);
assert_eq!(
serde_json::from_str::<RequestId>("0").unwrap(),
RequestId::Number(0)
);
assert_eq!(
serde_json::from_str::<RequestId>("\"x\"").unwrap(),
RequestId::String("x".into())
);
}
#[test]
fn reply_lines_echo_the_servers_id() {
let line = reply_line(
&RequestId::Number(0),
"result",
&json!({ "decision": "decline" }),
)
.unwrap();
assert_eq!(
String::from_utf8(line).unwrap(),
"{\"id\":0,\"result\":{\"decision\":\"decline\"}}\n"
);
let line = reply_line(
&RequestId::String("r-1".into()),
"error",
&json!({ "code": -32601, "message": "no" }),
)
.unwrap();
assert_eq!(
String::from_utf8(line).unwrap(),
"{\"id\":\"r-1\",\"error\":{\"code\":-32601,\"message\":\"no\"}}\n"
);
}
#[test]
fn colour_codes_are_removed_from_server_logs() {
let raw = "\u{1b}[2m2026-09-24T04:17:33Z\u{1b}[0m \u{1b}[31mERROR\u{1b}[0m worker quit";
assert_eq!(strip_ansi(raw), "2026-09-24T04:17:33Z ERROR worker quit");
}
#[test]
fn a_line_that_is_not_a_message_is_ignored_and_bad_json_is_fatal() {
let (events, mut received) = mpsc::unbounded_channel();
let shared = Shared::new(events, None);
assert!(route(r#"{"unrelated":true}"#, &shared).is_ok());
assert!(
route(
r#"{"id":null,"error":{"code":-32600,"message":"x"}}"#,
&shared
)
.is_ok()
);
assert!(route(r#"{"id":99,"result":{}}"#, &shared).is_ok());
assert!(received.try_recv().is_err(), "nothing should be delivered");
assert!(route(r#"{"method":"a/b","params":{"k":1}}"#, &shared).is_ok());
assert!(matches!(
received.try_recv(),
Ok(Event::Message(ServerMessage::Notification(n))) if n.method == "a/b"
));
assert!(route(r#"{"method":"a/b","id":"s"}"#, &shared).is_ok());
assert!(matches!(
received.try_recv(),
Ok(Event::Message(ServerMessage::Request(r))) if r.id == RequestId::String("s".into())
));
assert!(matches!(
route(r#"{"method": oops"#, &shared),
Err(Closed::Broken(_))
));
}
}