Skip to main content

codex_wrapper/
app_server.rs

1//! A JSON-RPC client for `codex app-server`.
2//!
3//! `codex exec` takes one prompt per process and cannot change a turn that is
4//! already running. The app-server can: [`AppServerHandle::turn_steer`] adds
5//! input to the active turn and [`AppServerHandle::turn_interrupt`] stops it.
6//! [`AppServer`] runs the server over stdio and gives a caller its events as
7//! they arrive, plus a way to answer the requests the server sends back, such
8//! as approvals.
9//!
10//! The CLI marks `app-server` experimental, so this module is behind the
11//! `app-server` feature and wraps the transport, not the whole protocol. The
12//! four methods with typed helpers ([`thread_start`], [`turn_start`],
13//! [`turn_steer`], [`turn_interrupt`]) were exercised against a real server;
14//! [`request`] reaches any other method without a wrapper change.
15//!
16//! [`thread_start`]: AppServerHandle::thread_start
17//! [`turn_start`]: AppServerHandle::turn_start
18//! [`turn_steer`]: AppServerHandle::turn_steer
19//! [`turn_interrupt`]: AppServerHandle::turn_interrupt
20//! [`request`]: AppServerHandle::request
21//!
22//! # Example
23//!
24//! ```no_run
25//! use codex_wrapper::Codex;
26//! use codex_wrapper::app_server::{
27//!     AppServer, ServerMessage, ThreadStartParams, TurnStartParams, UserInput,
28//! };
29//!
30//! # async fn example() -> codex_wrapper::Result<()> {
31//! let codex = Codex::builder().build()?;
32//! let mut server = AppServer::builder(&codex).start().await?;
33//!
34//! let thread = server
35//!     .thread_start(ThreadStartParams::new().ephemeral(true))
36//!     .await?;
37//! let turn = server
38//!     .turn_start(TurnStartParams::text(&thread.id, "run `sleep 10`, then say DONE"))
39//!     .await?;
40//!
41//! // A handle can be cloned into another task, for example one that
42//! // serves a "steer" command while this task reads events.
43//! let handle = server.handle();
44//! handle
45//!     .turn_steer(&thread.id, &turn.id, vec![UserInput::text("also say STEERED")])
46//!     .await?;
47//!
48//! let mut answer = None;
49//! while let Some(message) = server.next_message().await? {
50//!     match message {
51//!         ServerMessage::Notification(notification) => {
52//!             if let Some(message) = notification.agent_message()
53//!                 && message.is_final_answer()
54//!             {
55//!                 answer = Some(message.text);
56//!             }
57//!             if let Some(done) = notification.turn_completed() {
58//!                 println!("{:?}: {answer:?}", done.turn.status);
59//!                 break;
60//!             }
61//!         }
62//!         ServerMessage::Request(request) => {
63//!             // An unanswered request stalls the turn.
64//!             server.respond_error(request.id, -32601, "not supported")?;
65//!         }
66//!         _ => {}
67//!     }
68//! }
69//! server.shutdown().await?;
70//! # Ok(())
71//! # }
72//! ```
73//!
74//! # Lifecycle and cancellation
75//!
76//! The server runs in its own process group (unless the client disables
77//! [`CodexBuilder::process_group`](crate::CodexBuilder::process_group)).
78//! That group does not include the shell commands a turn runs: the server
79//! starts each in a group of its own. So there are two ways to stop, and they
80//! differ in what happens to a command that is still running:
81//!
82//! - [`AppServer::shutdown`] closes the server's stdin and waits up to the
83//!   client's termination grace for it to exit. The server stops its running
84//!   commands and exits, in milliseconds when a turn is active. If it does
85//!   not exit in time, this falls back to [`AppServer::terminate`]. Prefer it.
86//! - [`AppServer::terminate`] has the settled contract of
87//!   [`stream_exec_cancellable`](crate::streaming::stream_exec_cancellable):
88//!   it asks the server's group to stop, waits through the grace period, kills
89//!   what is left, and reaps the child before returning. A command the server
90//!   started in its own group keeps running, as it does when `codex exec` is
91//!   cancelled; the caller has to find and stop it.
92//! - Dropping an [`AppServer`] kills the server's group without waiting, as
93//!   dropping a streaming future does. The same caveat applies.
94//!
95//! [`AppServerHandle::turn_interrupt`] ends the turn, not the command it is
96//! running.
97//! - A failure that leaves the stream unusable (the output limit, or a line
98//!   that starts with `{` but is not valid JSON) kills the child: on Unix as
99//!   soon as it is detected, elsewhere when [`AppServer::next_message`] returns
100//!   the error. The error also reaches any request still waiting.
101//!
102//! # Limits
103//!
104//! [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit) caps the
105//! total bytes read from stdout over the life of the session, as it does for
106//! streaming. [`CodexBuilder::timeout`](crate::CodexBuilder::timeout) applies
107//! to each request, including the handshake, and not to the session; without
108//! it a request waits until the server answers or exits. The server's stderr is
109//! drained continuously and the last 16 KiB is kept for error messages.
110//!
111//! Messages wait in an unbounded queue until [`AppServer::next_message`]
112//! returns them, so a caller that does not read them, or reads more slowly than
113//! the server writes, holds them in memory. `output_limit` bounds the total.
114//! Streaming deltas are most of the volume, and
115//! [`AppServerBuilder::opt_out_notification`] stops the server sending them.
116//!
117//! # Verified against codex-cli 0.149.0
118//!
119//! Each of these was read from a captured session, not inferred. Re-capture
120//! after a CLI upgrade and correct this block in the same change.
121//!
122//! - Messages are newline-delimited JSON with no `jsonrpc` field. A
123//!   notification may carry extra top-level fields (`emittedAtMs`).
124//! - A request before `initialize` gets `{"error":{"code":-32600,"message":
125//!   "Not initialized"},"id":N}`, a second `initialize` gets `Already
126//!   initialized`, and an unknown method gets code -32600 with the valid
127//!   method names in the message.
128//! - `initialize` takes `clientInfo` and optionally
129//!   `capabilities.optOutNotificationMethods`, which suppresses those
130//!   notifications for the connection. The client then sends an `initialized`
131//!   notification.
132//! - `thread/start` accepts `cwd`, `ephemeral`, `approvalPolicy`, `sandbox`,
133//!   and `model`. It answers with `{"thread":{"id":...},"model":...}` and
134//!   sends a `thread/started` notification.
135//! - `turn/start` accepts `threadId`, `input`, `model`, `effort`,
136//!   `outputSchema`, `cwd`, and `approvalPolicy`. It answers with
137//!   `{"turn":{"id":...,"status":"inProgress"}}`. With `outputSchema` the
138//!   captured final message was JSON that followed the schema.
139//! - A turn ends with a `turn/completed` notification whose `turn.status` is
140//!   `completed` or `interrupted`. Whether `turn.items` holds the final
141//!   answer depends on the CLI: 0.149.0 includes it (`itemsView` `summary`),
142//!   0.145.0 always sends `items: []` (`notLoaded`). Both send an
143//!   `item/completed` notification for the final `agentMessage` (`phase`
144//!   `final_answer`) before `turn/completed`, so that is what
145//!   [`Notification::agent_message`] decodes.
146//! - `turn/steer` answers `{"turnId":...}` at once. The text reaches the model
147//!   at the next item boundary, not immediately. With no active turn it fails
148//!   with `no active turn to steer`; with one, but a different
149//!   `expectedTurnId`, with ``expected active turn id `X` but found `Y` ``.
150//! - `turn/interrupt` answers `{}`. With no active turn it fails with `no
151//!   active turn to interrupt`; with a different `turnId`, with `expected
152//!   active turn id X but found Y`. It ends the turn and leaves a running
153//!   shell command alone.
154//! - The server runs each shell command in a process group of its own, with
155//!   the server as its parent. With a command running, closing stdin made the
156//!   server exit 0 and took the command with it; SIGTERM to the server, SIGTERM
157//!   to its group, and SIGKILL to its group each left the command running.
158//! - When the approval policy asks, the server sends a request
159//!   (`item/commandExecution/requestApproval`, numeric id starting at 0) and
160//!   the turn waits. The reply is `{"id":0,"result":{"decision":"decline"}}`,
161//!   after which the server sends a `serverRequest/resolved` notification.
162//! - The server logs to stderr, in colour, including MCP startup errors.
163//! - Closing stdin ends the server with status 0. That took 5 seconds in one
164//!   capture where no thread had been started, and milliseconds after a turn.
165//! - A startup failure (an unknown `-c` key under `--strict-config`) writes one
166//!   line to stderr and exits 1.
167//!
168//! # Assumed, not verified
169//!
170//! - Server-initiated requests may use string ids; [`RequestId`] accepts both.
171//! - A JSON object with neither `method` nor a matching response `id` is
172//!   logged and ignored. A line that does not start with `{` is ignored, as
173//!   [`streaming`](crate::streaming) ignores it. A line that starts with `{`
174//!   and is not valid JSON ends the session.
175
176use std::collections::HashMap;
177use std::ops::Deref;
178use std::path::PathBuf;
179use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
180use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
181use std::time::Duration;
182
183use serde::ser::SerializeMap;
184use serde::{Deserialize, Serialize, Serializer};
185use serde_json::{Map, Value, json};
186use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
187use tokio::process::{Child, ChildStderr, ChildStdout, Command};
188use tokio::sync::{Notify, mpsc, oneshot};
189use tracing::{Instrument, debug, warn};
190
191use crate::Codex;
192use crate::error::{Error, OutputStream, Result};
193use crate::exec::{GroupKillGuard, SpanOutcome};
194use crate::types::{ApprovalPolicy, SandboxMode};
195
196/// How much of the server's stderr is kept for error messages.
197const STDERR_TAIL_BYTES: usize = 16 * 1024;
198
199/// How long a server that failed during the handshake is given to report why
200/// it exited before it is terminated.
201const STARTUP_EXIT_WAIT: Duration = Duration::from_secs(2);
202
203/// How long to wait for the stderr reader to finish once the child has exited,
204/// so the last lines it wrote make it into an error message.
205const STDERR_SETTLE: Duration = Duration::from_millis(500);
206
207/// A JSON-RPC request id.
208///
209/// The server has been seen to send numbers. The protocol allows strings, so
210/// both are accepted, and a reply echoes whichever the server used.
211#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
212#[serde(untagged)]
213pub enum RequestId {
214    /// A numeric id.
215    Number(i64),
216    /// A string id.
217    String(String),
218}
219
220impl std::fmt::Display for RequestId {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        match self {
223            Self::Number(n) => write!(f, "{n}"),
224            Self::String(s) => f.write_str(s),
225        }
226    }
227}
228
229/// A message the server sent without being asked.
230///
231/// `params` is `null` when the server sent none.
232#[derive(Debug, Clone, PartialEq)]
233pub struct Notification {
234    /// The method name, for example `turn/completed`.
235    pub method: String,
236    /// The method's parameters.
237    pub params: Value,
238}
239
240impl Notification {
241    /// Decode an `item/completed` notification for an agent message, or `None`
242    /// for anything else.
243    ///
244    /// A turn may produce several: progress remarks (`commentary`) and then
245    /// the answer (`final_answer`). Unlike `turn/completed`, this notification
246    /// carries the text on every CLI version tested.
247    #[must_use]
248    pub fn agent_message(&self) -> Option<AgentMessage> {
249        if self.method != "item/completed" {
250            return None;
251        }
252        let item = self.params.get("item")?;
253        if item.get("type")?.as_str()? != "agentMessage" {
254            return None;
255        }
256        Some(AgentMessage {
257            thread_id: self.params.get("threadId")?.as_str()?.to_string(),
258            turn_id: self.params.get("turnId")?.as_str()?.to_string(),
259            text: item.get("text")?.as_str()?.to_string(),
260            phase: item
261                .get("phase")
262                .and_then(Value::as_str)
263                .map(str::to_string),
264        })
265    }
266
267    /// Decode a `turn/completed` notification, or `None` for any other method
268    /// or a payload that does not have the verified shape.
269    #[must_use]
270    pub fn turn_completed(&self) -> Option<TurnCompleted> {
271        if self.method != "turn/completed" {
272            return None;
273        }
274        serde_json::from_value(self.params.clone()).ok()
275    }
276}
277
278/// A finished message from the model, decoded from an `item/completed`
279/// notification by [`Notification::agent_message`].
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct AgentMessage {
282    /// The thread the message belongs to.
283    pub thread_id: String,
284    /// The turn the message belongs to.
285    pub turn_id: String,
286    /// The message text.
287    pub text: String,
288    /// `commentary` for a progress remark, `final_answer` for the answer.
289    /// `None` if the server sent no phase.
290    pub phase: Option<String>,
291}
292
293impl AgentMessage {
294    /// Whether this is the turn's answer rather than a progress remark.
295    #[must_use]
296    pub fn is_final_answer(&self) -> bool {
297        self.phase.as_deref() == Some("final_answer")
298    }
299}
300
301/// A request the server sent and is waiting on, such as an approval.
302///
303/// Answer it with [`AppServerHandle::respond`] or
304/// [`AppServerHandle::respond_error`]. The turn that raised it makes no
305/// progress until then.
306#[derive(Debug, Clone, PartialEq)]
307pub struct ServerRequest {
308    /// The id to echo in the reply.
309    pub id: RequestId,
310    /// The method name, for example `item/commandExecution/requestApproval`.
311    pub method: String,
312    /// The method's parameters.
313    pub params: Value,
314}
315
316/// One message from the server that is not the answer to a request.
317#[derive(Debug, Clone, PartialEq)]
318#[non_exhaustive]
319pub enum ServerMessage {
320    /// An event, such as `turn/started` or `item/completed`.
321    Notification(Notification),
322    /// A request that needs a reply.
323    Request(ServerRequest),
324}
325
326/// How a turn is going, from its `status` field.
327///
328/// `inProgress`, `completed`, and `interrupted` were captured. `failed` comes
329/// from the protocol schema.
330#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
331#[serde(rename_all = "camelCase")]
332#[non_exhaustive]
333pub enum TurnStatus {
334    /// The turn is running.
335    InProgress,
336    /// The turn finished normally.
337    Completed,
338    /// The turn was stopped by `turn/interrupt`.
339    Interrupted,
340    /// The turn failed; see [`Turn::error`].
341    Failed,
342    /// A status this version of the wrapper does not know.
343    #[serde(other)]
344    Unknown,
345}
346
347/// A turn, as reported in `turn/start` responses and `turn/completed`
348/// notifications.
349#[derive(Debug, Clone, PartialEq, Deserialize)]
350#[serde(rename_all = "camelCase")]
351pub struct Turn {
352    /// The turn's id, needed for [`AppServerHandle::turn_steer`] and
353    /// [`AppServerHandle::turn_interrupt`].
354    pub id: String,
355    /// The turn's status.
356    pub status: TurnStatus,
357    /// The items the payload includes. Empty for a turn that was interrupted.
358    #[serde(default)]
359    pub items: Vec<Value>,
360    /// Why the turn failed. Only set when the status is
361    /// [`TurnStatus::Failed`].
362    #[serde(default)]
363    pub error: Option<Value>,
364    /// How long the turn ran, in milliseconds, once it has ended.
365    #[serde(default)]
366    pub duration_ms: Option<i64>,
367}
368
369impl Turn {
370    /// The text of the turn's final answer: the last `agentMessage` item in
371    /// [`items`](Self::items) whose `phase` is `final_answer`.
372    ///
373    /// Only newer servers put the answer in `turn/completed` (0.149.0 does,
374    /// 0.145.0 sends no items), and an interrupted turn never has one. To get
375    /// the answer from any version, keep the last
376    /// [`Notification::agent_message`] whose
377    /// [`is_final_answer`](AgentMessage::is_final_answer) is true.
378    #[must_use]
379    pub fn final_message(&self) -> Option<&str> {
380        self.items
381            .iter()
382            .rev()
383            .filter(|item| {
384                item.get("type").and_then(Value::as_str) == Some("agentMessage")
385                    && item.get("phase").and_then(Value::as_str) == Some("final_answer")
386            })
387            .find_map(|item| item.get("text").and_then(Value::as_str))
388    }
389}
390
391/// The payload of a `turn/completed` notification.
392#[derive(Debug, Clone, PartialEq, Deserialize)]
393#[serde(rename_all = "camelCase")]
394pub struct TurnCompleted {
395    /// The thread the turn belongs to.
396    pub thread_id: String,
397    /// The turn, in its final state.
398    pub turn: Turn,
399}
400
401/// A thread, as returned by `thread/start`.
402#[derive(Debug, Clone, PartialEq)]
403pub struct Thread {
404    /// The thread id, needed to start turns on it.
405    pub id: String,
406    /// The model the thread will use, when the server reports one.
407    pub model: Option<String>,
408    /// The complete response, for fields this type does not name.
409    pub raw: Value,
410}
411
412/// What the server reported about itself in the `initialize` response.
413#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
414#[serde(rename_all = "camelCase", default)]
415pub struct ServerInfo {
416    /// The server's user agent string, which includes the CLI version.
417    pub user_agent: String,
418    /// The Codex home directory the server is using.
419    pub codex_home: Option<String>,
420    /// `unix` or `windows`.
421    pub platform_family: Option<String>,
422    /// The operating system name.
423    pub platform_os: Option<String>,
424}
425
426/// One piece of user input for a turn.
427#[derive(Debug, Clone, PartialEq)]
428pub enum UserInput {
429    /// Plain text.
430    Text(String),
431    /// Any other input item, sent as given. See the protocol schema for the
432    /// shapes the server accepts.
433    Raw(Value),
434}
435
436impl UserInput {
437    /// A text input.
438    #[must_use]
439    pub fn text(text: impl Into<String>) -> Self {
440        Self::Text(text.into())
441    }
442}
443
444impl Serialize for UserInput {
445    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
446        match self {
447            Self::Text(text) => {
448                let mut map = serializer.serialize_map(Some(3))?;
449                map.serialize_entry("type", "text")?;
450                map.serialize_entry("text", text)?;
451                // Sent as the captured client sent it. The schema gives the
452                // field a default, but a server that requires it is not ruled
453                // out by that.
454                map.serialize_entry("text_elements", &Vec::<Value>::new())?;
455                map.end()
456            }
457            Self::Raw(value) => value.serialize(serializer),
458        }
459    }
460}
461
462/// Parameters for `thread/start`.
463///
464/// Every field is optional. Fields this type does not name can be set with
465/// [`param`](Self::param).
466#[derive(Debug, Clone, Default, Serialize)]
467#[serde(rename_all = "camelCase")]
468pub struct ThreadStartParams {
469    #[serde(skip_serializing_if = "Option::is_none")]
470    cwd: Option<PathBuf>,
471    #[serde(skip_serializing_if = "Option::is_none")]
472    model: Option<String>,
473    #[serde(skip_serializing_if = "Option::is_none")]
474    approval_policy: Option<ApprovalPolicy>,
475    #[serde(skip_serializing_if = "Option::is_none")]
476    sandbox: Option<SandboxMode>,
477    #[serde(skip_serializing_if = "Option::is_none")]
478    ephemeral: Option<bool>,
479    #[serde(flatten)]
480    extra: Map<String, Value>,
481}
482
483impl ThreadStartParams {
484    /// Parameters with nothing set, which starts a thread with the server's
485    /// defaults.
486    #[must_use]
487    pub fn new() -> Self {
488        Self::default()
489    }
490
491    /// The thread's working directory.
492    #[must_use]
493    pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
494        self.cwd = Some(dir.into());
495        self
496    }
497
498    /// The model the thread uses.
499    #[must_use]
500    pub fn model(mut self, model: impl Into<String>) -> Self {
501        self.model = Some(model.into());
502        self
503    }
504
505    /// When the server asks before running a command or applying a change.
506    #[must_use]
507    pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
508        self.approval_policy = Some(policy);
509        self
510    }
511
512    /// The sandbox for commands the model runs.
513    #[must_use]
514    pub fn sandbox(mut self, mode: SandboxMode) -> Self {
515        self.sandbox = Some(mode);
516        self
517    }
518
519    /// Whether the thread is kept out of the session history.
520    #[must_use]
521    pub fn ephemeral(mut self, ephemeral: bool) -> Self {
522        self.ephemeral = Some(ephemeral);
523        self
524    }
525
526    /// Set a parameter this type has no method for, using the protocol's
527    /// camelCase name. It is sent as given and not checked.
528    #[must_use]
529    pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
530        self.extra.insert(name.into(), value);
531        self
532    }
533}
534
535/// Parameters for `turn/start`.
536///
537/// The thread and the input are required. The other fields override the
538/// thread's settings for this turn and, per the protocol, later ones. Fields
539/// this type does not name can be set with [`param`](Self::param).
540#[derive(Debug, Clone, Serialize)]
541#[serde(rename_all = "camelCase")]
542pub struct TurnStartParams {
543    thread_id: String,
544    input: Vec<UserInput>,
545    #[serde(skip_serializing_if = "Option::is_none")]
546    model: Option<String>,
547    #[serde(skip_serializing_if = "Option::is_none")]
548    effort: Option<String>,
549    #[serde(skip_serializing_if = "Option::is_none")]
550    output_schema: Option<Value>,
551    #[serde(skip_serializing_if = "Option::is_none")]
552    cwd: Option<PathBuf>,
553    #[serde(skip_serializing_if = "Option::is_none")]
554    approval_policy: Option<ApprovalPolicy>,
555    #[serde(flatten)]
556    extra: Map<String, Value>,
557}
558
559impl TurnStartParams {
560    /// A turn on `thread_id` with the given input.
561    #[must_use]
562    pub fn new(thread_id: impl Into<String>, input: Vec<UserInput>) -> Self {
563        Self {
564            thread_id: thread_id.into(),
565            input,
566            model: None,
567            effort: None,
568            output_schema: None,
569            cwd: None,
570            approval_policy: None,
571            extra: Map::new(),
572        }
573    }
574
575    /// A turn on `thread_id` whose input is one text prompt.
576    #[must_use]
577    pub fn text(thread_id: impl Into<String>, prompt: impl Into<String>) -> Self {
578        Self::new(thread_id, vec![UserInput::text(prompt)])
579    }
580
581    /// The model for this turn.
582    #[must_use]
583    pub fn model(mut self, model: impl Into<String>) -> Self {
584        self.model = Some(model.into());
585        self
586    }
587
588    /// The reasoning effort for this turn. The valid values depend on the
589    /// model, so this is a string.
590    #[must_use]
591    pub fn effort(mut self, effort: impl Into<String>) -> Self {
592        self.effort = Some(effort.into());
593        self
594    }
595
596    /// A JSON Schema the final message must follow.
597    #[must_use]
598    pub fn output_schema(mut self, schema: Value) -> Self {
599        self.output_schema = Some(schema);
600        self
601    }
602
603    /// The working directory for this turn.
604    #[must_use]
605    pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
606        self.cwd = Some(dir.into());
607        self
608    }
609
610    /// When the server asks before running a command or applying a change.
611    #[must_use]
612    pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
613        self.approval_policy = Some(policy);
614        self
615    }
616
617    /// Set a parameter this type has no method for, using the protocol's
618    /// camelCase name. It is sent as given and not checked.
619    #[must_use]
620    pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
621        self.extra.insert(name.into(), value);
622        self
623    }
624}
625
626/// A JSON-RPC error the server returned for a request.
627struct RpcFailure {
628    code: i64,
629    message: String,
630    data: Option<Value>,
631}
632
633/// Why the connection to the server ended.
634#[derive(Debug, Clone)]
635enum Closed {
636    /// The server closed its stdout: it exited, or was stopped.
637    Eof,
638    /// Stdout passed the byte ceiling.
639    OutputLimit { limit_bytes: usize },
640    /// The stream cannot be trusted any more, or could not be read or written.
641    Broken(String),
642    /// The client ended the session.
643    Terminated,
644}
645
646/// What a waiting request gets back.
647enum Reply {
648    Result(Value),
649    Rpc(RpcFailure),
650    /// A response with neither `result` nor `error`.
651    Malformed,
652    Closed(Closed),
653}
654
655/// What the reader hands to [`AppServer::next_message`].
656enum Event {
657    Message(ServerMessage),
658    Closed(Closed),
659}
660
661/// What the writer task is asked to do.
662enum Outgoing {
663    Line(Vec<u8>),
664    /// Stop writing and drop stdin, which the server sees as end of input.
665    Close,
666}
667
668struct State {
669    pending: HashMap<i64, oneshot::Sender<Reply>>,
670    closed: Option<Closed>,
671}
672
673/// State shared by the handles, the owner, and the three I/O tasks.
674struct Shared {
675    state: Mutex<State>,
676    next_id: AtomicI64,
677    stderr_tail: Mutex<Vec<u8>>,
678    /// Set, and `stderr_finished` notified, when the stderr reader has seen
679    /// end of file, so its last lines are in `stderr_tail`.
680    stderr_done: AtomicBool,
681    stderr_finished: Notify,
682    /// What the reader task may kill when the stream breaks. Taken away, under
683    /// this lock, before the client reaps the child, so the reader can never
684    /// signal a pid that has been released.
685    kill: Mutex<Option<KillTarget>>,
686    events: mpsc::UnboundedSender<Event>,
687}
688
689fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
690    // Nothing here panics while holding a lock, so a poisoned mutex holds
691    // consistent data. Recovering keeps one panicking task from taking the
692    // whole session down with it.
693    mutex.lock().unwrap_or_else(PoisonError::into_inner)
694}
695
696impl Shared {
697    /// End the session: fail every waiting request and tell the reader side.
698    /// The first reason wins.
699    fn fail(&self, reason: Closed) {
700        let pending = {
701            let mut state = locked(&self.state);
702            if state.closed.is_some() {
703                return;
704            }
705            state.closed = Some(reason.clone());
706            std::mem::take(&mut state.pending)
707        };
708        for (_, waiter) in pending {
709            let _ = waiter.send(Reply::Closed(reason.clone()));
710        }
711        let _ = self.events.send(Event::Closed(reason));
712    }
713
714    fn new(events: mpsc::UnboundedSender<Event>, kill: Option<KillTarget>) -> Self {
715        Self {
716            state: Mutex::new(State {
717                pending: HashMap::new(),
718                closed: None,
719            }),
720            next_id: AtomicI64::new(0),
721            stderr_tail: Mutex::new(Vec::new()),
722            stderr_done: AtomicBool::new(false),
723            stderr_finished: Notify::new(),
724            kill: Mutex::new(kill),
725            events,
726        }
727    }
728
729    /// Kill the server, if the reader still has the authority to. Called when
730    /// the stream is unusable and nothing will read what the server writes.
731    fn fire_kill(&self) {
732        // Held across the signal, so `revoke_kill` cannot return while one is
733        // being sent.
734        if let Some(target) = *locked(&self.kill) {
735            target.signal();
736        }
737    }
738
739    /// Take away the reader's authority to kill. Must be called before the
740    /// child is reaped: from then on the pid may belong to another process.
741    fn revoke_kill(&self) {
742        *locked(&self.kill) = None;
743    }
744
745    /// Wait, for a short while, until the stderr reader has read everything
746    /// the server wrote. Stdout and stderr close together when the server
747    /// exits, but the two readers are separate tasks, so an error built from
748    /// the tail straight away could miss the last lines.
749    async fn stderr_settled(&self) {
750        let wait = async {
751            loop {
752                let notified = self.stderr_finished.notified();
753                if self.stderr_done.load(Ordering::Acquire) {
754                    return;
755                }
756                notified.await;
757            }
758        };
759        let _ = tokio::time::timeout(STDERR_SETTLE, wait).await;
760    }
761
762    /// The last lines the server wrote to stderr, without colour codes.
763    fn stderr_summary(&self) -> String {
764        let tail = locked(&self.stderr_tail);
765        let text = strip_ansi(&String::from_utf8_lossy(&tail));
766        let lines: Vec<&str> = text
767            .lines()
768            .map(str::trim)
769            .filter(|line| !line.is_empty())
770            .collect();
771        let start = lines.len().saturating_sub(5);
772        lines[start..].join("\n")
773    }
774
775    fn error_for(&self, reason: &Closed, method: Option<&str>) -> Error {
776        let protocol = |message: String| Error::AppServerProtocol { message };
777        match reason {
778            Closed::OutputLimit { limit_bytes } => Error::OutputLimitExceeded {
779                stream: OutputStream::Stdout,
780                limit_bytes: *limit_bytes,
781            },
782            Closed::Terminated => protocol("the app-server session was ended by the client".into()),
783            Closed::Broken(message) => protocol(message.clone()),
784            Closed::Eof => {
785                let stderr = self.stderr_summary();
786                let while_waiting =
787                    method.map_or_else(String::new, |m| format!(" before answering `{m}`"));
788                if stderr.is_empty() {
789                    protocol(format!("codex app-server closed its output{while_waiting}"))
790                } else {
791                    protocol(format!(
792                        "codex app-server closed its output{while_waiting}; stderr: {stderr}"
793                    ))
794                }
795            }
796        }
797    }
798}
799
800/// Remove ANSI colour sequences (`ESC [ ... letter`) from server log lines.
801fn strip_ansi(text: &str) -> String {
802    let mut out = String::with_capacity(text.len());
803    let mut chars = text.chars().peekable();
804    while let Some(c) = chars.next() {
805        if c == '\u{1b}' && chars.peek() == Some(&'[') {
806            chars.next();
807            for c in chars.by_ref() {
808                if c.is_ascii_alphabetic() {
809                    break;
810                }
811            }
812        } else {
813            out.push(c);
814        }
815    }
816    out
817}
818
819/// Removes a waiting request's entry when the request future is dropped, so a
820/// cancelled request does not leave its slot behind.
821struct PendingSlot<'a> {
822    shared: &'a Shared,
823    id: i64,
824}
825
826impl Drop for PendingSlot<'_> {
827    fn drop(&mut self) {
828        locked(&self.shared.state).pending.remove(&self.id);
829    }
830}
831
832fn json_error(context: &str, source: serde_json::Error) -> Error {
833    Error::Json {
834        message: format!("{context}: {source}"),
835        source,
836    }
837}
838
839fn request_line(id: i64, method: &str, params: &Value) -> Result<Vec<u8>> {
840    let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
841    let mut line = format!("{{\"id\":{id},\"method\":{method}");
842    if !params.is_null() {
843        let params = serde_json::to_string(params).map_err(|e| json_error("request params", e))?;
844        line.push_str(",\"params\":");
845        line.push_str(&params);
846    }
847    line.push_str("}\n");
848    Ok(line.into_bytes())
849}
850
851fn notification_line(method: &str, params: &Value) -> Result<Vec<u8>> {
852    let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
853    let mut line = format!("{{\"method\":{method}");
854    if !params.is_null() {
855        let params =
856            serde_json::to_string(params).map_err(|e| json_error("notification params", e))?;
857        line.push_str(",\"params\":");
858        line.push_str(&params);
859    }
860    line.push_str("}\n");
861    Ok(line.into_bytes())
862}
863
864fn reply_line(id: &RequestId, body_key: &str, body: &Value) -> Result<Vec<u8>> {
865    let id = serde_json::to_string(id).map_err(|e| json_error("request id", e))?;
866    let body = serde_json::to_string(body).map_err(|e| json_error("reply body", e))?;
867    Ok(format!("{{\"id\":{id},\"{body_key}\":{body}}}\n").into_bytes())
868}
869
870/// A cloneable handle for sending to the server.
871///
872/// It can send requests and answer the server's, but not read events: that
873/// stays with the [`AppServer`], so a task can steer or interrupt a turn while
874/// another reads its notifications. Every method fails once the session has
875/// ended.
876#[derive(Clone)]
877pub struct AppServerHandle {
878    shared: Arc<Shared>,
879    writer: mpsc::UnboundedSender<Outgoing>,
880    timeout: Option<Duration>,
881}
882
883impl std::fmt::Debug for AppServerHandle {
884    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
885        f.debug_struct("AppServerHandle")
886            .field("timeout", &self.timeout)
887            .finish_non_exhaustive()
888    }
889}
890
891impl AppServerHandle {
892    fn closed_error(&self, method: Option<&str>) -> Error {
893        let reason = locked(&self.shared.state).closed.clone();
894        match reason {
895            Some(reason) => self.shared.error_for(&reason, method),
896            None => Error::AppServerProtocol {
897                message: "codex app-server is no longer accepting messages (its stdin is closed)"
898                    .into(),
899            },
900        }
901    }
902
903    fn enqueue(&self, line: Vec<u8>, method: Option<&str>) -> Result<()> {
904        if let Some(reason) = &locked(&self.shared.state).closed {
905            return Err(self.shared.error_for(reason, method));
906        }
907        self.writer
908            .send(Outgoing::Line(line))
909            .map_err(|_| self.closed_error(method))
910    }
911
912    /// Send a request and wait for its answer, returning the `result` value.
913    ///
914    /// Requests may run concurrently; each answer is matched by id. A JSON-RPC
915    /// error from the server is [`Error::AppServerRpc`]. The client's
916    /// [`timeout`](crate::CodexBuilder::timeout), when set, bounds the wait
917    /// and yields [`Error::Timeout`]. Pass [`Value::Null`] for no parameters.
918    ///
919    /// # Errors
920    ///
921    /// Fails if the server rejects the request, the wait times out, or the
922    /// session ends first.
923    pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
924        let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
925        let line = request_line(id, method, &params)?;
926        let (waiter, answer) = oneshot::channel();
927        {
928            let mut state = locked(&self.shared.state);
929            if let Some(reason) = &state.closed {
930                return Err(self.shared.error_for(reason, Some(method)));
931            }
932            state.pending.insert(id, waiter);
933        }
934        let _slot = PendingSlot {
935            shared: &self.shared,
936            id,
937        };
938        self.writer
939            .send(Outgoing::Line(line))
940            .map_err(|_| self.closed_error(Some(method)))?;
941
942        let reply = match self.timeout {
943            Some(limit) => {
944                tokio::time::timeout(limit, answer)
945                    .await
946                    .map_err(|_| Error::Timeout {
947                        timeout_seconds: limit.as_secs(),
948                    })?
949            }
950            None => answer.await,
951        };
952        match reply {
953            Ok(Reply::Result(result)) => Ok(result),
954            Ok(Reply::Rpc(failure)) => Err(Error::AppServerRpc {
955                method: method.to_string(),
956                code: failure.code,
957                message: failure.message,
958                data: failure.data,
959            }),
960            Ok(Reply::Malformed) => Err(Error::AppServerProtocol {
961                message: format!(
962                    "codex app-server answered `{method}` with neither result nor error"
963                ),
964            }),
965            Ok(Reply::Closed(reason)) => Err(self.shared.error_for(&reason, Some(method))),
966            Err(_) => Err(self.closed_error(Some(method))),
967        }
968    }
969
970    /// Send a notification, which has no answer. Returns once it is queued
971    /// for writing.
972    ///
973    /// # Errors
974    ///
975    /// Fails if the session has ended.
976    pub fn notify(&self, method: &str, params: Value) -> Result<()> {
977        self.enqueue(notification_line(method, &params)?, Some(method))
978    }
979
980    /// Answer a [`ServerRequest`] with a result. Returns once it is queued for
981    /// writing.
982    ///
983    /// # Errors
984    ///
985    /// Fails if the session has ended.
986    pub fn respond(&self, id: RequestId, result: Value) -> Result<()> {
987        self.enqueue(reply_line(&id, "result", &result)?, None)
988    }
989
990    /// Answer a [`ServerRequest`] with a JSON-RPC error. Use it for a request
991    /// the caller does not handle, so the turn that raised it is not left
992    /// waiting. Returns once it is queued for writing.
993    ///
994    /// # Errors
995    ///
996    /// Fails if the session has ended.
997    pub fn respond_error(
998        &self,
999        id: RequestId,
1000        code: i64,
1001        message: impl Into<String>,
1002    ) -> Result<()> {
1003        let body = json!({ "code": code, "message": message.into() });
1004        self.enqueue(reply_line(&id, "error", &body)?, None)
1005    }
1006
1007    /// Start a thread (`thread/start`).
1008    ///
1009    /// # Errors
1010    ///
1011    /// As [`request`](Self::request), and a protocol error if the response has
1012    /// no thread id.
1013    pub async fn thread_start(&self, params: ThreadStartParams) -> Result<Thread> {
1014        let params =
1015            serde_json::to_value(params).map_err(|e| json_error("thread/start params", e))?;
1016        let raw = self.request("thread/start", params).await?;
1017        let id = raw
1018            .pointer("/thread/id")
1019            .and_then(Value::as_str)
1020            .ok_or_else(|| Error::AppServerProtocol {
1021                message: "thread/start returned no thread id".into(),
1022            })?
1023            .to_string();
1024        let model = raw.get("model").and_then(Value::as_str).map(str::to_string);
1025        Ok(Thread { id, model, raw })
1026    }
1027
1028    /// Start a turn (`turn/start`). The turn runs in the background: watch for
1029    /// its `turn/completed` notification.
1030    ///
1031    /// # Errors
1032    ///
1033    /// As [`request`](Self::request), and a protocol error if the response has
1034    /// no turn.
1035    pub async fn turn_start(&self, params: TurnStartParams) -> Result<Turn> {
1036        let params =
1037            serde_json::to_value(params).map_err(|e| json_error("turn/start params", e))?;
1038        let result = self.request("turn/start", params).await?;
1039        let turn = result.get("turn").cloned().unwrap_or(Value::Null);
1040        serde_json::from_value(turn).map_err(|e| Error::AppServerProtocol {
1041            message: format!("turn/start returned no usable turn: {e}"),
1042        })
1043    }
1044
1045    /// Add input to a running turn (`turn/steer`) and return the id of the
1046    /// turn it landed on.
1047    ///
1048    /// The server delivers it to the model at the next item boundary, so a
1049    /// long tool call delays it. `expected_turn_id` must be the active turn.
1050    /// With no active turn the server fails the request with `no active turn
1051    /// to steer`, and with a different one with `expected active turn id ...`;
1052    /// both are [`Error::AppServerRpc`].
1053    ///
1054    /// # Errors
1055    ///
1056    /// As [`request`](Self::request).
1057    pub async fn turn_steer(
1058        &self,
1059        thread_id: &str,
1060        expected_turn_id: &str,
1061        input: Vec<UserInput>,
1062    ) -> Result<String> {
1063        let params = json!({
1064            "threadId": thread_id,
1065            "expectedTurnId": expected_turn_id,
1066            "input": input,
1067        });
1068        let result = self.request("turn/steer", params).await?;
1069        result
1070            .get("turnId")
1071            .and_then(Value::as_str)
1072            .map(str::to_string)
1073            .ok_or_else(|| Error::AppServerProtocol {
1074                message: "turn/steer returned no turn id".into(),
1075            })
1076    }
1077
1078    /// Stop a running turn (`turn/interrupt`). The turn then ends with a
1079    /// `turn/completed` notification whose status is
1080    /// [`TurnStatus::Interrupted`].
1081    ///
1082    /// With no active turn the server fails the request with `no active turn
1083    /// to interrupt`, and with a different one with `expected active turn id
1084    /// ...`; both are [`Error::AppServerRpc`].
1085    ///
1086    /// # Errors
1087    ///
1088    /// As [`request`](Self::request).
1089    pub async fn turn_interrupt(&self, thread_id: &str, turn_id: &str) -> Result<()> {
1090        let params = json!({ "threadId": thread_id, "turnId": turn_id });
1091        self.request("turn/interrupt", params).await.map(|_| ())
1092    }
1093}
1094
1095/// Builds and starts an [`AppServer`].
1096///
1097/// Created by [`AppServer::builder`].
1098#[derive(Debug, Clone)]
1099pub struct AppServerBuilder<'a> {
1100    codex: &'a Codex,
1101    client_name: String,
1102    client_version: String,
1103    opt_out: Vec<String>,
1104}
1105
1106impl<'a> AppServerBuilder<'a> {
1107    /// Name and version reported to the server in `initialize`. The server
1108    /// includes them in its user agent. Defaults to `codex-wrapper` and this
1109    /// crate's version.
1110    #[must_use]
1111    pub fn client_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
1112        self.client_name = name.into();
1113        self.client_version = version.into();
1114        self
1115    }
1116
1117    /// Ask the server not to send a notification method on this connection,
1118    /// by exact name. Streaming deltas (`item/agentMessage/delta`) are the
1119    /// usual candidate for a caller that only needs completed items.
1120    #[must_use]
1121    pub fn opt_out_notification(mut self, method: impl Into<String>) -> Self {
1122        self.opt_out.push(method.into());
1123        self
1124    }
1125
1126    /// The arguments [`start`](Self::start) passes after the client's global
1127    /// args: `app-server --listen stdio://`.
1128    ///
1129    /// `--listen stdio://` is the default transport. It is passed anyway so a
1130    /// change of default cannot move this client onto a socket.
1131    #[must_use]
1132    pub fn args(&self) -> Vec<String> {
1133        vec!["app-server".into(), "--listen".into(), "stdio://".into()]
1134    }
1135
1136    /// The command [`start`](Self::start) will run, as a copy-pasteable shell
1137    /// string, including the client's global args.
1138    #[must_use]
1139    pub fn to_command_string(&self) -> String {
1140        crate::exec::command_string(self.codex, self.args())
1141    }
1142
1143    /// Spawn `codex app-server` and complete the handshake.
1144    ///
1145    /// The command is `codex [global args] app-server --listen stdio://`. The
1146    /// client's binary, environment, working directory, process-group policy,
1147    /// `die_with_parent`, and `on_spawn` observer apply. The handshake is
1148    /// bounded by the client's timeout, when set.
1149    ///
1150    /// # Errors
1151    ///
1152    /// [`Error::Io`] if the process cannot be spawned. If the server exits
1153    /// before the handshake finishes, the failure is classified from its
1154    /// stderr as any failed command is, so a rejected `-c` key is
1155    /// [`Error::Config`]. Otherwise the handshake's own error.
1156    pub async fn start(self) -> Result<AppServer> {
1157        let codex = self.codex;
1158        let operation_args = self.args();
1159        let span = crate::exec::command_span("codex.app_server", codex, &operation_args);
1160        let args = crate::exec::assemble_args(codex, operation_args);
1161        let command_text = format!("{} {}", codex.binary.display(), args.join(" "));
1162        debug!(arg_count = args.len(), "starting codex app-server");
1163
1164        let mut outcome = SpanOutcome::start(span.clone());
1165        let mut command = Command::new(&codex.binary);
1166        command.args(&args);
1167        command.stdin(std::process::Stdio::piped());
1168        command.stdout(std::process::Stdio::piped());
1169        command.stderr(std::process::Stdio::piped());
1170        // As for streaming: dropping the client must not leave the server
1171        // running with no handle left to stop it.
1172        command.kill_on_drop(true);
1173        crate::exec::own_process_group(&mut command, codex.process_group);
1174        crate::exec::apply_die_with_parent(&mut command, codex.die_with_parent);
1175        if let Some(dir) = &codex.working_dir {
1176            command.current_dir(dir);
1177        }
1178        crate::exec::apply_child_environment(&mut command, codex.clear_env, &codex.env);
1179
1180        let mut child = match command.spawn() {
1181            Ok(child) => child,
1182            Err(e) => {
1183                outcome.settle("error", None);
1184                return Err(Error::Io {
1185                    message: format!("failed to spawn codex app-server: {e}"),
1186                    source: e,
1187                    working_dir: codex.working_dir.clone(),
1188                });
1189            }
1190        };
1191        let group = crate::exec::arm_and_notify(
1192            codex.process_group,
1193            codex.termination_signal,
1194            child.id(),
1195            codex.on_spawn.as_ref(),
1196        );
1197        let pid = child.id();
1198
1199        let stdin = child.stdin.take().expect("stdin was configured as piped");
1200        let stdout = child.stdout.take().expect("stdout was configured as piped");
1201        let stderr = child.stderr.take().expect("stderr was configured as piped");
1202
1203        let (events_tx, events_rx) = mpsc::unbounded_channel();
1204        let (writer_tx, writer_rx) = mpsc::unbounded_channel();
1205        let shared = Arc::new(Shared::new(
1206            events_tx,
1207            Some(KillTarget {
1208                pid,
1209                group: codex.process_group,
1210            }),
1211        ));
1212
1213        tokio::spawn(read_stdout(
1214            stdout,
1215            Arc::clone(&shared),
1216            codex.output_limit,
1217            codex.working_dir.clone(),
1218        ));
1219        tokio::spawn(drain_stderr(stderr, Arc::clone(&shared)));
1220        tokio::spawn(write_stdin(stdin, writer_rx, Arc::clone(&shared)));
1221
1222        let handle = AppServerHandle {
1223            shared,
1224            writer: writer_tx,
1225            timeout: codex.timeout,
1226        };
1227        let mut server = AppServer {
1228            handle,
1229            events: events_rx,
1230            finished: false,
1231            child,
1232            group,
1233            outcome,
1234            termination_grace: codex.termination_grace,
1235            working_dir: codex.working_dir.clone(),
1236            command: command_text,
1237            info: ServerInfo::default(),
1238        };
1239
1240        let handshake = initialize(
1241            &server.handle,
1242            &self.client_name,
1243            &self.client_version,
1244            &self.opt_out,
1245        )
1246        .instrument(span)
1247        .await;
1248        match handshake {
1249            Ok(info) => {
1250                server.info = info;
1251                Ok(server)
1252            }
1253            Err(error) => Err(server.abandon(error).await),
1254        }
1255    }
1256}
1257
1258async fn initialize(
1259    handle: &AppServerHandle,
1260    name: &str,
1261    version: &str,
1262    opt_out: &[String],
1263) -> Result<ServerInfo> {
1264    let mut params = json!({ "clientInfo": { "name": name, "version": version } });
1265    if !opt_out.is_empty() {
1266        params["capabilities"] = json!({ "optOutNotificationMethods": opt_out });
1267    }
1268    let result = handle.request("initialize", params).await?;
1269    let info = serde_json::from_value(result).map_err(|e| Error::AppServerProtocol {
1270        message: format!("initialize returned an unexpected response: {e}"),
1271    })?;
1272    handle.notify("initialized", Value::Null)?;
1273    Ok(info)
1274}
1275
1276/// Which process a fatal stream error stops.
1277#[derive(Clone, Copy)]
1278struct KillTarget {
1279    pid: Option<u32>,
1280    group: bool,
1281}
1282
1283impl KillTarget {
1284    /// Stop the server now. The stream is unusable and nothing will read what
1285    /// the server writes next, so leaving it running would only fill the pipe.
1286    ///
1287    /// Unix only: there is nothing to signal elsewhere, where
1288    /// [`AppServer::next_message`] kills the child when it returns the error.
1289    fn signal(self) {
1290        #[cfg(unix)]
1291        if let Some(pid) = self.pid {
1292            if self.group {
1293                crate::exec::signal_group(pid, libc::SIGKILL);
1294            } else if let Ok(pid) = i32::try_from(pid) {
1295                // SAFETY: `kill` on a pid this client spawned. If the child
1296                // has already been reaped the call fails, which is the state
1297                // we want.
1298                unsafe {
1299                    libc::kill(pid, libc::SIGKILL);
1300                }
1301            }
1302        }
1303        // Read on every platform, so the fields are not dead code where there
1304        // is no signal to send.
1305        #[cfg(not(unix))]
1306        let _ = (self.pid, self.group);
1307    }
1308}
1309
1310/// Read the server's stdout: route answers to waiting requests and everything
1311/// else to the event queue.
1312async fn read_stdout(
1313    stdout: ChildStdout,
1314    shared: Arc<Shared>,
1315    output_limit: Option<usize>,
1316    working_dir: Option<PathBuf>,
1317) {
1318    let mut reader = BufReader::new(stdout);
1319    let mut captured = 0usize;
1320    let reason = loop {
1321        let line = match crate::streaming::read_bounded_line(
1322            &mut reader,
1323            &mut captured,
1324            output_limit,
1325            OutputStream::Stdout,
1326            &working_dir,
1327        )
1328        .await
1329        {
1330            Ok(Some(line)) => line,
1331            Ok(None) => {
1332                shared.stderr_settled().await;
1333                break Closed::Eof;
1334            }
1335            Err(Error::OutputLimitExceeded { limit_bytes, .. }) => {
1336                shared.fire_kill();
1337                break Closed::OutputLimit { limit_bytes };
1338            }
1339            Err(error) => {
1340                shared.fire_kill();
1341                break Closed::Broken(error.to_string());
1342            }
1343        };
1344        if !line.trim_start().starts_with('{') {
1345            debug!(
1346                bytes = line.len(),
1347                "ignoring a non-JSON line from codex app-server"
1348            );
1349            continue;
1350        }
1351        if let Err(reason) = route(&line, &shared) {
1352            shared.fire_kill();
1353            break reason;
1354        }
1355    };
1356    shared.fail(reason);
1357}
1358
1359/// Classify one line from the server and deliver it.
1360fn route(line: &str, shared: &Shared) -> std::result::Result<(), Closed> {
1361    let value: Value = serde_json::from_str(line).map_err(|e| {
1362        let head: String = line.chars().take(120).collect();
1363        Closed::Broken(format!("codex app-server sent invalid JSON ({e}): {head}"))
1364    })?;
1365    let method = value.get("method").and_then(Value::as_str);
1366    let id = value.get("id");
1367    match (method, id) {
1368        (Some(method), Some(id)) => {
1369            let Ok(id) = serde_json::from_value::<RequestId>(id.clone()) else {
1370                warn!(
1371                    method_bytes = method.len(),
1372                    "ignoring a server request with an unusable id"
1373                );
1374                return Ok(());
1375            };
1376            let request = ServerRequest {
1377                id,
1378                method: method.to_string(),
1379                params: value.get("params").cloned().unwrap_or(Value::Null),
1380            };
1381            let _ = shared
1382                .events
1383                .send(Event::Message(ServerMessage::Request(request)));
1384        }
1385        (Some(method), None) => {
1386            let notification = Notification {
1387                method: method.to_string(),
1388                params: value.get("params").cloned().unwrap_or(Value::Null),
1389            };
1390            let _ = shared
1391                .events
1392                .send(Event::Message(ServerMessage::Notification(notification)));
1393        }
1394        (None, Some(id)) if value.get("result").is_some() || value.get("error").is_some() => {
1395            deliver_answer(&value, id, shared);
1396        }
1397        (None, Some(id)) => {
1398            // Shaped like an answer, but neither a result nor an error. If it
1399            // names a waiting request, fail that request rather than leave it
1400            // waiting for an answer that will not come.
1401            let waiter = id
1402                .as_i64()
1403                .and_then(|id| locked(&shared.state).pending.remove(&id));
1404            match waiter {
1405                Some(waiter) => {
1406                    let _ = waiter.send(Reply::Malformed);
1407                }
1408                None => warn!("ignoring an answer with neither result nor error"),
1409            }
1410        }
1411        _ => warn!("ignoring a JSON object from codex app-server that is not a message"),
1412    }
1413    Ok(())
1414}
1415
1416fn deliver_answer(value: &Value, id: &Value, shared: &Shared) {
1417    let Some(id) = id.as_i64() else {
1418        // The server answers a request it could not parse with a null id.
1419        debug!("ignoring an answer with no request id");
1420        return;
1421    };
1422    let waiter = locked(&shared.state).pending.remove(&id);
1423    let Some(waiter) = waiter else {
1424        // The request was cancelled or timed out before the answer arrived.
1425        debug!(id, "ignoring an answer nobody is waiting for");
1426        return;
1427    };
1428    let reply = match value.get("error") {
1429        Some(error) => Reply::Rpc(RpcFailure {
1430            code: error.get("code").and_then(Value::as_i64).unwrap_or(0),
1431            message: error
1432                .get("message")
1433                .and_then(Value::as_str)
1434                .unwrap_or_default()
1435                .to_string(),
1436            data: error.get("data").cloned(),
1437        }),
1438        None => Reply::Result(value.get("result").cloned().unwrap_or(Value::Null)),
1439    };
1440    let _ = waiter.send(reply);
1441}
1442
1443/// Drain stderr for the life of the server. The server logs a lot there, and a
1444/// pipe nobody reads fills and stops it.
1445async fn drain_stderr(mut stderr: ChildStderr, shared: Arc<Shared>) {
1446    let mut buffer = [0u8; 4096];
1447    loop {
1448        match stderr.read(&mut buffer).await {
1449            Ok(0) | Err(_) => {
1450                shared.stderr_done.store(true, Ordering::Release);
1451                shared.stderr_finished.notify_waiters();
1452                break;
1453            }
1454            Ok(read) => {
1455                let mut tail = locked(&shared.stderr_tail);
1456                tail.extend_from_slice(&buffer[..read]);
1457                if tail.len() > STDERR_TAIL_BYTES {
1458                    let excess = tail.len() - STDERR_TAIL_BYTES;
1459                    tail.drain(..excess);
1460                }
1461            }
1462        }
1463    }
1464}
1465
1466/// Write queued lines to the server's stdin, one whole line at a time.
1467///
1468/// Writing happens here, not in the request future, so a request that is
1469/// dropped part way through cannot leave half a line on the wire.
1470async fn write_stdin<W: AsyncWrite + Unpin>(
1471    mut stdin: W,
1472    mut lines: mpsc::UnboundedReceiver<Outgoing>,
1473    shared: Arc<Shared>,
1474) {
1475    while let Some(outgoing) = lines.recv().await {
1476        match outgoing {
1477            Outgoing::Line(line) => {
1478                let written = async {
1479                    stdin.write_all(&line).await?;
1480                    stdin.flush().await
1481                }
1482                .await;
1483                if let Err(error) = written {
1484                    if error.kind() == std::io::ErrorKind::BrokenPipe {
1485                        // The server closed its input, which it does by
1486                        // exiting. Its output closes with it, and the reader
1487                        // reports that together with the server's stderr and,
1488                        // at startup, its exit status. Failing the session
1489                        // here first would hide all of that behind "broken
1490                        // pipe", and which one wins is a race.
1491                        debug!("codex app-server closed its stdin");
1492                    } else {
1493                        shared.fail(Closed::Broken(format!(
1494                            "failed to write to codex app-server stdin: {error}"
1495                        )));
1496                    }
1497                    break;
1498                }
1499            }
1500            Outgoing::Close => break,
1501        }
1502    }
1503    // Dropping stdin closes the pipe, which the server treats as the end of
1504    // its input.
1505}
1506
1507/// A running `codex app-server`.
1508///
1509/// Requests go through [`AppServerHandle`], which this type dereferences to,
1510/// so `server.turn_start(..)` works directly. [`handle`](Self::handle) gives a
1511/// clone that can be moved to another task. Events are read with
1512/// [`next_message`](Self::next_message), which needs `&mut self`.
1513///
1514/// Dropping the value kills the server's process group without waiting; use
1515/// [`shutdown`](Self::shutdown) or [`terminate`](Self::terminate) to stop it
1516/// and wait.
1517pub struct AppServer {
1518    handle: AppServerHandle,
1519    events: mpsc::UnboundedReceiver<Event>,
1520    finished: bool,
1521    child: Child,
1522    group: GroupKillGuard,
1523    outcome: SpanOutcome,
1524    termination_grace: Duration,
1525    working_dir: Option<PathBuf>,
1526    command: String,
1527    info: ServerInfo,
1528}
1529
1530impl std::fmt::Debug for AppServer {
1531    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1532        f.debug_struct("AppServer")
1533            .field("pid", &self.child.id())
1534            .field("info", &self.info)
1535            .finish_non_exhaustive()
1536    }
1537}
1538
1539impl Deref for AppServer {
1540    type Target = AppServerHandle;
1541
1542    fn deref(&self) -> &AppServerHandle {
1543        &self.handle
1544    }
1545}
1546
1547impl AppServer {
1548    /// Start configuring a server for `codex`.
1549    #[must_use]
1550    pub fn builder(codex: &Codex) -> AppServerBuilder<'_> {
1551        AppServerBuilder {
1552            codex,
1553            client_name: "codex-wrapper".to_string(),
1554            client_version: env!("CARGO_PKG_VERSION").to_string(),
1555            opt_out: Vec::new(),
1556        }
1557    }
1558
1559    /// What the server reported about itself during the handshake.
1560    #[must_use]
1561    pub fn server_info(&self) -> &ServerInfo {
1562        &self.info
1563    }
1564
1565    /// The server process's id, while it is running.
1566    #[must_use]
1567    pub fn pid(&self) -> Option<u32> {
1568        self.child.id()
1569    }
1570
1571    /// A cloneable handle for sending requests from other tasks.
1572    #[must_use]
1573    pub fn handle(&self) -> AppServerHandle {
1574        self.handle.clone()
1575    }
1576
1577    /// The next notification or server request, in the order the server sent
1578    /// them.
1579    ///
1580    /// Returns `Ok(None)` once the server's output has ended, after every
1581    /// earlier message has been returned. That is how a server that exited on
1582    /// its own looks; [`shutdown`](Self::shutdown) then reports its exit
1583    /// status. Cancel-safe: dropping the future loses no message.
1584    ///
1585    /// # Errors
1586    ///
1587    /// [`Error::OutputLimitExceeded`] or [`Error::AppServerProtocol`] when the
1588    /// stream became unusable. The server has been killed by then. The error
1589    /// is returned once; later calls return `Ok(None)`.
1590    pub async fn next_message(&mut self) -> Result<Option<ServerMessage>> {
1591        if self.finished {
1592            return Ok(None);
1593        }
1594        match self.events.recv().await {
1595            Some(Event::Message(message)) => Ok(Some(message)),
1596            Some(Event::Closed(reason)) => {
1597                self.finished = true;
1598                match reason {
1599                    Closed::Eof | Closed::Terminated => Ok(None),
1600                    reason => {
1601                        // Already killed on Unix, where the reader signals
1602                        // the group as soon as the stream fails. This covers
1603                        // the platforms that cannot.
1604                        let _ = self.child.start_kill();
1605                        Err(self.handle.shared.error_for(&reason, None))
1606                    }
1607                }
1608            }
1609            None => {
1610                self.finished = true;
1611                Ok(None)
1612            }
1613        }
1614    }
1615
1616    /// End the session and wait for the server to exit.
1617    ///
1618    /// Closes the server's stdin and waits up to the client's termination
1619    /// grace for it to exit on its own. If it does not, this falls back to
1620    /// [`terminate`](Self::terminate) and returns `Ok`, since the caller asked
1621    /// for the end.
1622    ///
1623    /// # Errors
1624    ///
1625    /// If the server exits with a non-zero status by itself, the failure is
1626    /// classified from its stderr like any failed command
1627    /// ([`Error::CommandFailed`] and its refinements).
1628    pub async fn shutdown(mut self) -> Result<()> {
1629        // The child is about to be reaped, after which its pid is not ours to
1630        // signal.
1631        self.handle.shared.revoke_kill();
1632        let _ = self.handle.writer.send(Outgoing::Close);
1633        match tokio::time::timeout(self.termination_grace, self.child.wait()).await {
1634            Ok(Ok(status)) => {
1635                self.group.disarm();
1636                self.handle.shared.stderr_settled().await;
1637                self.handle.shared.fail(Closed::Terminated);
1638                let code = status.code().unwrap_or(-1);
1639                if status.success() {
1640                    self.outcome.settle("ok", Some(code));
1641                    return Ok(());
1642                }
1643                self.outcome.settle("failed", Some(code));
1644                Err(Error::from_command_failure(
1645                    self.command.clone(),
1646                    code,
1647                    String::new(),
1648                    self.handle.shared.stderr_summary(),
1649                    self.working_dir.clone(),
1650                ))
1651            }
1652            Ok(Err(error)) => Err(Error::Io {
1653                message: format!("failed to wait on codex app-server: {error}"),
1654                source: error,
1655                working_dir: self.working_dir.clone(),
1656            }),
1657            Err(_) => self.terminate().await,
1658        }
1659    }
1660
1661    /// Stop the server and its process group, and wait until it is gone.
1662    ///
1663    /// Sends the client's configured termination signal to the group,
1664    /// waits through the client's termination grace,
1665    /// kills what remains, and reaps the child. Requests still waiting fail.
1666    ///
1667    /// Shell commands the server started run in groups of their own and are
1668    /// not reached by group signaling. Cooperative cleanup depends on the
1669    /// server; see the [module documentation](self#lifecycle-and-cancellation).
1670    /// [`shutdown`](Self::shutdown) is the way to stop those.
1671    ///
1672    /// # Errors
1673    ///
1674    /// [`Error::Io`] if the child cannot be waited on.
1675    pub async fn terminate(mut self) -> Result<()> {
1676        self.handle.shared.revoke_kill();
1677        self.handle.shared.fail(Closed::Terminated);
1678        let result = crate::exec::terminate_and_reap(
1679            &mut self.child,
1680            &mut self.group,
1681            self.termination_grace,
1682            self.working_dir.as_deref(),
1683        )
1684        .await;
1685        self.outcome.settle("cancelled", None);
1686        result
1687    }
1688
1689    /// Clean up after a failed handshake and choose the error to report.
1690    async fn abandon(mut self, error: Error) -> Error {
1691        self.handle.shared.revoke_kill();
1692        let outcome = if matches!(error, Error::Timeout { .. }) {
1693            "timeout"
1694        } else {
1695            "failed"
1696        };
1697        // Only a server that closed its own output has failed by itself. When
1698        // the reader gave up on the stream it killed the child, so the exit
1699        // status says nothing and the error already says what happened.
1700        let by_server = matches!(locked(&self.handle.shared.state).closed, Some(Closed::Eof));
1701
1702        // Has the child already ended? One that closed its output is given a
1703        // moment to finish exiting. Otherwise only look, so a server that is
1704        // merely silent is not waited on.
1705        let ended = if by_server {
1706            tokio::time::timeout(STARTUP_EXIT_WAIT, self.child.wait())
1707                .await
1708                .ok()
1709        } else {
1710            self.child.try_wait().transpose()
1711        };
1712        if let Some(Ok(status)) = ended {
1713            // Reaped: nothing is left to terminate, and its pid is no longer
1714            // ours to signal.
1715            self.group.disarm();
1716            self.handle.shared.stderr_settled().await;
1717            let code = status.code().unwrap_or(-1);
1718            self.outcome.settle(outcome, Some(code));
1719            if by_server && !status.success() {
1720                // A server that rejects its arguments or config exits before
1721                // it can answer. Its exit status and stderr say more than
1722                // "closed its output".
1723                return Error::from_command_failure(
1724                    self.command.clone(),
1725                    code,
1726                    String::new(),
1727                    self.handle.shared.stderr_summary(),
1728                    self.working_dir.clone(),
1729                );
1730            }
1731            return error;
1732        }
1733
1734        self.handle.shared.fail(Closed::Terminated);
1735        let _ = crate::exec::terminate_and_reap(
1736            &mut self.child,
1737            &mut self.group,
1738            self.termination_grace,
1739            self.working_dir.as_deref(),
1740        )
1741        .await;
1742        self.outcome.settle(outcome, None);
1743        error
1744    }
1745}
1746
1747impl Drop for AppServer {
1748    fn drop(&mut self) {
1749        // The fields that follow kill the group and let tokio reap the child.
1750        // After that the reader task must not signal the pid.
1751        self.handle.shared.revoke_kill();
1752    }
1753}
1754
1755#[cfg(all(test, unix))]
1756mod tests {
1757    use super::*;
1758    use crate::CodexBuilder;
1759    use crate::test_support::{PidFile, is_running_for_test, wait_until_gone};
1760
1761    fn fake(mode: &str) -> CodexBuilder {
1762        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1763            .join("tests")
1764            .join("fake-app-server.sh");
1765        Codex::builder()
1766            .binary("/bin/bash")
1767            .arg(script.to_str().expect("fixture path is utf-8"))
1768            .env("FAKE_APP_SERVER_MODE", mode)
1769            // Terminating always waits out the grace, so keep it short.
1770            .termination_grace(Duration::from_millis(100))
1771            // A lost answer should fail a test after this, not hang it.
1772            .timeout(Duration::from_secs(20))
1773    }
1774
1775    async fn started(mode: &str) -> AppServer {
1776        let codex = fake(mode).build().expect("bash must exist");
1777        AppServer::builder(&codex)
1778            .start()
1779            .await
1780            .expect("the fake server starts")
1781    }
1782
1783    /// Read messages until `turn/completed`, returning it and everything seen.
1784    async fn until_turn_completed(server: &mut AppServer) -> (TurnCompleted, Vec<ServerMessage>) {
1785        let mut seen = Vec::new();
1786        loop {
1787            let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
1788                .await
1789                .expect("the turn should finish")
1790                .expect("no stream error")
1791                .expect("the server should not close first");
1792            let done = match &message {
1793                ServerMessage::Notification(n) => n.turn_completed(),
1794                _ => None,
1795            };
1796            seen.push(message);
1797            if let Some(done) = done {
1798                return (done, seen);
1799            }
1800        }
1801    }
1802
1803    fn methods(seen: &[ServerMessage]) -> Vec<&str> {
1804        seen.iter()
1805            .map(|message| match message {
1806                ServerMessage::Notification(n) => n.method.as_str(),
1807                ServerMessage::Request(r) => r.method.as_str(),
1808            })
1809            .collect()
1810    }
1811
1812    #[tokio::test]
1813    async fn the_handshake_reports_the_server_and_delivers_unsolicited_notifications() {
1814        let mut server = started("turn").await;
1815        assert!(server.server_info().user_agent.contains("0.149.0"));
1816        assert_eq!(
1817            server.server_info().codex_home.as_deref(),
1818            Some("/home/user/.codex")
1819        );
1820
1821        // The real server sends this right after `initialized`, unasked.
1822        let first = server.next_message().await.unwrap().unwrap();
1823        let ServerMessage::Notification(notification) = first else {
1824            panic!("expected a notification, got {first:?}");
1825        };
1826        assert_eq!(notification.method, "remoteControl/status/changed");
1827        assert_eq!(notification.params["status"], "disabled");
1828        server.shutdown().await.unwrap();
1829    }
1830
1831    #[tokio::test]
1832    async fn a_turn_runs_to_completion_and_yields_its_final_message() {
1833        let mut server = started("turn").await;
1834        let thread = server
1835            .thread_start(
1836                ThreadStartParams::new()
1837                    .cwd("/tmp/fixture")
1838                    .ephemeral(true)
1839                    .approval_policy(ApprovalPolicy::Never)
1840                    .sandbox(SandboxMode::ReadOnly),
1841            )
1842            .await
1843            .unwrap();
1844        assert_eq!(thread.id, "01a0d1a2-5f2e-7263-a97b-cabf3e78caff");
1845        assert_eq!(thread.model.as_deref(), Some("gpt-5.6-sol"));
1846
1847        let turn = server
1848            .turn_start(TurnStartParams::text(&thread.id, "say ok"))
1849            .await
1850            .unwrap();
1851        assert_eq!(turn.status, TurnStatus::InProgress);
1852        assert_eq!(turn.id, "01a0d1a2-5f9f-75c1-9305-fa382e7b37bc");
1853
1854        let (done, seen) = until_turn_completed(&mut server).await;
1855        assert_eq!(done.thread_id, thread.id);
1856        assert_eq!(done.turn.id, turn.id);
1857        assert_eq!(done.turn.status, TurnStatus::Completed);
1858        assert_eq!(done.turn.final_message(), Some("ok"));
1859        let methods = methods(&seen);
1860        assert!(methods.contains(&"thread/started"));
1861        assert!(methods.contains(&"turn/started"));
1862        assert!(methods.contains(&"item/agentMessage/delta"));
1863        server.shutdown().await.unwrap();
1864    }
1865
1866    #[tokio::test]
1867    async fn steering_adds_input_to_the_running_turn() {
1868        let mut server = started("held").await;
1869        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1870        let turn = server
1871            .turn_start(TurnStartParams::text(&thread.id, "sleep, then say DONE"))
1872            .await
1873            .unwrap();
1874
1875        let steered = server
1876            .turn_steer(
1877                &thread.id,
1878                &turn.id,
1879                vec![UserInput::text("Also append STEERED")],
1880            )
1881            .await
1882            .unwrap();
1883        assert_eq!(steered, turn.id);
1884
1885        let (done, seen) = until_turn_completed(&mut server).await;
1886        assert_eq!(done.turn.final_message(), Some("DONE STEERED"));
1887        // The fixture echoes the steered text as a user message, so this shows
1888        // the text reached the server.
1889        let echoed = seen.iter().any(|message| match message {
1890            ServerMessage::Notification(n) => {
1891                n.method == "item/completed"
1892                    && n.params.pointer("/item/content/0/text")
1893                        == Some(&json!("Also append STEERED"))
1894            }
1895            _ => false,
1896        });
1897        assert!(echoed, "the server never saw the steered text: {seen:?}");
1898        server.shutdown().await.unwrap();
1899    }
1900
1901    #[tokio::test]
1902    async fn steering_from_another_task_while_events_are_read() {
1903        let mut server = started("held").await;
1904        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1905        let turn = server
1906            .turn_start(TurnStartParams::text(&thread.id, "go"))
1907            .await
1908            .unwrap();
1909
1910        let handle = server.handle();
1911        let (thread_id, turn_id) = (thread.id.clone(), turn.id.clone());
1912        let steer = tokio::spawn(async move {
1913            handle
1914                .turn_steer(&thread_id, &turn_id, vec![UserInput::text("more")])
1915                .await
1916        });
1917
1918        let (done, _) = until_turn_completed(&mut server).await;
1919        assert_eq!(done.turn.status, TurnStatus::Completed);
1920        assert_eq!(steer.await.unwrap().unwrap(), turn.id);
1921        server.shutdown().await.unwrap();
1922    }
1923
1924    #[tokio::test]
1925    async fn steering_the_wrong_turn_is_an_rpc_error_that_names_both_ids() {
1926        let server = started("held").await;
1927        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1928        let turn = server
1929            .turn_start(TurnStartParams::text(&thread.id, "go"))
1930            .await
1931            .unwrap();
1932
1933        let error = server
1934            .turn_steer(&thread.id, "not-the-turn", vec![UserInput::text("x")])
1935            .await
1936            .unwrap_err();
1937        match error {
1938            Error::AppServerRpc {
1939                method,
1940                code,
1941                message,
1942                ..
1943            } => {
1944                assert_eq!(method, "turn/steer");
1945                assert_eq!(code, -32600);
1946                assert_eq!(
1947                    message,
1948                    format!(
1949                        "expected active turn id `not-the-turn` but found `{}`",
1950                        turn.id
1951                    )
1952                );
1953            }
1954            other => panic!("expected an rpc error, got {other:?}"),
1955        }
1956
1957        let error = server
1958            .turn_interrupt(&thread.id, "not-the-turn")
1959            .await
1960            .unwrap_err();
1961        assert!(
1962            matches!(&error, Error::AppServerRpc { message, .. }
1963                if message == &format!("expected active turn id not-the-turn but found {}", turn.id)),
1964            "{error:?}"
1965        );
1966        server.shutdown().await.unwrap();
1967    }
1968
1969    #[tokio::test]
1970    async fn steering_or_interrupting_with_no_active_turn_is_an_rpc_error() {
1971        let server = started("held").await;
1972        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1973
1974        let error = server
1975            .turn_steer(&thread.id, "any", vec![UserInput::text("x")])
1976            .await
1977            .unwrap_err();
1978        assert!(
1979            matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to steer"),
1980            "{error:?}"
1981        );
1982        let error = server.turn_interrupt(&thread.id, "any").await.unwrap_err();
1983        assert!(
1984            matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to interrupt"),
1985            "{error:?}"
1986        );
1987        server.shutdown().await.unwrap();
1988    }
1989
1990    /// codex-cli 0.145.0 sends `items: []` (`itemsView: notLoaded`) in
1991    /// `turn/completed` even when the turn completed, so the answer has to come
1992    /// from the `item/completed` stream.
1993    #[tokio::test]
1994    async fn the_final_answer_is_available_when_turn_completed_carries_no_items() {
1995        let codex = fake("turn")
1996            .env("FAKE_APP_SERVER_ITEMS", "legacy")
1997            .build()
1998            .unwrap();
1999        let mut server = AppServer::builder(&codex).start().await.unwrap();
2000        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2001        server
2002            .turn_start(TurnStartParams::text(&thread.id, "say ok"))
2003            .await
2004            .unwrap();
2005
2006        let (done, seen) = until_turn_completed(&mut server).await;
2007        assert_eq!(done.turn.status, TurnStatus::Completed);
2008        assert!(done.turn.items.is_empty());
2009        assert_eq!(done.turn.final_message(), None);
2010        let answer = seen
2011            .iter()
2012            .filter_map(|message| match message {
2013                ServerMessage::Notification(n) => n.agent_message(),
2014                _ => None,
2015            })
2016            .rfind(AgentMessage::is_final_answer)
2017            .expect("the item stream carries the answer");
2018        assert_eq!(answer.text, "ok");
2019        server.shutdown().await.unwrap();
2020    }
2021
2022    #[tokio::test]
2023    async fn interrupting_ends_the_turn_as_interrupted_with_no_final_message() {
2024        let mut server = started("held").await;
2025        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2026        let turn = server
2027            .turn_start(TurnStartParams::text(&thread.id, "go"))
2028            .await
2029            .unwrap();
2030
2031        server.turn_interrupt(&thread.id, &turn.id).await.unwrap();
2032
2033        let (done, _) = until_turn_completed(&mut server).await;
2034        assert_eq!(done.turn.status, TurnStatus::Interrupted);
2035        assert!(done.turn.items.is_empty());
2036        assert_eq!(done.turn.final_message(), None);
2037        server.shutdown().await.unwrap();
2038    }
2039
2040    #[tokio::test]
2041    async fn a_server_request_is_delivered_and_the_reply_reaches_the_server() {
2042        let mut server = started("approval").await;
2043        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2044        server
2045            .turn_start(TurnStartParams::text(&thread.id, "touch a file"))
2046            .await
2047            .unwrap();
2048
2049        let mut seen = Vec::new();
2050        let request = loop {
2051            let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
2052                .await
2053                .unwrap()
2054                .unwrap()
2055                .unwrap();
2056            if let ServerMessage::Request(request) = message {
2057                break request;
2058            }
2059            seen.push(message);
2060        };
2061        assert_eq!(request.method, "item/commandExecution/requestApproval");
2062        assert_eq!(request.id, RequestId::Number(0));
2063        assert_eq!(
2064            request.params["command"],
2065            "/bin/zsh -lc 'touch created.txt'"
2066        );
2067
2068        server
2069            .respond(request.id, json!({ "decision": "decline" }))
2070            .unwrap();
2071
2072        let (done, after) = until_turn_completed(&mut server).await;
2073        // The fixture reports the decision it received.
2074        assert_eq!(done.turn.final_message(), Some("decision: decline"));
2075        assert!(methods(&after).contains(&"serverRequest/resolved"));
2076        server.shutdown().await.unwrap();
2077    }
2078
2079    #[tokio::test]
2080    async fn concurrent_requests_are_matched_to_their_answers_by_id() {
2081        let server = started("turn").await;
2082        let (first, second, unknown) = tokio::join!(
2083            server.thread_start(ThreadStartParams::new()),
2084            server.request("thread/start", json!({})),
2085            server.request("no/such/method", json!({})),
2086        );
2087        assert!(first.is_ok());
2088        assert!(second.unwrap().pointer("/thread/id").is_some());
2089        match unknown.unwrap_err() {
2090            Error::AppServerRpc { message, .. } => {
2091                assert!(
2092                    message.contains("unknown variant `no/such/method`"),
2093                    "{message}"
2094                );
2095            }
2096            other => panic!("expected an rpc error, got {other:?}"),
2097        }
2098        server.shutdown().await.unwrap();
2099    }
2100
2101    #[tokio::test]
2102    async fn a_second_initialize_is_rejected_by_the_server() {
2103        let server = started("turn").await;
2104        let error = server
2105            .request(
2106                "initialize",
2107                json!({ "clientInfo": { "name": "x", "version": "0" } }),
2108            )
2109            .await
2110            .unwrap_err();
2111        assert!(
2112            matches!(&error, Error::AppServerRpc { message, .. } if message == "Already initialized"),
2113            "{error:?}"
2114        );
2115        server.shutdown().await.unwrap();
2116    }
2117
2118    /// What the client puts on the wire, read back from the fixture's log.
2119    #[tokio::test]
2120    async fn requests_are_written_as_the_server_expects_them() {
2121        let log = std::env::temp_dir().join(format!(
2122            "codex-wrapper-{}-app-server-wire.log",
2123            std::process::id()
2124        ));
2125        let _ = std::fs::remove_file(&log);
2126        let codex = fake("held")
2127            .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
2128            .build()
2129            .unwrap();
2130        let mut server = AppServer::builder(&codex)
2131            .client_info("probe", "1.2.3")
2132            .opt_out_notification("item/agentMessage/delta")
2133            .opt_out_notification("mcpServer/startupStatus/updated")
2134            .start()
2135            .await
2136            .unwrap();
2137        let thread = server
2138            .thread_start(
2139                ThreadStartParams::new()
2140                    .cwd("/tmp/fixture")
2141                    .model("gpt-5.6-sol")
2142                    .approval_policy(ApprovalPolicy::Never)
2143                    .sandbox(SandboxMode::ReadOnly)
2144                    .ephemeral(true),
2145            )
2146            .await
2147            .unwrap();
2148        let schema = json!({ "type": "object", "required": ["answer"] });
2149        let turn = server
2150            .turn_start(
2151                TurnStartParams::text(&thread.id, "hi")
2152                    .model("gpt-5.6-sol")
2153                    .effort("low")
2154                    .output_schema(schema.clone())
2155                    .cwd("/tmp/fixture")
2156                    .approval_policy(ApprovalPolicy::Never)
2157                    .param("summary", json!("none")),
2158            )
2159            .await
2160            .unwrap();
2161        server
2162            .turn_steer(&thread.id, &turn.id, vec![UserInput::text("more")])
2163            .await
2164            .unwrap();
2165        let _ = until_turn_completed(&mut server).await;
2166        server.shutdown().await.unwrap();
2167
2168        let lines: Vec<Value> = std::fs::read_to_string(&log)
2169            .unwrap()
2170            .lines()
2171            .map(|line| serde_json::from_str(line).expect("every client line is JSON"))
2172            .collect();
2173        let _ = std::fs::remove_file(&log);
2174
2175        assert_eq!(
2176            lines[0],
2177            json!({
2178                "id": 0,
2179                "method": "initialize",
2180                "params": {
2181                    "clientInfo": { "name": "probe", "version": "1.2.3" },
2182                    "capabilities": {
2183                        "optOutNotificationMethods": [
2184                            "item/agentMessage/delta",
2185                            "mcpServer/startupStatus/updated"
2186                        ]
2187                    }
2188                }
2189            })
2190        );
2191        assert_eq!(lines[1], json!({ "method": "initialized" }));
2192        assert_eq!(
2193            lines[2],
2194            json!({
2195                "id": 1,
2196                "method": "thread/start",
2197                "params": {
2198                    "cwd": "/tmp/fixture",
2199                    "model": "gpt-5.6-sol",
2200                    "approvalPolicy": "never",
2201                    "sandbox": "read-only",
2202                    "ephemeral": true
2203                }
2204            })
2205        );
2206        assert_eq!(
2207            lines[3],
2208            json!({
2209                "id": 2,
2210                "method": "turn/start",
2211                "params": {
2212                    "threadId": thread.id,
2213                    "input": [{ "type": "text", "text": "hi", "text_elements": [] }],
2214                    "model": "gpt-5.6-sol",
2215                    "effort": "low",
2216                    "outputSchema": schema,
2217                    "cwd": "/tmp/fixture",
2218                    "approvalPolicy": "never",
2219                    "summary": "none"
2220                }
2221            })
2222        );
2223        assert_eq!(
2224            lines[4],
2225            json!({
2226                "id": 3,
2227                "method": "turn/steer",
2228                "params": {
2229                    "threadId": thread.id,
2230                    "expectedTurnId": turn.id,
2231                    "input": [{ "type": "text", "text": "more", "text_elements": [] }]
2232                }
2233            })
2234        );
2235    }
2236
2237    /// A server that exits 0 before it answers has been reaped by the time the
2238    /// failure is reported, so there is nothing left to terminate. Waiting out
2239    /// the grace period (and signalling a pid that is no longer ours) is the
2240    /// failure this guards.
2241    #[tokio::test]
2242    async fn a_server_that_exits_cleanly_before_answering_fails_the_start_without_waiting() {
2243        let codex = fake("exit-clean")
2244            .termination_grace(Duration::from_secs(4))
2245            .build()
2246            .unwrap();
2247        let started_at = std::time::Instant::now();
2248        let error = AppServer::builder(&codex).start().await.unwrap_err();
2249        assert!(
2250            matches!(error, Error::AppServerProtocol { .. }),
2251            "{error:?}"
2252        );
2253        assert!(
2254            started_at.elapsed() < Duration::from_secs(3),
2255            "start waited out the grace period for a server that had already exited"
2256        );
2257    }
2258
2259    /// The reader kills the server when the stream breaks. That must not be
2260    /// mistaken for the server failing by itself, or the useful message is
2261    /// replaced by an exit status.
2262    #[tokio::test]
2263    async fn invalid_json_during_the_handshake_is_reported_as_invalid_json() {
2264        let codex = fake("bad-init").build().unwrap();
2265        let error = AppServer::builder(&codex).start().await.unwrap_err();
2266        assert!(
2267            matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
2268            "{error:?}"
2269        );
2270        assert_eq!(error.exit_code(), None);
2271    }
2272
2273    /// A response that names a waiting request but has neither `result` nor
2274    /// `error` is not a valid answer. Ignoring it would leave the request
2275    /// waiting for one that will never come.
2276    #[tokio::test]
2277    async fn a_response_with_neither_result_nor_error_fails_the_request_it_names() {
2278        let server = started("no-result").await;
2279        let error = server
2280            .thread_start(ThreadStartParams::new())
2281            .await
2282            .unwrap_err();
2283        assert!(
2284            matches!(&error, Error::AppServerProtocol { message }
2285                if message.contains("neither result nor error") && message.contains("thread/start")),
2286            "{error:?}"
2287        );
2288        // The session itself is still usable.
2289        assert!(server.notify("initialized", Value::Null).is_ok());
2290        server.shutdown().await.unwrap();
2291    }
2292
2293    /// The reader task holds a way to kill the server. It must stop being able
2294    /// to once the client is done with the child: after that the pid may
2295    /// belong to someone else.
2296    #[tokio::test]
2297    async fn the_readers_kill_switch_is_revoked_when_the_client_is_done_with_the_child() {
2298        // Never signals this process: the target is a `sleep` started here.
2299        let sleeper = |seconds: &str| {
2300            std::process::Command::new("sleep")
2301                .arg(seconds)
2302                .spawn()
2303                .unwrap()
2304        };
2305        let (events, _received) = mpsc::unbounded_channel();
2306
2307        let mut live = sleeper("60");
2308        let shared = Shared::new(
2309            events.clone(),
2310            Some(KillTarget {
2311                pid: Some(live.id()),
2312                group: false,
2313            }),
2314        );
2315        shared.fire_kill();
2316        assert!(
2317            live.wait().unwrap().code().is_none(),
2318            "the switch should have killed the process it was armed with"
2319        );
2320
2321        let mut revoked = sleeper("60");
2322        let shared = Shared::new(
2323            events,
2324            Some(KillTarget {
2325                pid: Some(revoked.id()),
2326                group: false,
2327            }),
2328        );
2329        shared.revoke_kill();
2330        shared.fire_kill();
2331        std::thread::sleep(Duration::from_millis(200));
2332        assert!(
2333            revoked.try_wait().unwrap().is_none(),
2334            "a revoked switch still killed the process"
2335        );
2336        revoked.kill().unwrap();
2337        revoked.wait().unwrap();
2338    }
2339
2340    #[tokio::test]
2341    async fn every_way_of_ending_the_session_revokes_the_kill_switch() {
2342        let armed = |shared: &Shared| locked(&shared.kill).is_some();
2343
2344        let server = started("turn").await;
2345        let shared = Arc::clone(&server.handle.shared);
2346        assert!(armed(&shared));
2347        server.shutdown().await.unwrap();
2348        assert!(!armed(&shared), "shutdown left the switch armed");
2349
2350        let server = started("turn").await;
2351        let shared = Arc::clone(&server.handle.shared);
2352        server.terminate().await.unwrap();
2353        assert!(!armed(&shared), "terminate left the switch armed");
2354
2355        let server = started("turn").await;
2356        let shared = Arc::clone(&server.handle.shared);
2357        drop(server);
2358        assert!(!armed(&shared), "dropping left the switch armed");
2359    }
2360
2361    #[test]
2362    fn the_previewed_command_includes_the_clients_global_args() {
2363        let codex = Codex::builder()
2364            .binary("/bin/echo")
2365            .config("model=\"o3\"")
2366            .build()
2367            .unwrap();
2368        let builder = AppServer::builder(&codex);
2369        assert_eq!(builder.args(), ["app-server", "--listen", "stdio://"]);
2370        assert_eq!(
2371            builder.to_command_string(),
2372            "/bin/echo -c 'model=\"o3\"' app-server --listen stdio://"
2373        );
2374    }
2375
2376    #[tokio::test]
2377    async fn a_silent_server_times_out_the_handshake_and_is_stopped() {
2378        let pid = Arc::new(Mutex::new(None));
2379        let observed = Arc::clone(&pid);
2380        let codex = fake("silent")
2381            .timeout(Duration::from_millis(300))
2382            .on_spawn(Arc::new(move |info| {
2383                *observed.lock().unwrap() = Some(info.pid);
2384            }))
2385            .build()
2386            .unwrap();
2387
2388        let error = AppServer::builder(&codex).start().await.unwrap_err();
2389        assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
2390
2391        let pid = pid.lock().unwrap().expect("the server was spawned");
2392        assert!(
2393            wait_until_gone(pid).await,
2394            "the silent server ({pid}) survived a failed start"
2395        );
2396    }
2397
2398    #[tokio::test]
2399    async fn a_server_that_exits_at_startup_is_reported_with_its_stderr() {
2400        let codex = fake("exit-on-start").build().unwrap();
2401        let error = AppServer::builder(&codex).start().await.unwrap_err();
2402        assert_eq!(error.exit_code(), Some(1), "{error:?}");
2403        assert_eq!(
2404            error.failure_kind(),
2405            Some(crate::FailureKind::Config),
2406            "{error:?}"
2407        );
2408        assert!(error.to_string().contains("bogus_key"), "{error}");
2409    }
2410
2411    /// A server that dies at startup can be noticed by the client's write (the
2412    /// pipe is closed, EPIPE) before its read (the stream has ended). Either
2413    /// way the server went away by itself, and what says why is its stderr and
2414    /// exit status, which the reader reports at the end of the stream. A write
2415    /// error must not become the session's failure and hide that; this was
2416    /// seen as a flaky failure on Linux CI.
2417    ///
2418    /// An in-memory pipe stands in for the child's stdin. A real one made this
2419    /// test hang under load: on macOS a pipe's close-on-exec flag is set after
2420    /// it is created, so a process forked by a concurrent test can inherit the
2421    /// read end, and then the write never fails.
2422    #[tokio::test]
2423    async fn a_broken_stdin_pipe_leaves_the_verdict_to_the_reader() {
2424        let (stdin, server_end) = tokio::io::duplex(64);
2425        drop(server_end);
2426
2427        let (events, _received) = mpsc::unbounded_channel();
2428        let shared = Arc::new(Shared::new(events, None));
2429        let (lines, receiver) = mpsc::unbounded_channel();
2430        lines.send(Outgoing::Line(b"{}\n".to_vec())).unwrap();
2431
2432        // Ends by itself when the write fails. If it did not fail, `lines` is
2433        // still open and this would wait forever, so bound it.
2434        tokio::time::timeout(
2435            Duration::from_secs(10),
2436            write_stdin(stdin, receiver, Arc::clone(&shared)),
2437        )
2438        .await
2439        .expect("the write to a closed pipe did not fail");
2440
2441        assert!(
2442            locked(&shared.state).closed.is_none(),
2443            "a write to a closed pipe was recorded as the session's failure"
2444        );
2445        drop(lines);
2446    }
2447
2448    /// End to end: a server that closes its input and then fails is reported
2449    /// by its exit status and stderr. The race that once made this flaky on
2450    /// Linux CI is pinned by `a_broken_stdin_pipe_leaves_the_verdict_to_the_reader`.
2451    #[tokio::test]
2452    async fn a_server_that_closes_its_input_and_then_fails_is_reported_by_its_exit_status() {
2453        let codex = fake("close-stdin").build().unwrap();
2454        let error = AppServer::builder(&codex).start().await.unwrap_err();
2455        assert_eq!(error.exit_code(), Some(1), "{error:?}");
2456        assert_eq!(
2457            error.failure_kind(),
2458            Some(crate::FailureKind::Config),
2459            "{error:?}"
2460        );
2461        assert!(error.to_string().contains("bogus_key"), "{error}");
2462    }
2463
2464    /// The server writes about 500 KB to stderr before its first answer. An
2465    /// undrained pipe holds about 64 KB, so this hangs if stderr is not read.
2466    #[tokio::test]
2467    async fn heavy_stderr_does_not_stall_the_session() {
2468        let codex = fake("noisy-stderr").build().unwrap();
2469        let server =
2470            tokio::time::timeout(Duration::from_secs(20), AppServer::builder(&codex).start())
2471                .await
2472                .expect("the handshake stalled behind an undrained stderr pipe")
2473                .unwrap();
2474        server.shutdown().await.unwrap();
2475    }
2476
2477    #[tokio::test]
2478    async fn a_server_that_exits_mid_request_fails_it_with_the_stderr() {
2479        let mut server = started("exit-on-turn").await;
2480        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2481        let error = server
2482            .turn_start(TurnStartParams::text(&thread.id, "go"))
2483            .await
2484            .unwrap_err();
2485        let text = error.to_string();
2486        assert!(text.contains("turn/start"), "{text}");
2487        assert!(
2488            text.contains("connection to the model provider was lost"),
2489            "{text}"
2490        );
2491
2492        // Earlier messages are still delivered, then the stream ends cleanly.
2493        while server.next_message().await.unwrap().is_some() {}
2494        assert!(server.next_message().await.unwrap().is_none());
2495
2496        // New requests fail at once instead of waiting for a timeout.
2497        let again = server.request("thread/start", json!({})).await.unwrap_err();
2498        assert!(
2499            matches!(again, Error::AppServerProtocol { .. }),
2500            "{again:?}"
2501        );
2502
2503        // The exit status is reported by shutdown.
2504        let error = server.shutdown().await.unwrap_err();
2505        assert_eq!(error.exit_code(), Some(5), "{error:?}");
2506    }
2507
2508    #[tokio::test]
2509    async fn the_output_limit_ends_the_session_and_kills_the_server() {
2510        let pid = Arc::new(Mutex::new(None));
2511        let observed = Arc::clone(&pid);
2512        let codex = fake("flood")
2513            .output_limit(2048)
2514            .on_spawn(Arc::new(move |info| {
2515                *observed.lock().unwrap() = Some(info.pid);
2516            }))
2517            .build()
2518            .unwrap();
2519        let mut server = AppServer::builder(&codex).start().await.unwrap();
2520
2521        let error = loop {
2522            match server.next_message().await {
2523                Ok(Some(_)) => {}
2524                Ok(None) => panic!("the limit error was swallowed"),
2525                Err(error) => break error,
2526            }
2527        };
2528        assert!(
2529            matches!(
2530                error,
2531                Error::OutputLimitExceeded {
2532                    stream: OutputStream::Stdout,
2533                    limit_bytes: 2048
2534                }
2535            ),
2536            "{error:?}"
2537        );
2538        assert!(server.next_message().await.unwrap().is_none());
2539
2540        let pid = pid.lock().unwrap().expect("the server was spawned");
2541        assert!(
2542            wait_until_gone(pid).await,
2543            "the server ({pid}) kept running after the output limit"
2544        );
2545    }
2546
2547    #[tokio::test]
2548    async fn invalid_json_ends_the_session() {
2549        let mut server = started("bad-json").await;
2550        let error = loop {
2551            match server.next_message().await {
2552                Ok(Some(_)) => {}
2553                Ok(None) => panic!("the malformed line was swallowed"),
2554                Err(error) => break error,
2555            }
2556        };
2557        assert!(
2558            matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
2559            "{error:?}"
2560        );
2561    }
2562
2563    #[tokio::test]
2564    async fn terminate_stops_the_whole_process_group() {
2565        let pid_file = PidFile::new("app-server-terminate");
2566        let codex = fake("spawns-child")
2567            .env(
2568                "CODEX_WRAPPER_TEST_PIDFILE",
2569                pid_file.path().to_str().unwrap(),
2570            )
2571            // Long enough for the fixture's SIGTERM handler to run on a
2572            // loaded machine, so the marker below means what it says.
2573            .termination_grace(Duration::from_secs(1))
2574            .build()
2575            .unwrap();
2576        let server = AppServer::builder(&codex).start().await.unwrap();
2577        let (parent, child) = read_pids(&pid_file).await;
2578        assert!(is_running_for_test(parent) && is_running_for_test(child));
2579
2580        server.terminate().await.unwrap();
2581
2582        // The direct child has been reaped. Its subprocess got SIGKILL at the
2583        // same moment, but nothing waits for it, so allow it a moment to die.
2584        assert!(
2585            wait_until_gone(parent).await,
2586            "the server ({parent}) survived"
2587        );
2588        assert!(
2589            wait_until_gone(child).await,
2590            "the server's subprocess ({child}) survived terminate"
2591        );
2592        // The fixture writes this marker only if it is asked to stop with
2593        // SIGTERM first, which is what separates terminate from a kill.
2594        let marker = term_marker(&pid_file);
2595        assert!(
2596            marker.exists(),
2597            "terminate killed the server without asking it to stop first"
2598        );
2599        let _ = std::fs::remove_file(marker);
2600    }
2601
2602    #[tokio::test]
2603    async fn dropping_during_app_server_termination_grace_kills_the_group() {
2604        let fixture = crate::test_support::GracePeriodFixture::new("app-server-grace-drop");
2605        let codex = fixture.configure(fake("ignores-eof")).build().unwrap();
2606        let server = AppServer::builder(&codex).start().await.unwrap();
2607        fixture.assert_drop_during_grace(server.terminate()).await;
2608    }
2609
2610    #[tokio::test]
2611    async fn dropping_the_client_kills_the_process_group() {
2612        let pid_file = PidFile::new("app-server-drop");
2613        let codex = fake("spawns-child")
2614            .env(
2615                "CODEX_WRAPPER_TEST_PIDFILE",
2616                pid_file.path().to_str().unwrap(),
2617            )
2618            .build()
2619            .unwrap();
2620        let server = AppServer::builder(&codex).start().await.unwrap();
2621        let (parent, child) = read_pids(&pid_file).await;
2622
2623        drop(server);
2624
2625        assert!(
2626            wait_until_gone(parent).await,
2627            "the server ({parent}) survived"
2628        );
2629        assert!(
2630            wait_until_gone(child).await,
2631            "the server's subprocess ({child}) survived the drop"
2632        );
2633        // Dropping is the abrupt path: no SIGTERM, so no marker.
2634        assert!(!term_marker(&pid_file).exists());
2635    }
2636
2637    #[tokio::test]
2638    async fn shutdown_lets_a_server_that_exits_on_eof_finish_by_itself() {
2639        // A fallback to terminate would wait out the whole grace, so a long
2640        // grace makes the two paths easy to tell apart without a tight bound.
2641        let codex = fake("turn")
2642            .termination_grace(Duration::from_secs(4))
2643            .build()
2644            .unwrap();
2645        let server = AppServer::builder(&codex).start().await.unwrap();
2646        let pid = server.pid().expect("running");
2647        let started_at = std::time::Instant::now();
2648        server.shutdown().await.unwrap();
2649        assert!(
2650            started_at.elapsed() < Duration::from_secs(3),
2651            "shutdown waited out the grace instead of seeing the exit"
2652        );
2653        assert!(wait_until_gone(pid).await);
2654    }
2655
2656    #[tokio::test]
2657    async fn shutdown_falls_back_to_termination_when_the_server_ignores_eof() {
2658        let pid_file = PidFile::new("app-server-ignores-eof");
2659        let codex = fake("ignores-eof")
2660            .env(
2661                "CODEX_WRAPPER_TEST_PIDFILE",
2662                pid_file.path().to_str().unwrap(),
2663            )
2664            // Long enough for the fixture's SIGTERM handler to run on a
2665            // loaded machine, so the marker below means what it says.
2666            .termination_grace(Duration::from_secs(1))
2667            .build()
2668            .unwrap();
2669        let server = AppServer::builder(&codex).start().await.unwrap();
2670        let (parent, child) = read_pids(&pid_file).await;
2671
2672        server.shutdown().await.unwrap();
2673
2674        // Asked to stop before it was killed, not just killed.
2675        let marker = term_marker(&pid_file);
2676        assert!(
2677            marker.exists(),
2678            "shutdown killed the server without asking it to stop"
2679        );
2680        let _ = std::fs::remove_file(marker);
2681
2682        assert!(
2683            wait_until_gone(parent).await,
2684            "the server ({parent}) survived"
2685        );
2686        assert!(
2687            wait_until_gone(child).await,
2688            "the server's subprocess ({child}) survived shutdown"
2689        );
2690    }
2691
2692    #[tokio::test]
2693    async fn requests_after_shutdown_fail_on_a_surviving_handle() {
2694        let server = started("turn").await;
2695        let handle = server.handle();
2696        server.shutdown().await.unwrap();
2697        let error = handle.request("thread/start", json!({})).await.unwrap_err();
2698        assert!(
2699            matches!(error, Error::AppServerProtocol { .. }),
2700            "{error:?}"
2701        );
2702        assert!(handle.notify("initialized", Value::Null).is_err());
2703    }
2704
2705    fn term_marker(pid_file: &PidFile) -> std::path::PathBuf {
2706        let mut path = pid_file.path().as_os_str().to_owned();
2707        path.push(".term");
2708        std::path::PathBuf::from(path)
2709    }
2710
2711    async fn read_pids(pid_file: &PidFile) -> (u32, u32) {
2712        // Up to ten seconds: starting bash can be slow on a loaded machine.
2713        for _ in 0..1000 {
2714            if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
2715                let field = |key: &str| {
2716                    contents
2717                        .lines()
2718                        .find_map(|line| line.strip_prefix(key))
2719                        .and_then(|value| value.trim().parse::<u32>().ok())
2720                };
2721                if let (Some(parent), Some(child)) = (field("parent="), field("child=")) {
2722                    return (parent, child);
2723                }
2724            }
2725            tokio::time::sleep(Duration::from_millis(10)).await;
2726        }
2727        panic!("the fake server never recorded its pids");
2728    }
2729
2730    #[tokio::test]
2731    async fn a_request_that_times_out_leaves_the_session_usable_and_no_entry_behind() {
2732        // The short timeout is for the requests below, not the handshake,
2733        // which has to be allowed to take as long as a loaded machine needs.
2734        let server = started("mute-after-init").await;
2735        let mut handle = server.handle();
2736        handle.timeout = Some(Duration::from_millis(150));
2737
2738        for _ in 0..2 {
2739            let error = handle.request("thread/start", json!({})).await.unwrap_err();
2740            assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
2741        }
2742        assert!(
2743            locked(&handle.shared.state).pending.is_empty(),
2744            "a timed-out request left its slot behind"
2745        );
2746        // A timeout is a verdict on one request, not on the session.
2747        assert!(handle.notify("initialized", Value::Null).is_ok());
2748        server.terminate().await.unwrap();
2749    }
2750
2751    /// A request future that is dropped after it has queued its line must not
2752    /// leave half a line behind: the next request still gets a clean answer,
2753    /// and every line the server received is whole JSON.
2754    #[tokio::test]
2755    async fn dropping_a_request_future_does_not_corrupt_the_wire() {
2756        let log = std::env::temp_dir().join(format!(
2757            "codex-wrapper-{}-app-server-dropped.log",
2758            std::process::id()
2759        ));
2760        let _ = std::fs::remove_file(&log);
2761        let codex = fake("turn")
2762            .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
2763            .build()
2764            .unwrap();
2765        let server = AppServer::builder(&codex).start().await.unwrap();
2766
2767        for _ in 0..20 {
2768            // Poll once, so the line is queued, then drop the future before
2769            // any answer can be read.
2770            let request = server.request("thread/start", json!({ "ephemeral": true }));
2771            let mut request = std::pin::pin!(request);
2772            let mut context = std::task::Context::from_waker(std::task::Waker::noop());
2773            assert!(request.as_mut().poll(&mut context).is_pending());
2774        }
2775        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2776        assert!(!thread.id.is_empty());
2777        server.shutdown().await.unwrap();
2778
2779        let text = std::fs::read_to_string(&log).unwrap();
2780        let _ = std::fs::remove_file(&log);
2781        let mut count = 0;
2782        for line in text.lines() {
2783            serde_json::from_str::<Value>(line).expect("the server received a partial line");
2784            count += 1;
2785        }
2786        // initialize, initialized, twenty abandoned requests, one that was awaited.
2787        assert_eq!(count, 23, "{text}");
2788    }
2789
2790    #[tokio::test]
2791    async fn next_message_loses_nothing_when_its_future_is_dropped() {
2792        let mut server = started("turn").await;
2793        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2794        server
2795            .turn_start(TurnStartParams::text(&thread.id, "go"))
2796            .await
2797            .unwrap();
2798
2799        // Poll with a timeout that keeps expiring, so the future is dropped
2800        // over and over while messages arrive. Bounded by time, not by the
2801        // number of polls, so a slow machine only makes it take longer.
2802        let mut seen = Vec::new();
2803        let mut finished = false;
2804        let deadline = std::time::Instant::now() + Duration::from_secs(20);
2805        while std::time::Instant::now() < deadline {
2806            if let Ok(next) =
2807                tokio::time::timeout(Duration::from_micros(200), server.next_message()).await
2808            {
2809                let message = next.unwrap().expect("the stream ended early");
2810                if let ServerMessage::Notification(n) = &message {
2811                    finished |= n.turn_completed().is_some();
2812                }
2813                seen.push(message);
2814            }
2815            if finished {
2816                break;
2817            }
2818        }
2819        assert!(
2820            finished,
2821            "never saw the turn complete: {:?}",
2822            methods(&seen)
2823        );
2824        let methods = methods(&seen);
2825        // Every message the fixture sends after `initialized`, in order.
2826        let expected = [
2827            "remoteControl/status/changed",
2828            "thread/started",
2829            "thread/status/changed",
2830            "turn/started",
2831            "item/started",
2832            "item/agentMessage/delta",
2833            "item/completed",
2834            "thread/tokenUsage/updated",
2835            "thread/status/changed",
2836            "turn/completed",
2837        ];
2838        assert_eq!(methods, expected);
2839        server.shutdown().await.unwrap();
2840    }
2841
2842    #[test]
2843    fn turn_final_message_takes_the_last_final_answer_and_ignores_commentary() {
2844        let turn: Turn = serde_json::from_value(json!({
2845            "id": "t",
2846            "status": "completed",
2847            "items": [
2848                { "type": "agentMessage", "text": "working", "phase": "commentary" },
2849                { "type": "commandExecution", "text": "not a message", "phase": "final_answer" },
2850                { "type": "agentMessage", "text": "first", "phase": "final_answer" },
2851                { "type": "agentMessage", "text": "last", "phase": "final_answer" }
2852            ]
2853        }))
2854        .unwrap();
2855        assert_eq!(turn.final_message(), Some("last"));
2856    }
2857
2858    #[test]
2859    fn agent_messages_are_decoded_from_item_completed_only() {
2860        let message = |phase: Option<&str>| Notification {
2861            method: "item/completed".into(),
2862            params: json!({
2863                "item": {
2864                    "type": "agentMessage",
2865                    "id": "m",
2866                    "text": "DONE STEERED",
2867                    "phase": phase,
2868                },
2869                "threadId": "th",
2870                "turnId": "tu",
2871            }),
2872        };
2873        let answer = message(Some("final_answer")).agent_message().unwrap();
2874        assert_eq!(answer.text, "DONE STEERED");
2875        assert_eq!(
2876            (answer.thread_id.as_str(), answer.turn_id.as_str()),
2877            ("th", "tu")
2878        );
2879        assert!(answer.is_final_answer());
2880        assert!(
2881            !message(Some("commentary"))
2882                .agent_message()
2883                .unwrap()
2884                .is_final_answer()
2885        );
2886        assert!(!message(None).agent_message().unwrap().is_final_answer());
2887
2888        // Other items, other methods, and a delta are not agent messages.
2889        let mut command = message(None);
2890        command.params["item"]["type"] = json!("commandExecution");
2891        assert!(command.agent_message().is_none());
2892        let mut delta = message(None);
2893        delta.method = "item/agentMessage/delta".into();
2894        assert!(delta.agent_message().is_none());
2895    }
2896
2897    #[test]
2898    fn an_unknown_turn_status_is_kept_apart_from_the_known_ones() {
2899        let turn: Turn =
2900            serde_json::from_value(json!({ "id": "t", "status": "someFutureStatus" })).unwrap();
2901        assert_eq!(turn.status, TurnStatus::Unknown);
2902    }
2903
2904    #[test]
2905    fn only_a_well_formed_turn_completed_notification_decodes() {
2906        let other = Notification {
2907            method: "turn/started".into(),
2908            params: json!({}),
2909        };
2910        assert!(other.turn_completed().is_none());
2911        let malformed = Notification {
2912            method: "turn/completed".into(),
2913            params: json!({ "threadId": "x" }),
2914        };
2915        assert!(malformed.turn_completed().is_none());
2916    }
2917
2918    #[test]
2919    fn request_ids_round_trip_as_numbers_and_strings() {
2920        assert_eq!(serde_json::to_string(&RequestId::Number(7)).unwrap(), "7");
2921        assert_eq!(
2922            serde_json::to_string(&RequestId::String("a".into())).unwrap(),
2923            "\"a\""
2924        );
2925        assert_eq!(
2926            serde_json::from_str::<RequestId>("0").unwrap(),
2927            RequestId::Number(0)
2928        );
2929        assert_eq!(
2930            serde_json::from_str::<RequestId>("\"x\"").unwrap(),
2931            RequestId::String("x".into())
2932        );
2933    }
2934
2935    #[test]
2936    fn reply_lines_echo_the_servers_id() {
2937        let line = reply_line(
2938            &RequestId::Number(0),
2939            "result",
2940            &json!({ "decision": "decline" }),
2941        )
2942        .unwrap();
2943        assert_eq!(
2944            String::from_utf8(line).unwrap(),
2945            "{\"id\":0,\"result\":{\"decision\":\"decline\"}}\n"
2946        );
2947        let line = reply_line(
2948            &RequestId::String("r-1".into()),
2949            "error",
2950            &json!({ "code": -32601, "message": "no" }),
2951        )
2952        .unwrap();
2953        assert_eq!(
2954            String::from_utf8(line).unwrap(),
2955            "{\"id\":\"r-1\",\"error\":{\"code\":-32601,\"message\":\"no\"}}\n"
2956        );
2957    }
2958
2959    #[test]
2960    fn colour_codes_are_removed_from_server_logs() {
2961        let raw = "\u{1b}[2m2026-09-24T04:17:33Z\u{1b}[0m \u{1b}[31mERROR\u{1b}[0m worker quit";
2962        assert_eq!(strip_ansi(raw), "2026-09-24T04:17:33Z ERROR worker quit");
2963    }
2964
2965    #[test]
2966    fn a_line_that_is_not_a_message_is_ignored_and_bad_json_is_fatal() {
2967        let (events, mut received) = mpsc::unbounded_channel();
2968        let shared = Shared::new(events, None);
2969        assert!(route(r#"{"unrelated":true}"#, &shared).is_ok());
2970        assert!(
2971            route(
2972                r#"{"id":null,"error":{"code":-32600,"message":"x"}}"#,
2973                &shared
2974            )
2975            .is_ok()
2976        );
2977        assert!(route(r#"{"id":99,"result":{}}"#, &shared).is_ok());
2978        assert!(received.try_recv().is_err(), "nothing should be delivered");
2979
2980        assert!(route(r#"{"method":"a/b","params":{"k":1}}"#, &shared).is_ok());
2981        assert!(matches!(
2982            received.try_recv(),
2983            Ok(Event::Message(ServerMessage::Notification(n))) if n.method == "a/b"
2984        ));
2985        assert!(route(r#"{"method":"a/b","id":"s"}"#, &shared).is_ok());
2986        assert!(matches!(
2987            received.try_recv(),
2988            Ok(Event::Message(ServerMessage::Request(r))) if r.id == RequestId::String("s".into())
2989        ));
2990        assert!(matches!(
2991            route(r#"{"method": oops"#, &shared),
2992            Err(Closed::Broken(_))
2993        ));
2994    }
2995}