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, the wrapper stops it and reports the action used and
86//!   the reaped status through [`Error::AppServerForcedShutdown`].
87//! - [`AppServer::terminate`] has the settled contract of
88//!   [`stream_exec_cancellable`](crate::streaming::stream_exec_cancellable):
89//!   it asks the server's group to stop, waits through the grace period, kills
90//!   what is left, and reaps the child before returning. A command the server
91//!   started in its own group keeps running, as it does when `codex exec` is
92//!   cancelled; the caller has to find and stop it.
93//! - Dropping an [`AppServer`] kills the server's group without waiting, as
94//!   dropping a streaming future does. The same caveat applies.
95//!
96//! [`AppServerHandle::turn_interrupt`] ends the turn, not the command it is
97//! running.
98//! - A failure that leaves the stream unusable (the output limit, or a line
99//!   that starts with `{` but is not valid JSON) kills the child: on Unix as
100//!   soon as it is detected, and on Windows through its owned process handle.
101//!   The error also reaches any request still waiting.
102//!
103//! # Limits
104//!
105//! [`CodexBuilder::output_limit`](crate::CodexBuilder::output_limit) caps the
106//! total bytes read from stdout over the life of the session, as it does for
107//! streaming. [`CodexBuilder::timeout`](crate::CodexBuilder::timeout) applies
108//! to each request, including the handshake, and not to the session; without
109//! it a request waits until the server answers or exits. The server's stderr is
110//! drained continuously and the last 16 KiB is kept for error messages.
111//!
112//! By default messages wait in an unbounded queue until
113//! [`AppServer::next_message`] returns them, so a caller that does not read
114//! them, or reads more slowly than the server writes, holds them in memory.
115//! `output_limit` bounds the total. Streaming deltas are most of the volume,
116//! and [`AppServerBuilder::opt_out_notification`] stops the server sending
117//! them.
118//!
119//! Five opt-in limits bound memory instead of the lifetime total, and each is
120//! off by default:
121//!
122//! - [`max_frame_bytes`](AppServerBuilder::max_frame_bytes): one line from
123//!   the server, newline included. A longer line is rejected before more than
124//!   the limit is buffered, whether or not it ever ends.
125//! - [`max_queued_messages`](AppServerBuilder::max_queued_messages) and
126//!   [`max_queued_bytes`](AppServerBuilder::max_queued_bytes): notifications
127//!   and server requests read but not yet returned by `next_message`. Answers
128//!   to the client's own requests do not pass through this queue, so they are
129//!   delivered while events wait, and the reader never blocks on it.
130//! - [`max_writer_queue_messages`](AppServerBuilder::max_writer_queue_messages)
131//!   and [`max_writer_queue_bytes`](AppServerBuilder::max_writer_queue_bytes):
132//!   lines queued for the server's stdin, including the one being written. A
133//!   server that stops reading its input fills this.
134//!
135//! Exceeding any of them ends the connection with
136//! [`Error::AppServerLimitExceeded`]. No message is dropped or merged to stay
137//! under a limit: an approval request or a `turn/completed` that does not fit
138//! is not delivered and the session fails instead, so a caller never mistakes
139//! a lossy stream for a complete one. Messages queued before the failure are
140//! still returned by `next_message`, then the error. Every waiting request
141//! fails with the same error, later sends fail at once, and the process the
142//! client owns is killed, as for the output limit.
143//!
144//! # Capabilities
145//!
146//! `initialize` is sent without `capabilities` unless something asks for one.
147//! [`AppServerBuilder::capability`] sets any field of it by its protocol name,
148//! for example `experimentalApi`, which
149//! [`experimental_api`](AppServerBuilder::experimental_api) also sets. The
150//! wrapper does not check other fields; what a field means and whether the
151//! server accepts it depends on the CLI version.
152//!
153//! `optOutNotificationMethods` can be set both ways. The two lists are
154//! combined: the entries set through `capability` first, then those from
155//! [`opt_out_notification`](AppServerBuilder::opt_out_notification), each
156//! method once. A value for it that is neither an array of strings nor `null`
157//! is rejected by [`AppServerBuilder::start`] before anything is spawned.
158//! [`AppServerBuilder::initialize_params`] shows the result.
159//!
160//! # Connecting to an existing server
161//!
162//! On Unix, `AppServerBuilder::connect_unix(path)` attaches over a WebSocket
163//! connection to an explicitly selected Unix socket. It spawns no process:
164//! [`AppServer::pid`] is `None`, and shutdown, terminate, drop, or a transport
165//! failure close only this connection. They never signal the shared server
166//! or promise to interrupt its turns. Client binary/env/global arguments,
167//! spawn observers, and process-group policies do not apply in this mode.
168//!
169//! The connection performs a fresh initialize handshake with the configured
170//! capabilities. Client timeout bounds connect/upgrade and each RPC wait.
171//! Frame and queue byte limits count UTF-8 JSON message payloads, without
172//! WebSocket headers; stdio counts raw line bytes including delimiters.
173//! These budgets are not exact heap measurements. WebSocket frame and
174//! aggregate-message limits prevent fragmentation from bypassing the cap.
175//!
176//! Attached transport support was qualified on CLI 0.163.0 and remains
177//! experimental. Nothing discovers or starts a daemon, adopts a private TUI
178//! process, reconnects automatically, or replays uncertain requests. A new
179//! connection must explicitly resume/reconcile threads, subscriptions and
180//! approvals. Empty, unmaterialized threads may not yet be resumable by a
181//! second client. Two-client rejoin, steering, pending approval delivery and
182//! cancellation, observer disconnect/reconnect, and server loss were probed
183//! with an isolated server and deterministic offline backend. See the shipped
184//! `tests/app-server-qualification.md` for versioned evidence and limits.
185//!
186//! # Verified against codex-cli 0.149.0
187//!
188//! Each of these was read from a captured session, not inferred. Re-capture
189//! after a CLI upgrade and correct this block in the same change.
190//!
191//! - Messages are newline-delimited JSON with no `jsonrpc` field. A
192//!   notification may carry extra top-level fields (`emittedAtMs`).
193//! - A request before `initialize` gets `{"error":{"code":-32600,"message":
194//!   "Not initialized"},"id":N}`, a second `initialize` gets `Already
195//!   initialized`, and an unknown method gets code -32600 with the valid
196//!   method names in the message.
197//! - `initialize` takes `clientInfo` and optionally
198//!   `capabilities.optOutNotificationMethods`, which suppresses those
199//!   notifications for the connection. The client then sends an `initialized`
200//!   notification.
201//! - `thread/start` accepts `cwd`, `ephemeral`, `approvalPolicy`, `sandbox`,
202//!   and `model`. It answers with `{"thread":{"id":...},"model":...}` and
203//!   sends a `thread/started` notification.
204//! - `turn/start` accepts `threadId`, `input`, `model`, `effort`,
205//!   `outputSchema`, `cwd`, and `approvalPolicy`. It answers with
206//!   `{"turn":{"id":...,"status":"inProgress"}}`. With `outputSchema` the
207//!   captured final message was JSON that followed the schema.
208//! - A turn ends with a `turn/completed` notification whose `turn.status` is
209//!   `completed` or `interrupted`. Whether `turn.items` holds the final
210//!   answer depends on the CLI: 0.149.0 includes it (`itemsView` `summary`),
211//!   0.145.0 always sends `items: []` (`notLoaded`). Both send an
212//!   `item/completed` notification for the final `agentMessage` (`phase`
213//!   `final_answer`) before `turn/completed`, so that is what
214//!   [`Notification::agent_message`] decodes.
215//! - `turn/steer` answers `{"turnId":...}` at once. The text reaches the model
216//!   at the next item boundary, not immediately. With no active turn it fails
217//!   with `no active turn to steer`; with one, but a different
218//!   `expectedTurnId`, with ``expected active turn id `X` but found `Y` ``.
219//! - `turn/interrupt` answers `{}`. With no active turn it fails with `no
220//!   active turn to interrupt`; with a different `turnId`, with `expected
221//!   active turn id X but found Y`. It ends the turn and leaves a running
222//!   shell command alone.
223//! - The server runs each shell command in a process group of its own, with
224//!   the server as its parent. With a command running, closing stdin made the
225//!   server exit 0 and took the command with it; SIGTERM to the server, SIGTERM
226//!   to its group, and SIGKILL to its group each left the command running.
227//! - When the approval policy asks, the server sends a request
228//!   (`item/commandExecution/requestApproval`, numeric id starting at 0) and
229//!   the turn waits. The reply is `{"id":0,"result":{"decision":"decline"}}`,
230//!   after which the server sends a `serverRequest/resolved` notification.
231//! - The server logs to stderr, in colour, including MCP startup errors.
232//! - Closing stdin ends the server with status 0. That took 5 seconds in one
233//!   capture where no thread had been started, and milliseconds after a turn.
234//! - A startup failure (an unknown `-c` key under `--strict-config`) writes one
235//!   line to stderr and exits 1.
236//!
237//! # Assumed, not verified
238//!
239//! - Server-initiated requests may use string ids; [`RequestId`] accepts both.
240//! - A JSON object with neither `method` nor a matching response `id` is
241//!   logged and ignored. A line that does not start with `{` is ignored, as
242//!   [`streaming`](crate::streaming) ignores it. A line that starts with `{`
243//!   and is not valid JSON ends the session.
244
245use std::collections::HashMap;
246use std::ops::Deref;
247use std::path::PathBuf;
248use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
249use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
250use std::time::Duration;
251
252#[cfg(unix)]
253use futures_util::{SinkExt, StreamExt};
254use serde::ser::SerializeMap;
255use serde::{Deserialize, Serialize, Serializer};
256use serde_json::{Map, Value, json};
257use tokio::io::{
258    AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader,
259};
260use tokio::process::{Child, ChildStderr, ChildStdout};
261use tokio::sync::{Notify, mpsc, oneshot, watch};
262#[cfg(unix)]
263use tokio_tungstenite::tungstenite::{Message as WsMessage, protocol::WebSocketConfig};
264use tracing::{Instrument, debug, warn};
265
266use crate::Codex;
267use crate::error::{Error, OutputStream, Result, ShutdownAction};
268use crate::exec::{GroupKillGuard, SpanOutcome};
269use crate::types::{ApprovalPolicy, SandboxMode};
270
271/// How much of the server's stderr is kept for error messages.
272const STDERR_TAIL_BYTES: usize = 16 * 1024;
273
274/// How long a server that failed during the handshake is given to report why
275/// it exited before it is terminated.
276const STARTUP_EXIT_WAIT: Duration = Duration::from_secs(2);
277
278/// How long to wait for the stderr reader to finish once the child has exited,
279/// so the last lines it wrote make it into an error message.
280const STDERR_SETTLE: Duration = Duration::from_millis(500);
281
282/// The `initialize` capability that [`AppServerBuilder::opt_out_notification`]
283/// also writes.
284const OPT_OUT_KEY: &str = "optOutNotificationMethods";
285
286/// One of the opt-in transport limits, as reported by
287/// [`Error::AppServerLimitExceeded`].
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
289#[non_exhaustive]
290pub enum AppServerLimit {
291    /// The bytes in one line from the server, newline included. Set with
292    /// [`AppServerBuilder::max_frame_bytes`].
293    FrameBytes,
294    /// Messages waiting for [`AppServer::next_message`]. Set with
295    /// [`AppServerBuilder::max_queued_messages`].
296    QueuedMessages,
297    /// Bytes waiting for [`AppServer::next_message`]. Set with
298    /// [`AppServerBuilder::max_queued_bytes`].
299    QueuedBytes,
300    /// Lines waiting to be written to the server. Set with
301    /// [`AppServerBuilder::max_writer_queue_messages`].
302    WriterQueueMessages,
303    /// Bytes waiting to be written to the server. Set with
304    /// [`AppServerBuilder::max_writer_queue_bytes`].
305    WriterQueueBytes,
306}
307
308impl std::fmt::Display for AppServerLimit {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        f.write_str(match self {
311            Self::FrameBytes => "frame byte",
312            Self::QueuedMessages => "queued message",
313            Self::QueuedBytes => "queued byte",
314            Self::WriterQueueMessages => "writer queue message",
315            Self::WriterQueueBytes => "writer queue byte",
316        })
317    }
318}
319
320/// How an [`AppServer`] reaches the server, and so what it owns.
321#[derive(Debug, Clone, PartialEq, Eq)]
322#[non_exhaustive]
323pub enum AppServerTransport {
324    /// `app-server --listen stdio://`: the client started the server and owns
325    /// it.
326    Stdio,
327    /// An existing server reached by WebSocket over an explicitly selected
328    /// Unix socket. The client owns only its connection.
329    #[cfg(unix)]
330    UnixSocket {
331        /// The selected local socket path.
332        socket: PathBuf,
333    },
334}
335
336impl AppServerTransport {
337    /// Whether this client owns the server process. Attached connections never
338    /// signal the shared server.
339    #[must_use]
340    pub fn owns_server(&self) -> bool {
341        matches!(self, Self::Stdio)
342    }
343
344    /// How the owned process is named in error messages.
345    fn process_name(&self) -> &'static str {
346        match self {
347            Self::Stdio => "codex app-server",
348            #[cfg(unix)]
349            Self::UnixSocket { .. } => "codex app-server connection",
350        }
351    }
352}
353
354/// The opt-in transport limits. `None` is unlimited.
355#[derive(Debug, Clone, Copy, Default)]
356struct Limits {
357    frame_bytes: Option<usize>,
358    queued_messages: Option<usize>,
359    queued_bytes: Option<usize>,
360    writer_messages: Option<usize>,
361    writer_bytes: Option<usize>,
362}
363
364/// Counts what is in one queue against its limits.
365///
366/// A message is reserved before it is queued and released when it leaves the
367/// queue: returned to the caller, written, or discarded. The lock is never held
368/// while another is taken.
369struct Budget {
370    max_messages: Option<usize>,
371    max_bytes: Option<usize>,
372    messages_limit: AppServerLimit,
373    bytes_limit: AppServerLimit,
374    used: Mutex<(usize, usize)>,
375}
376
377impl Budget {
378    fn new(
379        max_messages: Option<usize>,
380        max_bytes: Option<usize>,
381        messages_limit: AppServerLimit,
382        bytes_limit: AppServerLimit,
383    ) -> Self {
384        Self {
385            max_messages,
386            max_bytes,
387            messages_limit,
388            bytes_limit,
389            used: Mutex::new((0, 0)),
390        }
391    }
392
393    /// Count one message of `bytes`, or say which limit it would pass.
394    fn reserve(&self, bytes: usize) -> std::result::Result<(), Closed> {
395        let mut used = locked(&self.used);
396        let messages = used.0.saturating_add(1);
397        let total = used.1.saturating_add(bytes);
398        if let Some(max) = self.max_messages
399            && messages > max
400        {
401            return Err(Closed::Limit {
402                limit: self.messages_limit,
403                max,
404            });
405        }
406        if let Some(max) = self.max_bytes
407            && total > max
408        {
409            return Err(Closed::Limit {
410                limit: self.bytes_limit,
411                max,
412            });
413        }
414        *used = (messages, total);
415        Ok(())
416    }
417
418    fn release(&self, bytes: usize) {
419        let mut used = locked(&self.used);
420        used.0 = used.0.saturating_sub(1);
421        used.1 = used.1.saturating_sub(bytes);
422    }
423
424    #[cfg(all(test, unix))]
425    fn used(&self) -> (usize, usize) {
426        *locked(&self.used)
427    }
428}
429
430/// A JSON-RPC request id.
431///
432/// The server has been seen to send numbers. The protocol allows strings, so
433/// both are accepted, and a reply echoes whichever the server used.
434#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
435#[serde(untagged)]
436pub enum RequestId {
437    /// A numeric id.
438    Number(i64),
439    /// A string id.
440    String(String),
441}
442
443impl std::fmt::Display for RequestId {
444    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445        match self {
446            Self::Number(n) => write!(f, "{n}"),
447            Self::String(s) => f.write_str(s),
448        }
449    }
450}
451
452/// A message the server sent without being asked.
453///
454/// `params` is `null` when the server sent none.
455#[derive(Debug, Clone, PartialEq)]
456pub struct Notification {
457    /// The method name, for example `turn/completed`.
458    pub method: String,
459    /// The method's parameters.
460    pub params: Value,
461}
462
463impl Notification {
464    /// Decode an `item/completed` notification for an agent message, or `None`
465    /// for anything else.
466    ///
467    /// A turn may produce several: progress remarks (`commentary`) and then
468    /// the answer (`final_answer`). Unlike `turn/completed`, this notification
469    /// carries the text on every CLI version tested.
470    #[must_use]
471    pub fn agent_message(&self) -> Option<AgentMessage> {
472        if self.method != "item/completed" {
473            return None;
474        }
475        let item = self.params.get("item")?;
476        if item.get("type")?.as_str()? != "agentMessage" {
477            return None;
478        }
479        Some(AgentMessage {
480            thread_id: self.params.get("threadId")?.as_str()?.to_string(),
481            turn_id: self.params.get("turnId")?.as_str()?.to_string(),
482            text: item.get("text")?.as_str()?.to_string(),
483            phase: item
484                .get("phase")
485                .and_then(Value::as_str)
486                .map(str::to_string),
487        })
488    }
489
490    /// Decode a `turn/completed` notification, or `None` for any other method
491    /// or a payload that does not have the verified shape.
492    #[must_use]
493    pub fn turn_completed(&self) -> Option<TurnCompleted> {
494        if self.method != "turn/completed" {
495            return None;
496        }
497        serde_json::from_value(self.params.clone()).ok()
498    }
499}
500
501/// A finished message from the model, decoded from an `item/completed`
502/// notification by [`Notification::agent_message`].
503#[derive(Debug, Clone, PartialEq, Eq)]
504pub struct AgentMessage {
505    /// The thread the message belongs to.
506    pub thread_id: String,
507    /// The turn the message belongs to.
508    pub turn_id: String,
509    /// The message text.
510    pub text: String,
511    /// `commentary` for a progress remark, `final_answer` for the answer.
512    /// `None` if the server sent no phase.
513    pub phase: Option<String>,
514}
515
516impl AgentMessage {
517    /// Whether this is the turn's answer rather than a progress remark.
518    #[must_use]
519    pub fn is_final_answer(&self) -> bool {
520        self.phase.as_deref() == Some("final_answer")
521    }
522}
523
524/// A request the server sent and is waiting on, such as an approval.
525///
526/// Answer it with [`AppServerHandle::respond`] or
527/// [`AppServerHandle::respond_error`]. The turn that raised it makes no
528/// progress until then.
529#[derive(Debug, Clone, PartialEq)]
530pub struct ServerRequest {
531    /// The id to echo in the reply.
532    pub id: RequestId,
533    /// The method name, for example `item/commandExecution/requestApproval`.
534    pub method: String,
535    /// The method's parameters.
536    pub params: Value,
537}
538
539/// One message from the server that is not the answer to a request.
540#[derive(Debug, Clone, PartialEq)]
541#[non_exhaustive]
542pub enum ServerMessage {
543    /// An event, such as `turn/started` or `item/completed`.
544    Notification(Notification),
545    /// A request that needs a reply.
546    Request(ServerRequest),
547}
548
549/// How a turn is going, from its `status` field.
550///
551/// `inProgress`, `completed`, and `interrupted` were captured. `failed` comes
552/// from the protocol schema.
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
554#[serde(rename_all = "camelCase")]
555#[non_exhaustive]
556pub enum TurnStatus {
557    /// The turn is running.
558    InProgress,
559    /// The turn finished normally.
560    Completed,
561    /// The turn was stopped by `turn/interrupt`.
562    Interrupted,
563    /// The turn failed; see [`Turn::error`].
564    Failed,
565    /// A status this version of the wrapper does not know.
566    #[serde(other)]
567    Unknown,
568}
569
570/// A turn, as reported in `turn/start` responses and `turn/completed`
571/// notifications.
572#[derive(Debug, Clone, PartialEq, Deserialize)]
573#[serde(rename_all = "camelCase")]
574pub struct Turn {
575    /// The turn's id, needed for [`AppServerHandle::turn_steer`] and
576    /// [`AppServerHandle::turn_interrupt`].
577    pub id: String,
578    /// The turn's status.
579    pub status: TurnStatus,
580    /// The items the payload includes. Empty for a turn that was interrupted.
581    #[serde(default)]
582    pub items: Vec<Value>,
583    /// Why the turn failed. Only set when the status is
584    /// [`TurnStatus::Failed`].
585    #[serde(default)]
586    pub error: Option<Value>,
587    /// How long the turn ran, in milliseconds, once it has ended.
588    #[serde(default)]
589    pub duration_ms: Option<i64>,
590}
591
592impl Turn {
593    /// The text of the turn's final answer: the last `agentMessage` item in
594    /// [`items`](Self::items) whose `phase` is `final_answer`.
595    ///
596    /// Only newer servers put the answer in `turn/completed` (0.149.0 does,
597    /// 0.145.0 sends no items), and an interrupted turn never has one. To get
598    /// the answer from any version, keep the last
599    /// [`Notification::agent_message`] whose
600    /// [`is_final_answer`](AgentMessage::is_final_answer) is true.
601    #[must_use]
602    pub fn final_message(&self) -> Option<&str> {
603        self.items
604            .iter()
605            .rev()
606            .filter(|item| {
607                item.get("type").and_then(Value::as_str) == Some("agentMessage")
608                    && item.get("phase").and_then(Value::as_str) == Some("final_answer")
609            })
610            .find_map(|item| item.get("text").and_then(Value::as_str))
611    }
612}
613
614/// The payload of a `turn/completed` notification.
615#[derive(Debug, Clone, PartialEq, Deserialize)]
616#[serde(rename_all = "camelCase")]
617pub struct TurnCompleted {
618    /// The thread the turn belongs to.
619    pub thread_id: String,
620    /// The turn, in its final state.
621    pub turn: Turn,
622}
623
624/// A thread, as returned by `thread/start`.
625#[derive(Debug, Clone, PartialEq)]
626pub struct Thread {
627    /// The thread id, needed to start turns on it.
628    pub id: String,
629    /// The model the thread will use, when the server reports one.
630    pub model: Option<String>,
631    /// The complete response, for fields this type does not name.
632    pub raw: Value,
633}
634
635/// What the server reported about itself in the `initialize` response.
636#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
637#[serde(rename_all = "camelCase", default)]
638pub struct ServerInfo {
639    /// The server's user agent string, which includes the CLI version.
640    pub user_agent: String,
641    /// The Codex home directory the server is using.
642    pub codex_home: Option<String>,
643    /// `unix` or `windows`.
644    pub platform_family: Option<String>,
645    /// The operating system name.
646    pub platform_os: Option<String>,
647}
648
649/// One piece of user input for a turn.
650#[derive(Debug, Clone, PartialEq)]
651pub enum UserInput {
652    /// Plain text.
653    Text(String),
654    /// Any other input item, sent as given. See the protocol schema for the
655    /// shapes the server accepts.
656    Raw(Value),
657}
658
659impl UserInput {
660    /// A text input.
661    #[must_use]
662    pub fn text(text: impl Into<String>) -> Self {
663        Self::Text(text.into())
664    }
665}
666
667impl Serialize for UserInput {
668    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
669        match self {
670            Self::Text(text) => {
671                let mut map = serializer.serialize_map(Some(3))?;
672                map.serialize_entry("type", "text")?;
673                map.serialize_entry("text", text)?;
674                // Sent as the captured client sent it. The schema gives the
675                // field a default, but a server that requires it is not ruled
676                // out by that.
677                map.serialize_entry("text_elements", &Vec::<Value>::new())?;
678                map.end()
679            }
680            Self::Raw(value) => value.serialize(serializer),
681        }
682    }
683}
684
685/// Parameters for `thread/start`.
686///
687/// Every field is optional. Fields this type does not name can be set with
688/// [`param`](Self::param).
689#[derive(Debug, Clone, Default, Serialize)]
690#[serde(rename_all = "camelCase")]
691pub struct ThreadStartParams {
692    #[serde(skip_serializing_if = "Option::is_none")]
693    cwd: Option<PathBuf>,
694    #[serde(skip_serializing_if = "Option::is_none")]
695    model: Option<String>,
696    #[serde(skip_serializing_if = "Option::is_none")]
697    approval_policy: Option<ApprovalPolicy>,
698    #[serde(skip_serializing_if = "Option::is_none")]
699    sandbox: Option<SandboxMode>,
700    #[serde(skip_serializing_if = "Option::is_none")]
701    ephemeral: Option<bool>,
702    #[serde(flatten)]
703    extra: Map<String, Value>,
704}
705
706impl ThreadStartParams {
707    /// Parameters with nothing set, which starts a thread with the server's
708    /// defaults.
709    #[must_use]
710    pub fn new() -> Self {
711        Self::default()
712    }
713
714    /// The thread's working directory.
715    #[must_use]
716    pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
717        self.cwd = Some(dir.into());
718        self
719    }
720
721    /// The model the thread uses.
722    #[must_use]
723    pub fn model(mut self, model: impl Into<String>) -> Self {
724        self.model = Some(model.into());
725        self
726    }
727
728    /// When the server asks before running a command or applying a change.
729    #[must_use]
730    pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
731        self.approval_policy = Some(policy);
732        self
733    }
734
735    /// The sandbox for commands the model runs.
736    #[must_use]
737    pub fn sandbox(mut self, mode: SandboxMode) -> Self {
738        self.sandbox = Some(mode);
739        self
740    }
741
742    /// Whether the thread is kept out of the session history.
743    #[must_use]
744    pub fn ephemeral(mut self, ephemeral: bool) -> Self {
745        self.ephemeral = Some(ephemeral);
746        self
747    }
748
749    /// Set a parameter this type has no method for, using the protocol's
750    /// camelCase name. It is sent as given and not checked.
751    #[must_use]
752    pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
753        self.extra.insert(name.into(), value);
754        self
755    }
756}
757
758/// Parameters for `turn/start`.
759///
760/// The thread and the input are required. The other fields override the
761/// thread's settings for this turn and, per the protocol, later ones. Fields
762/// this type does not name can be set with [`param`](Self::param).
763#[derive(Debug, Clone, Serialize)]
764#[serde(rename_all = "camelCase")]
765pub struct TurnStartParams {
766    thread_id: String,
767    input: Vec<UserInput>,
768    #[serde(skip_serializing_if = "Option::is_none")]
769    model: Option<String>,
770    #[serde(skip_serializing_if = "Option::is_none")]
771    effort: Option<String>,
772    #[serde(skip_serializing_if = "Option::is_none")]
773    output_schema: Option<Value>,
774    #[serde(skip_serializing_if = "Option::is_none")]
775    cwd: Option<PathBuf>,
776    #[serde(skip_serializing_if = "Option::is_none")]
777    approval_policy: Option<ApprovalPolicy>,
778    #[serde(flatten)]
779    extra: Map<String, Value>,
780}
781
782impl TurnStartParams {
783    /// A turn on `thread_id` with the given input.
784    #[must_use]
785    pub fn new(thread_id: impl Into<String>, input: Vec<UserInput>) -> Self {
786        Self {
787            thread_id: thread_id.into(),
788            input,
789            model: None,
790            effort: None,
791            output_schema: None,
792            cwd: None,
793            approval_policy: None,
794            extra: Map::new(),
795        }
796    }
797
798    /// A turn on `thread_id` whose input is one text prompt.
799    #[must_use]
800    pub fn text(thread_id: impl Into<String>, prompt: impl Into<String>) -> Self {
801        Self::new(thread_id, vec![UserInput::text(prompt)])
802    }
803
804    /// The model for this turn.
805    #[must_use]
806    pub fn model(mut self, model: impl Into<String>) -> Self {
807        self.model = Some(model.into());
808        self
809    }
810
811    /// The reasoning effort for this turn. The valid values depend on the
812    /// model, so this is a string.
813    #[must_use]
814    pub fn effort(mut self, effort: impl Into<String>) -> Self {
815        self.effort = Some(effort.into());
816        self
817    }
818
819    /// A JSON Schema the final message must follow.
820    #[must_use]
821    pub fn output_schema(mut self, schema: Value) -> Self {
822        self.output_schema = Some(schema);
823        self
824    }
825
826    /// The working directory for this turn.
827    #[must_use]
828    pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
829        self.cwd = Some(dir.into());
830        self
831    }
832
833    /// When the server asks before running a command or applying a change.
834    #[must_use]
835    pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
836        self.approval_policy = Some(policy);
837        self
838    }
839
840    /// Set a parameter this type has no method for, using the protocol's
841    /// camelCase name. It is sent as given and not checked.
842    #[must_use]
843    pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
844        self.extra.insert(name.into(), value);
845        self
846    }
847}
848
849/// A JSON-RPC error the server returned for a request.
850struct RpcFailure {
851    code: i64,
852    message: String,
853    data: Option<Value>,
854}
855
856/// Why the connection to the server ended.
857#[derive(Debug, Clone)]
858enum Closed {
859    /// The server closed its stdout: it exited, or was stopped.
860    Eof,
861    /// Stdout passed the byte ceiling.
862    OutputLimit { limit_bytes: usize },
863    /// The stream cannot be trusted any more, or could not be read or written.
864    Broken(String),
865    /// The client ended the session.
866    Terminated,
867    /// One of the opt-in transport limits was passed.
868    Limit { limit: AppServerLimit, max: usize },
869}
870
871/// What a waiting request gets back.
872enum Reply {
873    Result(Value),
874    Rpc(RpcFailure),
875    /// A response with neither `result` nor `error`.
876    Malformed,
877    Closed(Closed),
878}
879
880/// What the reader hands to [`AppServer::next_message`].
881enum Event {
882    /// A message and the bytes it holds in the inbound budget.
883    Message(ServerMessage, usize),
884    Closed(Closed),
885}
886
887/// What the writer task is asked to do.
888enum Outgoing {
889    Line(ReservedLine),
890    /// Stop writing and drop stdin, which the server sees as end of input.
891    Close,
892}
893
894/// Owns the reservation through queued, in-flight, cancelled and aborted writes.
895struct ReservedLine {
896    bytes: Vec<u8>,
897    budget: Arc<Budget>,
898}
899impl Drop for ReservedLine {
900    fn drop(&mut self) {
901        self.budget.release(self.bytes.len());
902    }
903}
904
905struct State {
906    pending: HashMap<i64, oneshot::Sender<Reply>>,
907    closed: Option<Closed>,
908}
909
910/// State shared by the handles, the owner, and the three I/O tasks.
911struct Shared {
912    state: Mutex<State>,
913    next_id: AtomicI64,
914    stderr_tail: Mutex<Vec<u8>>,
915    /// Set, and `stderr_finished` notified, when the stderr reader has seen
916    /// end of file, so its last lines are in `stderr_tail`.
917    stderr_done: AtomicBool,
918    stderr_finished: Notify,
919    /// What the reader task may kill when the stream breaks. Taken away, under
920    /// this lock, before the client reaps the child, so the reader can never
921    /// signal a pid that has been released.
922    kill: Mutex<Option<KillTarget>>,
923    /// Preserves a transport-triggered hard stop for a later shutdown.
924    /// Revoking the kill switch synchronizes with writes from the I/O tasks.
925    hard_kill_sent: AtomicBool,
926    events: mpsc::UnboundedSender<Event>,
927    /// Messages routed to `events` and not yet returned by `next_message`.
928    inbound: Budget,
929    /// Lines handed to the writer and not yet written, the one being written
930    /// included.
931    outbound: Arc<Budget>,
932    closed: watch::Sender<bool>,
933    newline_delimited: bool,
934    frame_bytes: Option<usize>,
935    /// The owned process, as error messages name it.
936    process: &'static str,
937}
938
939fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
940    // Nothing here panics while holding a lock, so a poisoned mutex holds
941    // consistent data. Recovering keeps one panicking task from taking the
942    // whole session down with it.
943    mutex.lock().unwrap_or_else(PoisonError::into_inner)
944}
945
946impl Shared {
947    /// End the session: fail every waiting request and tell the reader side.
948    /// The first reason wins.
949    fn fail(&self, reason: Closed) {
950        self.end(reason, true);
951    }
952
953    fn end(&self, reason: Closed, stop_writer: bool) {
954        self.end_with_cleanup(reason, stop_writer, false);
955    }
956
957    fn end_with_cleanup(&self, reason: Closed, stop_writer: bool, kill: bool) {
958        let pending = {
959            let mut state = locked(&self.state);
960            if state.closed.is_some() {
961                if stop_writer {
962                    self.closed.send_replace(true);
963                }
964                return;
965            }
966            state.closed = Some(reason.clone());
967            if kill {
968                self.fire_kill();
969            }
970            if stop_writer {
971                self.closed.send_replace(true);
972            }
973            std::mem::take(&mut state.pending)
974        };
975        for (_, waiter) in pending {
976            let _ = waiter.send(Reply::Closed(reason.clone()));
977        }
978        let _ = self.events.send(Event::Closed(reason));
979    }
980
981    /// Preserve the causal failure before cleanup can produce EOF.
982    fn fatal(&self, reason: Closed) {
983        // Hold admission closed while cleanup starts, then publish the error.
984        // EOF can neither replace the cause nor reach waiters before the kill.
985        self.end_with_cleanup(reason, true, true);
986    }
987
988    async fn wait_closed(&self) {
989        let mut closed = self.closed.subscribe();
990        if !*closed.borrow_and_update() {
991            let _ = closed.changed().await;
992        }
993    }
994
995    fn new(
996        events: mpsc::UnboundedSender<Event>,
997        kill: Option<KillTarget>,
998        limits: Limits,
999        process: &'static str,
1000    ) -> Self {
1001        Self {
1002            state: Mutex::new(State {
1003                pending: HashMap::new(),
1004                closed: None,
1005            }),
1006            next_id: AtomicI64::new(0),
1007            stderr_tail: Mutex::new(Vec::new()),
1008            stderr_done: AtomicBool::new(false),
1009            stderr_finished: Notify::new(),
1010            kill: Mutex::new(kill),
1011            hard_kill_sent: AtomicBool::new(false),
1012            events,
1013            inbound: Budget::new(
1014                limits.queued_messages,
1015                limits.queued_bytes,
1016                AppServerLimit::QueuedMessages,
1017                AppServerLimit::QueuedBytes,
1018            ),
1019            outbound: Arc::new(Budget::new(
1020                limits.writer_messages,
1021                limits.writer_bytes,
1022                AppServerLimit::WriterQueueMessages,
1023                AppServerLimit::WriterQueueBytes,
1024            )),
1025            closed: watch::channel(false).0,
1026            newline_delimited: true,
1027            frame_bytes: limits.frame_bytes,
1028            process,
1029        }
1030    }
1031
1032    fn closed_reason(&self) -> Option<Closed> {
1033        locked(&self.state).closed.clone()
1034    }
1035
1036    /// Hand a message to `next_message`, counting it against the inbound
1037    /// limits. Never waits: answers to requests are routed by the same task,
1038    /// so blocking here would hold them behind events nobody is reading.
1039    fn deliver(&self, message: ServerMessage, bytes: usize) -> std::result::Result<(), Closed> {
1040        let state = locked(&self.state);
1041        if let Some(reason) = &state.closed {
1042            // Intentional shutdown has closed admission, but incoming traffic
1043            // must not cancel the owned writer's graceful drain.
1044            return if matches!(reason, Closed::Terminated) {
1045                Ok(())
1046            } else {
1047                Err(reason.clone())
1048            };
1049        }
1050        self.inbound.reserve(bytes)?;
1051        if self.events.send(Event::Message(message, bytes)).is_err() {
1052            // The receiver is gone with the `AppServer`.
1053            self.inbound.release(bytes);
1054        }
1055        Ok(())
1056    }
1057
1058    /// Kill the server, if the reader still has the authority to. Called when
1059    /// the stream is unusable and nothing will read what the server writes.
1060    fn fire_kill(&self) {
1061        // Held across the signal, so `revoke_kill` cannot return while one is
1062        // being sent.
1063        if let Some(target) = *locked(&self.kill)
1064            && target.signal()
1065        {
1066            self.hard_kill_sent.store(true, Ordering::Relaxed);
1067        }
1068    }
1069
1070    /// Take away the reader's authority to kill. Must be called before the
1071    /// child is reaped: from then on the pid may belong to another process.
1072    fn revoke_kill(&self) {
1073        *locked(&self.kill) = None;
1074    }
1075
1076    /// Wait, for a short while, until the stderr reader has read everything
1077    /// the server wrote. Stdout and stderr close together when the server
1078    /// exits, but the two readers are separate tasks, so an error built from
1079    /// the tail straight away could miss the last lines.
1080    async fn stderr_settled(&self) {
1081        let wait = async {
1082            loop {
1083                let notified = self.stderr_finished.notified();
1084                if self.stderr_done.load(Ordering::Acquire) {
1085                    return;
1086                }
1087                notified.await;
1088            }
1089        };
1090        let _ = tokio::time::timeout(STDERR_SETTLE, wait).await;
1091    }
1092
1093    /// The last lines the server wrote to stderr, without colour codes.
1094    fn stderr_summary(&self) -> String {
1095        let tail = locked(&self.stderr_tail);
1096        let text = strip_ansi(&String::from_utf8_lossy(&tail));
1097        let lines: Vec<&str> = text
1098            .lines()
1099            .map(str::trim)
1100            .filter(|line| !line.is_empty())
1101            .collect();
1102        let start = lines.len().saturating_sub(5);
1103        lines[start..].join("\n")
1104    }
1105
1106    fn error_for(&self, reason: &Closed, method: Option<&str>) -> Error {
1107        let protocol = |message: String| Error::AppServerProtocol { message };
1108        match reason {
1109            Closed::OutputLimit { limit_bytes } => Error::OutputLimitExceeded {
1110                stream: OutputStream::Stdout,
1111                limit_bytes: *limit_bytes,
1112            },
1113            Closed::Limit { limit, max } => Error::AppServerLimitExceeded {
1114                limit: *limit,
1115                max: *max,
1116            },
1117            Closed::Terminated => protocol("the app-server session was ended by the client".into()),
1118            Closed::Broken(message) => protocol(message.clone()),
1119            Closed::Eof => {
1120                let process = self.process;
1121                let stderr = self.stderr_summary();
1122                let while_waiting =
1123                    method.map_or_else(String::new, |m| format!(" before answering `{m}`"));
1124                if stderr.is_empty() {
1125                    protocol(format!("{process} closed its output{while_waiting}"))
1126                } else {
1127                    protocol(format!(
1128                        "{process} closed its output{while_waiting}; stderr: {stderr}"
1129                    ))
1130                }
1131            }
1132        }
1133    }
1134}
1135
1136/// Remove ANSI colour sequences (`ESC [ ... letter`) from server log lines.
1137fn strip_ansi(text: &str) -> String {
1138    let mut out = String::with_capacity(text.len());
1139    let mut chars = text.chars().peekable();
1140    while let Some(c) = chars.next() {
1141        if c == '\u{1b}' && chars.peek() == Some(&'[') {
1142            chars.next();
1143            for c in chars.by_ref() {
1144                if c.is_ascii_alphabetic() {
1145                    break;
1146                }
1147            }
1148        } else {
1149            out.push(c);
1150        }
1151    }
1152    out
1153}
1154
1155/// Removes a waiting request's entry when the request future is dropped, so a
1156/// cancelled request does not leave its slot behind.
1157struct PendingSlot<'a> {
1158    shared: &'a Shared,
1159    id: i64,
1160}
1161
1162impl Drop for PendingSlot<'_> {
1163    fn drop(&mut self) {
1164        locked(&self.shared.state).pending.remove(&self.id);
1165    }
1166}
1167
1168fn json_error(context: &str, source: serde_json::Error) -> Error {
1169    Error::Json {
1170        message: format!("{context}: {source}"),
1171        source,
1172    }
1173}
1174
1175fn request_line(id: i64, method: &str, params: &Value) -> Result<Vec<u8>> {
1176    let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
1177    let mut line = format!("{{\"id\":{id},\"method\":{method}");
1178    if !params.is_null() {
1179        let params = serde_json::to_string(params).map_err(|e| json_error("request params", e))?;
1180        line.push_str(",\"params\":");
1181        line.push_str(&params);
1182    }
1183    line.push_str("}\n");
1184    Ok(line.into_bytes())
1185}
1186
1187fn notification_line(method: &str, params: &Value) -> Result<Vec<u8>> {
1188    let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
1189    let mut line = format!("{{\"method\":{method}");
1190    if !params.is_null() {
1191        let params =
1192            serde_json::to_string(params).map_err(|e| json_error("notification params", e))?;
1193        line.push_str(",\"params\":");
1194        line.push_str(&params);
1195    }
1196    line.push_str("}\n");
1197    Ok(line.into_bytes())
1198}
1199
1200fn reply_line(id: &RequestId, body_key: &str, body: &Value) -> Result<Vec<u8>> {
1201    let id = serde_json::to_string(id).map_err(|e| json_error("request id", e))?;
1202    let body = serde_json::to_string(body).map_err(|e| json_error("reply body", e))?;
1203    Ok(format!("{{\"id\":{id},\"{body_key}\":{body}}}\n").into_bytes())
1204}
1205
1206/// A cloneable handle for sending to the server.
1207///
1208/// It can send requests and answer the server's, but not read events: that
1209/// stays with the [`AppServer`], so a task can steer or interrupt a turn while
1210/// another reads its notifications. Every method fails once the session has
1211/// ended.
1212#[derive(Clone)]
1213pub struct AppServerHandle {
1214    shared: Arc<Shared>,
1215    writer: mpsc::UnboundedSender<Outgoing>,
1216    timeout: Option<Duration>,
1217}
1218
1219impl std::fmt::Debug for AppServerHandle {
1220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1221        f.debug_struct("AppServerHandle")
1222            .field("timeout", &self.timeout)
1223            .finish_non_exhaustive()
1224    }
1225}
1226
1227impl AppServerHandle {
1228    fn closed_error(&self, method: Option<&str>) -> Error {
1229        match self.shared.closed_reason() {
1230            Some(reason) => self.shared.error_for(&reason, method),
1231            None => Error::AppServerProtocol {
1232                message: format!(
1233                    "{} is no longer accepting messages (its stdin is closed)",
1234                    self.shared.process
1235                ),
1236            },
1237        }
1238    }
1239
1240    /// Count a line of `bytes` against the writer limits, or end the session
1241    /// if it does not fit. A line that would pass a limit is never queued: the
1242    /// server would see a gap in what the client sent.
1243    fn admit(&self, bytes: usize, method: Option<&str>) -> Result<()> {
1244        if let Some(reason) = self.shared.closed_reason() {
1245            return Err(self.shared.error_for(&reason, method));
1246        }
1247        if let Err(reason) = self.shared.outbound.reserve(bytes) {
1248            // No lock is held here: `fail` takes the state lock and wakes
1249            // waiters, which may call back into this handle.
1250            self.shared.fatal(reason);
1251            return Err(self.closed_error(method));
1252        }
1253        Ok(())
1254    }
1255
1256    /// Queue a reserved line for the writer, releasing the reservation if the
1257    /// writer has gone.
1258    fn send_line(&self, line: Vec<u8>, method: Option<&str>) -> Result<()> {
1259        let line = ReservedLine {
1260            bytes: line,
1261            budget: Arc::clone(&self.shared.outbound),
1262        };
1263        let state = locked(&self.shared.state);
1264        if let Some(reason) = &state.closed {
1265            return Err(self.shared.error_for(reason, method));
1266        }
1267        let sent = self.writer.send(Outgoing::Line(line));
1268        drop(state);
1269        sent.map_err(|_| self.closed_error(method))
1270    }
1271
1272    fn wire_line(&self, mut line: Vec<u8>) -> Vec<u8> {
1273        if !self.shared.newline_delimited && line.last() == Some(&b'\n') {
1274            line.pop();
1275        }
1276        line
1277    }
1278
1279    fn enqueue(&self, line: Vec<u8>, method: Option<&str>) -> Result<()> {
1280        let line = self.wire_line(line);
1281        self.admit(line.len(), method)?;
1282        self.send_line(line, method)
1283    }
1284
1285    /// Send a request and wait for its answer, returning the `result` value.
1286    ///
1287    /// Requests may run concurrently; each answer is matched by id. A JSON-RPC
1288    /// error from the server is [`Error::AppServerRpc`]. The client's
1289    /// [`timeout`](crate::CodexBuilder::timeout), when set, bounds the wait
1290    /// and yields [`Error::Timeout`]. Pass [`Value::Null`] for no parameters.
1291    ///
1292    /// # Errors
1293    ///
1294    /// Fails if the server rejects the request, the wait times out, or the
1295    /// session ends first.
1296    pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
1297        let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
1298        let line = self.wire_line(request_line(id, method, &params)?);
1299        let (waiter, answer) = oneshot::channel();
1300        // Reserve the line's place before registering for its answer, so a
1301        // request that does not fit fails without having been half accepted.
1302        self.admit(line.len(), Some(method))?;
1303        let closed = {
1304            let mut state = locked(&self.shared.state);
1305            let closed = state.closed.clone();
1306            if closed.is_none() {
1307                state.pending.insert(id, waiter);
1308            }
1309            closed
1310        };
1311        if let Some(reason) = closed {
1312            self.shared.outbound.release(line.len());
1313            return Err(self.shared.error_for(&reason, Some(method)));
1314        }
1315        let _slot = PendingSlot {
1316            shared: &self.shared,
1317            id,
1318        };
1319        self.send_line(line, Some(method))?;
1320
1321        let reply = match self.timeout {
1322            Some(limit) => {
1323                tokio::time::timeout(limit, answer)
1324                    .await
1325                    .map_err(|_| Error::Timeout {
1326                        timeout_seconds: limit.as_secs(),
1327                    })?
1328            }
1329            None => answer.await,
1330        };
1331        match reply {
1332            Ok(Reply::Result(result)) => Ok(result),
1333            Ok(Reply::Rpc(failure)) => Err(Error::AppServerRpc {
1334                method: method.to_string(),
1335                code: failure.code,
1336                message: failure.message,
1337                data: failure.data,
1338            }),
1339            Ok(Reply::Malformed) => Err(Error::AppServerProtocol {
1340                message: format!(
1341                    "codex app-server answered `{method}` with neither result nor error"
1342                ),
1343            }),
1344            Ok(Reply::Closed(reason)) => Err(self.shared.error_for(&reason, Some(method))),
1345            Err(_) => Err(self.closed_error(Some(method))),
1346        }
1347    }
1348
1349    /// Send a notification, which has no answer. Returns once it is queued
1350    /// for writing.
1351    ///
1352    /// # Errors
1353    ///
1354    /// Fails if the session has ended.
1355    pub fn notify(&self, method: &str, params: Value) -> Result<()> {
1356        self.enqueue(notification_line(method, &params)?, Some(method))
1357    }
1358
1359    /// Answer a [`ServerRequest`] with a result. Returns once it is queued for
1360    /// writing.
1361    ///
1362    /// # Errors
1363    ///
1364    /// Fails if the session has ended.
1365    pub fn respond(&self, id: RequestId, result: Value) -> Result<()> {
1366        self.enqueue(reply_line(&id, "result", &result)?, None)
1367    }
1368
1369    /// Answer a [`ServerRequest`] with a JSON-RPC error. Use it for a request
1370    /// the caller does not handle, so the turn that raised it is not left
1371    /// waiting. Returns once it is queued for writing.
1372    ///
1373    /// # Errors
1374    ///
1375    /// Fails if the session has ended.
1376    pub fn respond_error(
1377        &self,
1378        id: RequestId,
1379        code: i64,
1380        message: impl Into<String>,
1381    ) -> Result<()> {
1382        let body = json!({ "code": code, "message": message.into() });
1383        self.enqueue(reply_line(&id, "error", &body)?, None)
1384    }
1385
1386    /// Start a thread (`thread/start`).
1387    ///
1388    /// # Errors
1389    ///
1390    /// As [`request`](Self::request), and a protocol error if the response has
1391    /// no thread id.
1392    pub async fn thread_start(&self, params: ThreadStartParams) -> Result<Thread> {
1393        let params =
1394            serde_json::to_value(params).map_err(|e| json_error("thread/start params", e))?;
1395        let raw = self.request("thread/start", params).await?;
1396        let id = raw
1397            .pointer("/thread/id")
1398            .and_then(Value::as_str)
1399            .ok_or_else(|| Error::AppServerProtocol {
1400                message: "thread/start returned no thread id".into(),
1401            })?
1402            .to_string();
1403        let model = raw.get("model").and_then(Value::as_str).map(str::to_string);
1404        Ok(Thread { id, model, raw })
1405    }
1406
1407    /// Start a turn (`turn/start`). The turn runs in the background: watch for
1408    /// its `turn/completed` notification.
1409    ///
1410    /// # Errors
1411    ///
1412    /// As [`request`](Self::request), and a protocol error if the response has
1413    /// no turn.
1414    pub async fn turn_start(&self, params: TurnStartParams) -> Result<Turn> {
1415        let params =
1416            serde_json::to_value(params).map_err(|e| json_error("turn/start params", e))?;
1417        let result = self.request("turn/start", params).await?;
1418        let turn = result.get("turn").cloned().unwrap_or(Value::Null);
1419        serde_json::from_value(turn).map_err(|e| Error::AppServerProtocol {
1420            message: format!("turn/start returned no usable turn: {e}"),
1421        })
1422    }
1423
1424    /// Add input to a running turn (`turn/steer`) and return the id of the
1425    /// turn it landed on.
1426    ///
1427    /// The server delivers it to the model at the next item boundary, so a
1428    /// long tool call delays it. `expected_turn_id` must be the active turn.
1429    /// With no active turn the server fails the request with `no active turn
1430    /// to steer`, and with a different one with `expected active turn id ...`;
1431    /// both are [`Error::AppServerRpc`].
1432    ///
1433    /// # Errors
1434    ///
1435    /// As [`request`](Self::request).
1436    pub async fn turn_steer(
1437        &self,
1438        thread_id: &str,
1439        expected_turn_id: &str,
1440        input: Vec<UserInput>,
1441    ) -> Result<String> {
1442        let params = json!({
1443            "threadId": thread_id,
1444            "expectedTurnId": expected_turn_id,
1445            "input": input,
1446        });
1447        let result = self.request("turn/steer", params).await?;
1448        result
1449            .get("turnId")
1450            .and_then(Value::as_str)
1451            .map(str::to_string)
1452            .ok_or_else(|| Error::AppServerProtocol {
1453                message: "turn/steer returned no turn id".into(),
1454            })
1455    }
1456
1457    /// Stop a running turn (`turn/interrupt`). The turn then ends with a
1458    /// `turn/completed` notification whose status is
1459    /// [`TurnStatus::Interrupted`].
1460    ///
1461    /// With no active turn the server fails the request with `no active turn
1462    /// to interrupt`, and with a different one with `expected active turn id
1463    /// ...`; both are [`Error::AppServerRpc`].
1464    ///
1465    /// # Errors
1466    ///
1467    /// As [`request`](Self::request).
1468    pub async fn turn_interrupt(&self, thread_id: &str, turn_id: &str) -> Result<()> {
1469        let params = json!({ "threadId": thread_id, "turnId": turn_id });
1470        self.request("turn/interrupt", params).await.map(|_| ())
1471    }
1472}
1473
1474/// Builds and starts an [`AppServer`].
1475///
1476/// Created by [`AppServer::builder`].
1477#[derive(Debug, Clone)]
1478pub struct AppServerBuilder<'a> {
1479    codex: &'a Codex,
1480    client_name: String,
1481    client_version: String,
1482    opt_out: Vec<String>,
1483    capabilities: Map<String, Value>,
1484    limits: Limits,
1485    transport: AppServerTransport,
1486}
1487
1488impl<'a> AppServerBuilder<'a> {
1489    /// Name and version reported to the server in `initialize`. The server
1490    /// includes them in its user agent. Defaults to `codex-wrapper` and this
1491    /// crate's version.
1492    #[must_use]
1493    pub fn client_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
1494        self.client_name = name.into();
1495        self.client_version = version.into();
1496        self
1497    }
1498
1499    /// Ask the server not to send a notification method on this connection,
1500    /// by exact name. Streaming deltas (`item/agentMessage/delta`) are the
1501    /// usual candidate for a caller that only needs completed items.
1502    #[must_use]
1503    pub fn opt_out_notification(mut self, method: impl Into<String>) -> Self {
1504        self.opt_out.push(method.into());
1505        self
1506    }
1507
1508    /// Set a field of the `initialize` request's `capabilities` by its
1509    /// protocol name, replacing an earlier value for the same name. Sent as
1510    /// given and not checked, except `optOutNotificationMethods`, which is
1511    /// combined with [`opt_out_notification`](Self::opt_out_notification) as
1512    /// the [module documentation](self#capabilities) describes.
1513    #[must_use]
1514    pub fn capability(mut self, name: impl Into<String>, value: Value) -> Self {
1515        self.capabilities.insert(name.into(), value);
1516        self
1517    }
1518
1519    /// Set the `experimentalApi` capability, which asks the server to allow
1520    /// methods and fields it marks experimental. Shorthand for
1521    /// `capability("experimentalApi", Value::Bool(enabled))`.
1522    #[must_use]
1523    pub fn experimental_api(self, enabled: bool) -> Self {
1524        self.capability("experimentalApi", Value::Bool(enabled))
1525    }
1526
1527    /// The most bytes one line from the server may hold, newline included. A
1528    /// longer line ends the session with [`Error::AppServerLimitExceeded`]
1529    /// once the limit is reached, without buffering the rest. Unlimited by
1530    /// default. Attached WebSocket mode counts JSON payload bytes instead.
1531    #[must_use]
1532    pub fn max_frame_bytes(mut self, bytes: usize) -> Self {
1533        self.limits.frame_bytes = Some(bytes);
1534        self
1535    }
1536
1537    /// The most notifications and server requests that may wait for
1538    /// [`AppServer::next_message`]. One more ends the session. Unlimited by
1539    /// default.
1540    #[must_use]
1541    pub fn max_queued_messages(mut self, messages: usize) -> Self {
1542        self.limits.queued_messages = Some(messages);
1543        self
1544    }
1545
1546    /// The most bytes, counted as each message's line plus its newline, that
1547    /// may wait for [`AppServer::next_message`]. Attached mode counts JSON
1548    /// payload bytes without WebSocket framing. Unlimited by default.
1549    #[must_use]
1550    pub fn max_queued_bytes(mut self, bytes: usize) -> Self {
1551        self.limits.queued_bytes = Some(bytes);
1552        self
1553    }
1554
1555    /// The most lines that may wait to be written to the server, the one being
1556    /// written included. Unlimited by default.
1557    #[must_use]
1558    pub fn max_writer_queue_messages(mut self, messages: usize) -> Self {
1559        self.limits.writer_messages = Some(messages);
1560        self
1561    }
1562
1563    /// The most bytes, newlines included, that may wait to be written to the
1564    /// server, the line being written included. Attached mode counts JSON
1565    /// payload bytes without WebSocket framing. Unlimited by default.
1566    #[must_use]
1567    pub fn max_writer_queue_bytes(mut self, bytes: usize) -> Self {
1568        self.limits.writer_bytes = Some(bytes);
1569        self
1570    }
1571
1572    /// Attach to an existing server over a Unix WebSocket connection.
1573    ///
1574    /// Spawns no process and never signals the shared server. The endpoint
1575    /// must be selected explicitly. Verified with CLI 0.163.0; this provider
1576    /// transport is experimental. Reconnect by creating a fresh connection
1577    /// and explicitly reconciling threads and approvals; requests are not replayed.
1578    #[cfg(unix)]
1579    #[must_use]
1580    pub fn connect_unix(mut self, socket: impl Into<PathBuf>) -> Self {
1581        self.transport = AppServerTransport::UnixSocket {
1582            socket: socket.into(),
1583        };
1584        self
1585    }
1586
1587    /// The `params` of the `initialize` request [`start`](Self::start) sends.
1588    ///
1589    /// # Errors
1590    ///
1591    /// [`Error::AppServerConfig`] if `optOutNotificationMethods` was set
1592    /// through [`capability`](Self::capability) to something other than an
1593    /// array of strings or `null`.
1594    pub fn initialize_params(&self) -> Result<Value> {
1595        let mut params = json!({
1596            "clientInfo": { "name": self.client_name, "version": self.client_version }
1597        });
1598        let mut capabilities = self.capabilities.clone();
1599        if let Some(given) = capabilities.get(OPT_OUT_KEY) {
1600            let valid = match given {
1601                Value::Null => true,
1602                Value::Array(items) => items.iter().all(Value::is_string),
1603                _ => false,
1604            };
1605            if !valid {
1606                return Err(Error::AppServerConfig {
1607                    message: format!(
1608                        "capabilities.{OPT_OUT_KEY} must be an array of method names or null"
1609                    ),
1610                });
1611            }
1612        }
1613        if !self.opt_out.is_empty() {
1614            let mut methods: Vec<String> = Vec::new();
1615            let given = capabilities.get(OPT_OUT_KEY).and_then(Value::as_array);
1616            let given = given.into_iter().flatten().filter_map(Value::as_str);
1617            for method in given.chain(self.opt_out.iter().map(String::as_str)) {
1618                if !methods.iter().any(|seen| seen == method) {
1619                    methods.push(method.to_string());
1620                }
1621            }
1622            capabilities.insert(OPT_OUT_KEY.into(), json!(methods));
1623        }
1624        if !capabilities.is_empty() {
1625            params["capabilities"] = Value::Object(capabilities);
1626        }
1627        Ok(params)
1628    }
1629
1630    /// The owned-server arguments: `app-server --listen stdio://`. Empty for
1631    /// an attached connection, which spawns no command.
1632    ///
1633    /// `--listen stdio://` is the default transport. It is passed anyway so a
1634    /// change of default cannot move this client onto a socket.
1635    #[must_use]
1636    pub fn args(&self) -> Vec<String> {
1637        match &self.transport {
1638            AppServerTransport::Stdio => {
1639                vec!["app-server".into(), "--listen".into(), "stdio://".into()]
1640            }
1641            #[cfg(unix)]
1642            AppServerTransport::UnixSocket { .. } => Vec::new(),
1643        }
1644    }
1645
1646    /// Reject a setting that cannot work, before anything is spawned.
1647    fn validate(&self) -> Result<Value> {
1648        #[cfg(unix)]
1649        if let AppServerTransport::UnixSocket { socket } = &self.transport
1650            && socket.as_os_str().is_empty()
1651        {
1652            return Err(Error::AppServerConfig {
1653                message: "the socket path is empty".into(),
1654            });
1655        }
1656        self.initialize_params()
1657    }
1658
1659    /// The command [`start`](Self::start) will run, as a copy-pasteable shell
1660    /// string, including the client's global args. Empty for an attached connection.
1661    #[must_use]
1662    pub fn to_command_string(&self) -> String {
1663        if !self.transport.owns_server() {
1664            return String::new();
1665        }
1666        crate::exec::command_string(self.codex, self.args())
1667    }
1668
1669    /// Spawn `codex app-server` and complete the handshake.
1670    ///
1671    /// Owned mode runs `codex [global args] app-server --listen stdio://`. The
1672    /// client's binary, environment, working directory, process-group policy,
1673    /// `die_with_parent`, and `on_spawn` observer apply to that process. The
1674    /// handshake is bounded by the client's timeout, when set.
1675    ///
1676    /// # Errors
1677    ///
1678    /// [`Error::AppServerConfig`] for an invalid setting, before anything is
1679    /// spawned. [`Error::Io`] if the process cannot be spawned. If the process
1680    /// exits before the handshake finishes, the failure is classified from its
1681    /// stderr as any failed command is, so a rejected `-c` key is
1682    /// [`Error::Config`]. Otherwise the handshake's own error.
1683    pub async fn start(self) -> Result<AppServer> {
1684        let initialize_params = self.validate()?;
1685        #[cfg(unix)]
1686        if let AppServerTransport::UnixSocket { socket } = &self.transport {
1687            let socket = socket.clone();
1688            return self.start_unix(socket, initialize_params).await;
1689        }
1690        let codex = self.codex;
1691        let process = self.transport.process_name();
1692        let operation_args = self.args();
1693        let span = crate::exec::command_span("codex.app_server", codex, &operation_args);
1694        let args = crate::exec::assemble_args(codex, operation_args);
1695        let command_text = format!("{} {}", codex.binary.display(), args.join(" "));
1696        debug!(
1697            arg_count = args.len(),
1698            owns_server = self.transport.owns_server(),
1699            "starting codex app-server"
1700        );
1701
1702        let mut outcome = SpanOutcome::start(span.clone());
1703        let mut command =
1704            crate::exec::child_command(&codex.binary, codex.process_group, codex.die_with_parent);
1705        command.args(&args);
1706        command.stdin(std::process::Stdio::piped());
1707        command.stdout(std::process::Stdio::piped());
1708        command.stderr(std::process::Stdio::piped());
1709        if let Some(dir) = &codex.working_dir {
1710            command.current_dir(dir);
1711        }
1712        crate::exec::apply_child_environment(&mut command, codex.clear_env, &codex.env);
1713
1714        let mut child = match command.spawn() {
1715            Ok(child) => child,
1716            Err(e) => {
1717                outcome.settle("error", None);
1718                return Err(Error::Io {
1719                    message: format!("failed to spawn {process}: {e}"),
1720                    source: e,
1721                    working_dir: codex.working_dir.clone(),
1722                });
1723            }
1724        };
1725        let group = crate::exec::arm_and_notify(
1726            codex.process_group,
1727            codex.termination_signal,
1728            child.id(),
1729            codex.on_spawn.as_ref(),
1730        );
1731        let pid = child.id();
1732
1733        let stdin = child.stdin.take().expect("stdin was configured as piped");
1734        let stdout = child.stdout.take().expect("stdout was configured as piped");
1735        let stderr = child.stderr.take().expect("stderr was configured as piped");
1736
1737        let (events_tx, events_rx) = mpsc::unbounded_channel();
1738        let (writer_tx, writer_rx) = mpsc::unbounded_channel();
1739        // Only owned mode creates a process kill target.
1740        let shared = Arc::new(Shared::new(
1741            events_tx,
1742            Some(KillTarget {
1743                pid,
1744                group: codex.process_group,
1745                #[cfg(windows)]
1746                handle: child.raw_handle().map(|handle| handle as usize),
1747            }),
1748            self.limits,
1749            process,
1750        ));
1751
1752        let reader = tokio::spawn(read_stdout(
1753            stdout,
1754            Arc::clone(&shared),
1755            codex.output_limit,
1756            codex.working_dir.clone(),
1757        ));
1758        let stderr_reader = tokio::spawn(drain_stderr(stderr, Arc::clone(&shared)));
1759        let writer = tokio::spawn(write_stdin(stdin, writer_rx, Arc::clone(&shared)));
1760
1761        let handle = AppServerHandle {
1762            shared,
1763            writer: writer_tx,
1764            timeout: codex.timeout,
1765        };
1766        let mut server = AppServer {
1767            handle,
1768            events: events_rx,
1769            finished: false,
1770            child: Some(child),
1771            tasks: vec![
1772                reader.abort_handle(),
1773                stderr_reader.abort_handle(),
1774                writer.abort_handle(),
1775            ],
1776            group,
1777            outcome,
1778            termination_grace: codex.termination_grace,
1779            working_dir: codex.working_dir.clone(),
1780            command: command_text,
1781            info: ServerInfo::default(),
1782            transport: self.transport,
1783        };
1784
1785        let handshake = initialize(&server.handle, initialize_params)
1786            .instrument(span)
1787            .await;
1788        match handshake {
1789            Ok(info) => {
1790                server.info = info;
1791                Ok(server)
1792            }
1793            Err(error) => Err(server.abandon(error).await),
1794        }
1795    }
1796}
1797
1798#[cfg(unix)]
1799impl AppServerBuilder<'_> {
1800    async fn start_unix(self, socket: PathBuf, params: Value) -> Result<AppServer> {
1801        let codex = self.codex;
1802        let span = tracing::info_span!("codex.app_server", transport = "unix");
1803        let outcome = SpanOutcome::start(span.clone());
1804        let max = match (self.limits.frame_bytes, codex.output_limit) {
1805            (Some(a), Some(b)) => Some(a.min(b)),
1806            (a, b) => a.or(b),
1807        };
1808        // Both aggregate-message and fragment limits are needed: a peer can
1809        // split a large message across individually small WebSocket frames.
1810        let config = WebSocketConfig::default()
1811            .max_frame_size(max)
1812            .max_message_size(max)
1813            .write_buffer_size(0);
1814        let connect = async {
1815            let stream = tokio::net::UnixStream::connect(&socket)
1816                .await
1817                .map_err(|source| Error::Io {
1818                    message: "failed to connect to app-server Unix socket".into(),
1819                    source,
1820                    working_dir: codex.working_dir.clone(),
1821                })?;
1822            let (stream, _) = tokio_tungstenite::client_async_with_config(
1823                "ws://localhost/",
1824                stream,
1825                Some(config),
1826            )
1827            .await
1828            .map_err(|error| Error::AppServerProtocol {
1829                message: format!("app-server WebSocket handshake failed: {error}"),
1830            })?;
1831            Ok::<_, Error>(stream)
1832        };
1833        let stream = if let Some(limit) = codex.timeout {
1834            tokio::time::timeout(limit, connect)
1835                .await
1836                .map_err(|_| Error::Timeout {
1837                    timeout_seconds: limit.as_secs(),
1838                })??
1839        } else {
1840            connect.await?
1841        };
1842        let (events_tx, events_rx) = mpsc::unbounded_channel();
1843        let (writer_tx, writer_rx) = mpsc::unbounded_channel();
1844        let mut state = Shared::new(events_tx, None, self.limits, self.transport.process_name());
1845        state.newline_delimited = false;
1846        state.stderr_done.store(true, Ordering::Release);
1847        let shared = Arc::new(state);
1848        let task = tokio::spawn(socket_io(
1849            stream,
1850            writer_rx,
1851            Arc::clone(&shared),
1852            codex.output_limit,
1853            codex.termination_grace,
1854        ));
1855        // Construct the owner before awaiting initialize: cancelling start()
1856        // must abort its I/O task even if cloned internal state survives.
1857        let mut server = AppServer {
1858            handle: AppServerHandle {
1859                shared,
1860                writer: writer_tx,
1861                timeout: codex.timeout,
1862            },
1863            events: events_rx,
1864            finished: false,
1865            child: None,
1866            tasks: vec![task.abort_handle()],
1867            group: GroupKillGuard::new(None, codex.termination_signal),
1868            outcome,
1869            termination_grace: codex.termination_grace,
1870            working_dir: codex.working_dir.clone(),
1871            command: String::new(),
1872            info: ServerInfo::default(),
1873            transport: self.transport,
1874        };
1875        match initialize(&server.handle, params).instrument(span).await {
1876            Ok(info) => {
1877                server.info = info;
1878                Ok(server)
1879            }
1880            Err(error) => Err(server.abandon(error).await),
1881        }
1882    }
1883}
1884
1885#[cfg(unix)]
1886async fn socket_io(
1887    stream: tokio_tungstenite::WebSocketStream<tokio::net::UnixStream>,
1888    mut lines: mpsc::UnboundedReceiver<Outgoing>,
1889    shared: Arc<Shared>,
1890    output_limit: Option<usize>,
1891    close_grace: Duration,
1892) {
1893    let (mut sink, mut source) = stream.split();
1894    let acknowledge_close = AtomicBool::new(false);
1895    let read = async {
1896        let mut captured = 0usize;
1897        loop {
1898            let next = tokio::select! {
1899                biased;
1900                () = shared.wait_closed() => return,
1901                next = source.next() => next,
1902            };
1903            let reason = match next {
1904                Some(Ok(WsMessage::Text(text))) => {
1905                    captured = captured.saturating_add(text.len());
1906                    if let Some(limit) = output_limit
1907                        && captured > limit
1908                    {
1909                        Some(Closed::OutputLimit { limit_bytes: limit })
1910                    } else {
1911                        route_bytes(&text, text.len(), &shared).err()
1912                    }
1913                }
1914                // Tungstenite handles pong and close replies; reading keeps
1915                // those control frames progressing independently of events.
1916                Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => None,
1917                Some(Ok(WsMessage::Close(_))) => {
1918                    acknowledge_close.store(true, Ordering::Release);
1919                    Some(Closed::Eof)
1920                }
1921                None => Some(Closed::Eof),
1922                Some(Ok(_)) => Some(Closed::Broken(
1923                    "app-server sent a non-text WebSocket message".into(),
1924                )),
1925                Some(Err(tokio_tungstenite::tungstenite::Error::Capacity(_))) => {
1926                    if let Some(limit) = output_limit
1927                        && shared.frame_bytes.is_none_or(|frame| limit <= frame)
1928                    {
1929                        Some(Closed::OutputLimit { limit_bytes: limit })
1930                    } else if let Some(max) = shared.frame_bytes {
1931                        Some(Closed::Limit {
1932                            limit: AppServerLimit::FrameBytes,
1933                            max,
1934                        })
1935                    } else {
1936                        Some(Closed::Broken("WebSocket capacity exceeded".into()))
1937                    }
1938                }
1939                Some(Err(error)) => Some(Closed::Broken(format!(
1940                    "app-server WebSocket failed: {error}"
1941                ))),
1942            };
1943            if let Some(reason) = reason {
1944                shared.fail(reason);
1945                return;
1946            }
1947        }
1948    };
1949    let write = async {
1950        loop {
1951            let next = tokio::select! {
1952                biased;
1953                () = shared.wait_closed() => break,
1954                next = lines.recv() => next,
1955            };
1956            let Some(Outgoing::Line(line)) = next else {
1957                break;
1958            };
1959            let text = String::from_utf8(line.bytes.clone()).expect("serialized JSON is UTF-8");
1960            let result = tokio::select! {
1961                biased;
1962                () = shared.wait_closed() => break,
1963                result = sink.send(WsMessage::Text(text.into())) => result,
1964            };
1965            if let Err(error) = result {
1966                shared.fail(Closed::Broken(format!(
1967                    "failed to write app-server WebSocket: {error}"
1968                )));
1969                break;
1970            }
1971        }
1972        if acknowledge_close.load(Ordering::Acquire) {
1973            // Reading Close queues the reply inside tungstenite. Waiters have
1974            // already failed; bound the remaining protocol cleanup separately.
1975            let _ = tokio::time::timeout(close_grace, sink.flush()).await;
1976        }
1977    };
1978    // Neither half depends on the application draining the event queue. On
1979    // failure or owner closure both futures wake and release the socket.
1980    tokio::join!(read, write);
1981}
1982
1983async fn initialize(handle: &AppServerHandle, params: Value) -> Result<ServerInfo> {
1984    let result = handle.request("initialize", params).await?;
1985    let info = serde_json::from_value(result).map_err(|e| Error::AppServerProtocol {
1986        message: format!("initialize returned an unexpected response: {e}"),
1987    })?;
1988    handle.notify("initialized", Value::Null)?;
1989    Ok(info)
1990}
1991
1992/// Which process a fatal stream error stops.
1993#[derive(Clone, Copy)]
1994struct KillTarget {
1995    pid: Option<u32>,
1996    group: bool,
1997    #[cfg(windows)]
1998    handle: Option<usize>,
1999}
2000
2001impl KillTarget {
2002    /// Stop the server now. The stream is unusable and nothing will read what
2003    /// the server writes next, so leaving it running would only fill the pipe.
2004    ///
2005    /// Unix signals the owned group or child. Windows terminates the owned
2006    /// process using its still-valid native handle.
2007    fn signal(self) -> bool {
2008        #[cfg(unix)]
2009        if let Some(pid) = self.pid {
2010            if self.group {
2011                return crate::exec::signal_group(pid, libc::SIGKILL);
2012            } else if let Ok(pid) = i32::try_from(pid) {
2013                // SAFETY: `kill` on a pid this client spawned. If the child
2014                // has already been reaped the call fails, which is the state
2015                // we want.
2016                return unsafe { libc::kill(pid, libc::SIGKILL) == 0 };
2017            }
2018        }
2019        #[cfg(windows)]
2020        if let Some(handle) = self.handle {
2021            // SAFETY: this is the owned child's handle, not a reopened PID.
2022            // The Shared kill lock is held across this call and revoked before
2023            // reaping or dropping the child can invalidate the handle.
2024            return unsafe {
2025                windows_sys::Win32::System::Threading::TerminateProcess(handle as _, 1) != 0
2026            };
2027        }
2028        #[cfg(not(unix))]
2029        let _ = (self.pid, self.group);
2030        false
2031    }
2032}
2033
2034/// Read the server's stdout: route answers to waiting requests and everything
2035/// else to the event queue.
2036async fn read_stdout(
2037    stdout: ChildStdout,
2038    shared: Arc<Shared>,
2039    output_limit: Option<usize>,
2040    working_dir: Option<PathBuf>,
2041) {
2042    let mut reader = BufReader::new(stdout);
2043    let mut captured = 0usize;
2044    let reason = loop {
2045        let line = match read_frame(
2046            &mut reader,
2047            &mut captured,
2048            output_limit,
2049            shared.frame_bytes,
2050            &working_dir,
2051        )
2052        .await
2053        {
2054            Ok(Some(line)) => line,
2055            Ok(None) => {
2056                shared.stderr_settled().await;
2057                break Closed::Eof;
2058            }
2059            Err(reason) => {
2060                shared.fatal(reason.clone());
2061                break reason;
2062            }
2063        };
2064        let (line, wire_bytes) = line;
2065        if !line.trim_start().starts_with('{') {
2066            debug!(
2067                bytes = line.len(),
2068                "ignoring a non-JSON line from codex app-server"
2069            );
2070            continue;
2071        }
2072        if let Err(reason) = route_bytes(&line, wire_bytes, &shared) {
2073            shared.fatal(reason.clone());
2074            break reason;
2075        }
2076    };
2077    shared.fail(reason);
2078}
2079
2080/// Read one line, as [`crate::streaming`] reads one, but also bounded by
2081/// `frame_limit`. The check comes before each chunk is copied, so a line that
2082/// never ends is rejected having buffered at most the limit.
2083async fn read_frame<R: AsyncBufRead + Unpin>(
2084    reader: &mut R,
2085    captured: &mut usize,
2086    output_limit: Option<usize>,
2087    frame_limit: Option<usize>,
2088    working_dir: &Option<PathBuf>,
2089) -> std::result::Result<Option<(String, usize)>, Closed> {
2090    let mut line = Vec::new();
2091    let mut wire_bytes = 0;
2092    loop {
2093        let available = reader.fill_buf().await.map_err(|source| {
2094            let error = Error::Io {
2095                message: format!("failed to read stdout line: {source}"),
2096                source,
2097                working_dir: working_dir.clone(),
2098            };
2099            Closed::Broken(error.to_string())
2100        })?;
2101        if available.is_empty() {
2102            if line.is_empty() {
2103                return Ok(None);
2104            }
2105            break;
2106        }
2107        let take = available
2108            .iter()
2109            .position(|byte| *byte == b'\n')
2110            .map_or(available.len(), |index| index + 1);
2111        if let Some(limit) = output_limit
2112            && captured.saturating_add(take) > limit
2113        {
2114            return Err(Closed::OutputLimit { limit_bytes: limit });
2115        }
2116        if let Some(max) = frame_limit
2117            && line.len().saturating_add(take) > max
2118        {
2119            return Err(Closed::Limit {
2120                limit: AppServerLimit::FrameBytes,
2121                max,
2122            });
2123        }
2124        line.extend_from_slice(&available[..take]);
2125        wire_bytes += take;
2126        *captured = captured.saturating_add(take);
2127        let complete = line.last() == Some(&b'\n');
2128        reader.consume(take);
2129        if complete {
2130            line.pop();
2131            break;
2132        }
2133    }
2134    if line.last() == Some(&b'\r') {
2135        line.pop();
2136    }
2137    String::from_utf8(line)
2138        .map(|line| Some((line, wire_bytes)))
2139        .map_err(|_| Closed::Broken("io error: failed to decode stdout line".into()))
2140}
2141
2142/// Classify one line from the server and deliver it.
2143#[cfg(all(test, unix))]
2144fn route(line: &str, shared: &Shared) -> std::result::Result<(), Closed> {
2145    route_bytes(line, line.len() + 1, shared)
2146}
2147
2148fn route_bytes(line: &str, bytes: usize, shared: &Shared) -> std::result::Result<(), Closed> {
2149    let value: Value = serde_json::from_str(line).map_err(|e| {
2150        let head: String = line.chars().take(120).collect();
2151        Closed::Broken(format!("codex app-server sent invalid JSON ({e}): {head}"))
2152    })?;
2153    let method = value.get("method").and_then(Value::as_str);
2154    let id = value.get("id");
2155    match (method, id) {
2156        (Some(method), Some(id)) => {
2157            let Ok(id) = serde_json::from_value::<RequestId>(id.clone()) else {
2158                warn!(
2159                    method_bytes = method.len(),
2160                    "ignoring a server request with an unusable id"
2161                );
2162                return Ok(());
2163            };
2164            let request = ServerRequest {
2165                id,
2166                method: method.to_string(),
2167                params: value.get("params").cloned().unwrap_or(Value::Null),
2168            };
2169            shared.deliver(ServerMessage::Request(request), bytes)?;
2170        }
2171        (Some(method), None) => {
2172            let notification = Notification {
2173                method: method.to_string(),
2174                params: value.get("params").cloned().unwrap_or(Value::Null),
2175            };
2176            shared.deliver(ServerMessage::Notification(notification), bytes)?;
2177        }
2178        (None, Some(id)) if value.get("result").is_some() || value.get("error").is_some() => {
2179            deliver_answer(&value, id, shared);
2180        }
2181        (None, Some(id)) => {
2182            // Shaped like an answer, but neither a result nor an error. If it
2183            // names a waiting request, fail that request rather than leave it
2184            // waiting for an answer that will not come.
2185            let waiter = id
2186                .as_i64()
2187                .and_then(|id| locked(&shared.state).pending.remove(&id));
2188            match waiter {
2189                Some(waiter) => {
2190                    let _ = waiter.send(Reply::Malformed);
2191                }
2192                None => warn!("ignoring an answer with neither result nor error"),
2193            }
2194        }
2195        _ => warn!("ignoring a JSON object from codex app-server that is not a message"),
2196    }
2197    Ok(())
2198}
2199
2200fn deliver_answer(value: &Value, id: &Value, shared: &Shared) {
2201    let Some(id) = id.as_i64() else {
2202        // The server answers a request it could not parse with a null id.
2203        debug!("ignoring an answer with no request id");
2204        return;
2205    };
2206    let waiter = locked(&shared.state).pending.remove(&id);
2207    let Some(waiter) = waiter else {
2208        // The request was cancelled or timed out before the answer arrived.
2209        debug!(id, "ignoring an answer nobody is waiting for");
2210        return;
2211    };
2212    let reply = match value.get("error") {
2213        Some(error) => Reply::Rpc(RpcFailure {
2214            code: error.get("code").and_then(Value::as_i64).unwrap_or(0),
2215            message: error
2216                .get("message")
2217                .and_then(Value::as_str)
2218                .unwrap_or_default()
2219                .to_string(),
2220            data: error.get("data").cloned(),
2221        }),
2222        None => Reply::Result(value.get("result").cloned().unwrap_or(Value::Null)),
2223    };
2224    let _ = waiter.send(reply);
2225}
2226
2227/// Drain stderr for the life of the server. The server logs a lot there, and a
2228/// pipe nobody reads fills and stops it.
2229async fn drain_stderr(mut stderr: ChildStderr, shared: Arc<Shared>) {
2230    let mut buffer = [0u8; 4096];
2231    loop {
2232        match stderr.read(&mut buffer).await {
2233            Ok(0) | Err(_) => {
2234                shared.stderr_done.store(true, Ordering::Release);
2235                shared.stderr_finished.notify_waiters();
2236                break;
2237            }
2238            Ok(read) => {
2239                let mut tail = locked(&shared.stderr_tail);
2240                tail.extend_from_slice(&buffer[..read]);
2241                if tail.len() > STDERR_TAIL_BYTES {
2242                    let excess = tail.len() - STDERR_TAIL_BYTES;
2243                    tail.drain(..excess);
2244                }
2245            }
2246        }
2247    }
2248}
2249
2250/// Write queued lines to the server's stdin, one whole line at a time.
2251///
2252/// Writing happens here, not in the request future, so a request that is
2253/// dropped part way through cannot leave half a line on the wire.
2254async fn write_stdin<W: AsyncWrite + Unpin>(
2255    mut stdin: W,
2256    mut lines: mpsc::UnboundedReceiver<Outgoing>,
2257    shared: Arc<Shared>,
2258) {
2259    loop {
2260        let outgoing = tokio::select! {
2261            biased;
2262            () = shared.wait_closed() => break,
2263            outgoing = lines.recv() => outgoing,
2264        };
2265        let Some(Outgoing::Line(line)) = outgoing else {
2266            break;
2267        };
2268        let written = tokio::select! {
2269            biased;
2270            () = shared.wait_closed() => break,
2271            result = async { stdin.write_all(&line.bytes).await?; stdin.flush().await } => result,
2272        };
2273        if let Err(error) = written {
2274            if error.kind() == std::io::ErrorKind::BrokenPipe {
2275                // Preserve the reader's native startup-error classification.
2276                debug!("codex app-server closed its stdin");
2277            } else {
2278                shared.fatal(Closed::Broken(format!(
2279                    "failed to write to codex app-server stdin: {error}"
2280                )));
2281            }
2282            break;
2283        }
2284    }
2285    // Dropping the receiver also drops each queued reservation.
2286    lines.close();
2287    while lines.try_recv().is_ok() {}
2288
2289    // Dropping stdin closes the pipe, which the server treats as the end of
2290    // its input.
2291}
2292
2293/// A running `codex app-server`.
2294///
2295/// Requests go through [`AppServerHandle`], which this type dereferences to,
2296/// so `server.turn_start(..)` works directly. [`handle`](Self::handle) gives a
2297/// clone that can be moved to another task. Events are read with
2298/// [`next_message`](Self::next_message), which needs `&mut self`.
2299///
2300/// Dropping the value kills the server's process group without waiting; use
2301/// [`shutdown`](Self::shutdown) or [`terminate`](Self::terminate) to stop it
2302/// and wait. An attached connection closes only its socket; the shared server
2303/// and its turns remain the server owner's responsibility.
2304pub struct AppServer {
2305    handle: AppServerHandle,
2306    events: mpsc::UnboundedReceiver<Event>,
2307    finished: bool,
2308    child: Option<Child>,
2309    tasks: Vec<tokio::task::AbortHandle>,
2310    group: GroupKillGuard,
2311    outcome: SpanOutcome,
2312    termination_grace: Duration,
2313    working_dir: Option<PathBuf>,
2314    command: String,
2315    info: ServerInfo,
2316    transport: AppServerTransport,
2317}
2318
2319impl std::fmt::Debug for AppServer {
2320    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2321        f.debug_struct("AppServer")
2322            .field("pid", &self.pid())
2323            .field("transport", &self.transport)
2324            .field("info", &self.info)
2325            .finish_non_exhaustive()
2326    }
2327}
2328
2329impl Deref for AppServer {
2330    type Target = AppServerHandle;
2331
2332    fn deref(&self) -> &AppServerHandle {
2333        &self.handle
2334    }
2335}
2336
2337impl AppServer {
2338    /// Start configuring a server for `codex`.
2339    #[must_use]
2340    pub fn builder(codex: &Codex) -> AppServerBuilder<'_> {
2341        AppServerBuilder {
2342            codex,
2343            client_name: "codex-wrapper".to_string(),
2344            client_version: env!("CARGO_PKG_VERSION").to_string(),
2345            opt_out: Vec::new(),
2346            capabilities: Map::new(),
2347            limits: Limits::default(),
2348            transport: AppServerTransport::Stdio,
2349        }
2350    }
2351
2352    /// What the server reported about itself during the handshake.
2353    #[must_use]
2354    pub fn server_info(&self) -> &ServerInfo {
2355        &self.info
2356    }
2357
2358    /// How this client reaches the server, and whether it owns it.
2359    #[must_use]
2360    pub fn transport(&self) -> &AppServerTransport {
2361        &self.transport
2362    }
2363
2364    /// The owned server's process ID while running. `None` for an attached
2365    /// connection, which neither starts nor owns a process.
2366    #[must_use]
2367    pub fn pid(&self) -> Option<u32> {
2368        self.child.as_ref().and_then(Child::id)
2369    }
2370
2371    /// A cloneable handle for sending requests from other tasks.
2372    #[must_use]
2373    pub fn handle(&self) -> AppServerHandle {
2374        self.handle.clone()
2375    }
2376
2377    /// The next notification or server request, in the order the server sent
2378    /// them.
2379    ///
2380    /// Returns `Ok(None)` once the server's output has ended, after every
2381    /// earlier message has been returned. That is how a server that exited on
2382    /// its own looks; [`shutdown`](Self::shutdown) then reports its exit
2383    /// status. Cancel-safe: dropping the future loses no message.
2384    ///
2385    /// # Errors
2386    ///
2387    /// [`Error::OutputLimitExceeded`], [`Error::AppServerLimitExceeded`], or
2388    /// [`Error::AppServerProtocol`] when the stream became unusable. The owned
2389    /// process has been killed by then. The error
2390    /// is returned once; later calls return `Ok(None)`.
2391    pub async fn next_message(&mut self) -> Result<Option<ServerMessage>> {
2392        if self.finished {
2393            return Ok(None);
2394        }
2395        match self.events.recv().await {
2396            Some(Event::Message(message, bytes)) => {
2397                self.handle.shared.inbound.release(bytes);
2398                Ok(Some(message))
2399            }
2400            Some(Event::Closed(reason)) => {
2401                self.finished = true;
2402                match reason {
2403                    Closed::Eof | Closed::Terminated => Ok(None),
2404                    reason => {
2405                        // Already killed on Unix, where the reader signals
2406                        // the group as soon as the stream fails. This covers
2407                        // the platforms that cannot.
2408                        if let Some(child) = &mut self.child
2409                            && child.start_kill().is_ok()
2410                        {
2411                            self.handle
2412                                .shared
2413                                .hard_kill_sent
2414                                .store(true, Ordering::Relaxed);
2415                        }
2416                        Err(self.handle.shared.error_for(&reason, None))
2417                    }
2418                }
2419            }
2420            None => {
2421                self.finished = true;
2422                Ok(None)
2423            }
2424        }
2425    }
2426
2427    /// End the session and wait for the server to exit.
2428    ///
2429    /// Closes the owned server's stdin and waits up to the client's
2430    /// [termination grace](crate::CodexBuilder::termination_grace). A clean
2431    /// exit without a stop action returns `Ok(())`. If the wait expires,
2432    /// the wrapper uses the same stop policy as [`terminate`](Self::terminate).
2433    /// If the leader has already exited cleanly at the first check after the
2434    /// timeout, shutdown can return `Ok(())` even if it signals the rest of
2435    /// the group.
2436    /// An attached connection closes its own socket and returns `Ok(())`.
2437    /// Pending requests fail when either kind of connection closes.
2438    ///
2439    /// # Errors
2440    ///
2441    /// - A nonzero exit without a stop action is classified from stderr
2442    ///   as [`Error::CommandFailed`] or one of its refinements.
2443    /// - [`Error::AppServerSignaled`] carries the native status if the server
2444    ///   died from a signal without wrapper intervention.
2445    /// - [`Error::AppServerForcedShutdown`] carries the stop action and
2446    ///   native status when the wrapper intervened on the server itself,
2447    ///   even if the status is successful. The server has been reaped.
2448    /// - [`Error::Io`] reports a failure to stop or reap the server.
2449    pub async fn shutdown(mut self) -> Result<()> {
2450        // The child is about to be reaped, after which its pid is not ours to
2451        // signal.
2452        self.handle.shared.revoke_kill();
2453        // Stop admission now, but let owned stdio flush already accepted
2454        // messages before Close. The termination grace bounds a stalled writer.
2455        self.handle
2456            .shared
2457            .end(Closed::Terminated, self.child.is_none());
2458        let Some(child) = &mut self.child else {
2459            self.outcome.settle("ok", None);
2460            return Ok(());
2461        };
2462        let _ = self.handle.writer.send(Outgoing::Close);
2463        let (status, action) =
2464            match tokio::time::timeout(self.termination_grace, child.wait()).await {
2465                Ok(Ok(status)) => {
2466                    self.group.disarm();
2467                    (status, None)
2468                }
2469                Ok(Err(error)) => {
2470                    #[cfg(unix)]
2471                    if error.raw_os_error() == Some(libc::ECHILD) {
2472                        self.group.disarm();
2473                    }
2474                    self.outcome.settle("error", None);
2475                    return Err(self.wait_error(error));
2476                }
2477                Err(_) => {
2478                    self.handle.shared.fail(Closed::Terminated);
2479                    crate::exec::terminate_and_reap(child, &mut self.group, self.termination_grace)
2480                        .await
2481                        .map_err(|error| {
2482                            self.outcome.settle("cleanup_failed", None);
2483                            self.wait_error(error)
2484                        })?
2485                }
2486            };
2487        let action = if self.handle.shared.hard_kill_sent.load(Ordering::Relaxed)
2488            && crate::exec::hard_kill_matches(status)
2489        {
2490            Some(ShutdownAction::Kill)
2491        } else {
2492            action
2493        };
2494        self.handle.shared.stderr_settled().await;
2495        self.handle.shared.fail(Closed::Terminated);
2496        let code = status.code();
2497        if action.is_none() && status.success() {
2498            self.outcome.settle("ok", code);
2499            return Ok(());
2500        }
2501        self.outcome.settle(
2502            if action.is_some() {
2503                "forced_shutdown"
2504            } else {
2505                "failed"
2506            },
2507            code,
2508        );
2509        let stderr = self.handle.shared.stderr_summary();
2510        Err(match (action, code) {
2511            (Some(action), _) => Error::AppServerForcedShutdown {
2512                action,
2513                status,
2514                stderr,
2515            },
2516            (None, None) => Error::AppServerSignaled { status, stderr },
2517            (None, Some(code)) => Error::from_command_failure(
2518                self.command.clone(),
2519                code,
2520                String::new(),
2521                stderr,
2522                self.working_dir.clone(),
2523            ),
2524        })
2525    }
2526
2527    /// Stop the server and its process group, and wait until it is gone.
2528    ///
2529    /// Sends the client's configured termination signal to the group,
2530    /// waits through the client's termination grace,
2531    /// kills what remains, and reaps the child. Requests still waiting fail.
2532    ///
2533    /// Shell commands the server started run in groups of their own and are
2534    /// not reached by group signaling. Cooperative cleanup depends on the
2535    /// server; see the [module documentation](self#lifecycle-and-cancellation).
2536    /// [`shutdown`](Self::shutdown) is the way to stop those.
2537    ///
2538    /// # Errors
2539    ///
2540    /// [`Error::Io`] if the child cannot be waited on.
2541    pub async fn terminate(mut self) -> Result<()> {
2542        self.handle.shared.revoke_kill();
2543        self.handle.shared.fail(Closed::Terminated);
2544        let Some(child) = &mut self.child else {
2545            self.outcome.settle("cancelled", None);
2546            return Ok(());
2547        };
2548        match crate::exec::terminate_and_reap(child, &mut self.group, self.termination_grace).await
2549        {
2550            Ok(_) => {
2551                self.outcome.settle("cancelled", None);
2552                Ok(())
2553            }
2554            Err(error) => {
2555                self.outcome.settle("cleanup_failed", None);
2556                Err(self.wait_error(error))
2557            }
2558        }
2559    }
2560
2561    fn wait_error(&self, source: std::io::Error) -> Error {
2562        Error::Io {
2563            message: format!("failed to wait on codex app-server: {source}"),
2564            source,
2565            working_dir: self.working_dir.clone(),
2566        }
2567    }
2568
2569    /// Clean up after a failed handshake and choose the error to report.
2570    async fn abandon(mut self, error: Error) -> Error {
2571        self.handle.shared.revoke_kill();
2572        let outcome = if matches!(error, Error::Timeout { .. }) {
2573            "timeout"
2574        } else {
2575            "failed"
2576        };
2577        let Some(child) = &mut self.child else {
2578            self.handle.shared.fail(Closed::Terminated);
2579            self.outcome.settle(outcome, None);
2580            return error;
2581        };
2582        // Only a server that closed its own output has failed by itself. When
2583        // the reader gave up on the stream it killed the child, so the exit
2584        // status says nothing and the error already says what happened.
2585        let by_server = matches!(locked(&self.handle.shared.state).closed, Some(Closed::Eof));
2586
2587        // Has the child already ended? One that closed its output is given a
2588        // moment to finish exiting. Otherwise only look, so a server that is
2589        // merely silent is not waited on.
2590        let ended = if by_server {
2591            tokio::time::timeout(STARTUP_EXIT_WAIT, child.wait())
2592                .await
2593                .ok()
2594        } else {
2595            child.try_wait().transpose()
2596        };
2597        if let Some(Ok(status)) = ended {
2598            // Reaped: nothing is left to terminate, and its pid is no longer
2599            // ours to signal.
2600            self.group.disarm();
2601            self.handle.shared.stderr_settled().await;
2602            let code = status.code().unwrap_or(-1);
2603            self.outcome.settle(outcome, Some(code));
2604            if by_server && !status.success() {
2605                // A server that rejects its arguments or config exits before
2606                // it can answer. Its exit status and stderr say more than
2607                // "closed its output".
2608                return Error::from_command_failure(
2609                    self.command.clone(),
2610                    code,
2611                    String::new(),
2612                    self.handle.shared.stderr_summary(),
2613                    self.working_dir.clone(),
2614                );
2615            }
2616            return error;
2617        }
2618
2619        self.handle.shared.fail(Closed::Terminated);
2620        let _ =
2621            crate::exec::terminate_and_reap(child, &mut self.group, self.termination_grace).await;
2622        self.outcome.settle(outcome, None);
2623        error
2624    }
2625}
2626
2627impl Drop for AppServer {
2628    fn drop(&mut self) {
2629        // The fields that follow kill the group and let tokio reap the child.
2630        // After that the reader task must not signal the pid.
2631        self.handle.shared.revoke_kill();
2632        self.handle.shared.fail(Closed::Terminated);
2633        for task in &self.tasks {
2634            task.abort();
2635        }
2636        self.events.close();
2637        while let Ok(event) = self.events.try_recv() {
2638            if let Event::Message(_, bytes) = event {
2639                self.handle.shared.inbound.release(bytes);
2640            }
2641        }
2642    }
2643}
2644
2645#[cfg(all(test, unix))]
2646mod tests {
2647    use super::*;
2648    use crate::CodexBuilder;
2649    use crate::test_support::{PidFile, is_running_for_test, wait_until_gone};
2650    use std::os::unix::process::ExitStatusExt;
2651
2652    const FORCED_STOP_GRACE: Duration = Duration::from_millis(500);
2653
2654    fn fake(mode: &str) -> CodexBuilder {
2655        fake_with_grace(mode, Duration::from_secs(10))
2656    }
2657
2658    fn fake_with_grace(mode: &str, grace: Duration) -> CodexBuilder {
2659        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2660            .join("tests")
2661            .join("fake-app-server.sh");
2662        Codex::builder()
2663            .binary("/bin/bash")
2664            .arg(script.to_str().expect("fixture path is utf-8"))
2665            .env("FAKE_APP_SERVER_MODE", mode)
2666            .termination_grace(grace)
2667            // A lost answer should fail a test after this, not hang it.
2668            .timeout(Duration::from_secs(20))
2669    }
2670
2671    async fn started(mode: &str) -> AppServer {
2672        let codex = fake(mode).build().expect("bash must exist");
2673        AppServer::builder(&codex)
2674            .start()
2675            .await
2676            .expect("the fake server starts")
2677    }
2678
2679    /// Read messages until `turn/completed`, returning it and everything seen.
2680    async fn until_turn_completed(server: &mut AppServer) -> (TurnCompleted, Vec<ServerMessage>) {
2681        let mut seen = Vec::new();
2682        loop {
2683            let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
2684                .await
2685                .expect("the turn should finish")
2686                .expect("no stream error")
2687                .expect("the server should not close first");
2688            let done = match &message {
2689                ServerMessage::Notification(n) => n.turn_completed(),
2690                _ => None,
2691            };
2692            seen.push(message);
2693            if let Some(done) = done {
2694                return (done, seen);
2695            }
2696        }
2697    }
2698
2699    fn methods(seen: &[ServerMessage]) -> Vec<&str> {
2700        seen.iter()
2701            .map(|message| match message {
2702                ServerMessage::Notification(n) => n.method.as_str(),
2703                ServerMessage::Request(r) => r.method.as_str(),
2704            })
2705            .collect()
2706    }
2707
2708    #[cfg(any(target_os = "macos", target_os = "ios"))]
2709    #[tokio::test]
2710    async fn owned_app_server_marks_inherited_descriptors_close_on_exec() {
2711        use crate::test_support::inheritable_pipe_writer;
2712        use std::os::fd::AsRawFd;
2713
2714        let writer = inheritable_pipe_writer();
2715        let codex = fake("turn")
2716            .env("CODEX_WRAPPER_TEST_FD", writer.as_raw_fd().to_string())
2717            .build()
2718            .unwrap();
2719        let server = AppServer::builder(&codex).start().await.unwrap();
2720        assert_eq!(server.server_info().user_agent, "fd-closed");
2721        server.shutdown().await.unwrap();
2722    }
2723
2724    #[tokio::test]
2725    async fn the_handshake_reports_the_server_and_delivers_unsolicited_notifications() {
2726        let mut server = started("turn").await;
2727        assert!(server.server_info().user_agent.contains("0.149.0"));
2728        assert_eq!(
2729            server.server_info().codex_home.as_deref(),
2730            Some("/home/user/.codex")
2731        );
2732
2733        // The real server sends this right after `initialized`, unasked.
2734        let first = server.next_message().await.unwrap().unwrap();
2735        let ServerMessage::Notification(notification) = first else {
2736            panic!("expected a notification, got {first:?}");
2737        };
2738        assert_eq!(notification.method, "remoteControl/status/changed");
2739        assert_eq!(notification.params["status"], "disabled");
2740        server.shutdown().await.unwrap();
2741    }
2742
2743    #[tokio::test]
2744    async fn a_turn_runs_to_completion_and_yields_its_final_message() {
2745        let mut server = started("turn").await;
2746        let thread = server
2747            .thread_start(
2748                ThreadStartParams::new()
2749                    .cwd("/tmp/fixture")
2750                    .ephemeral(true)
2751                    .approval_policy(ApprovalPolicy::Never)
2752                    .sandbox(SandboxMode::ReadOnly),
2753            )
2754            .await
2755            .unwrap();
2756        assert_eq!(thread.id, "01a0d1a2-5f2e-7263-a97b-cabf3e78caff");
2757        assert_eq!(thread.model.as_deref(), Some("gpt-5.6-sol"));
2758
2759        let turn = server
2760            .turn_start(TurnStartParams::text(&thread.id, "say ok"))
2761            .await
2762            .unwrap();
2763        assert_eq!(turn.status, TurnStatus::InProgress);
2764        assert_eq!(turn.id, "01a0d1a2-5f9f-75c1-9305-fa382e7b37bc");
2765
2766        let (done, seen) = until_turn_completed(&mut server).await;
2767        assert_eq!(done.thread_id, thread.id);
2768        assert_eq!(done.turn.id, turn.id);
2769        assert_eq!(done.turn.status, TurnStatus::Completed);
2770        assert_eq!(done.turn.final_message(), Some("ok"));
2771        let methods = methods(&seen);
2772        assert!(methods.contains(&"thread/started"));
2773        assert!(methods.contains(&"turn/started"));
2774        assert!(methods.contains(&"item/agentMessage/delta"));
2775        server.shutdown().await.unwrap();
2776    }
2777
2778    #[tokio::test]
2779    async fn steering_adds_input_to_the_running_turn() {
2780        let mut server = started("held").await;
2781        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2782        let turn = server
2783            .turn_start(TurnStartParams::text(&thread.id, "sleep, then say DONE"))
2784            .await
2785            .unwrap();
2786
2787        let steered = server
2788            .turn_steer(
2789                &thread.id,
2790                &turn.id,
2791                vec![UserInput::text("Also append STEERED")],
2792            )
2793            .await
2794            .unwrap();
2795        assert_eq!(steered, turn.id);
2796
2797        let (done, seen) = until_turn_completed(&mut server).await;
2798        assert_eq!(done.turn.final_message(), Some("DONE STEERED"));
2799        // The fixture echoes the steered text as a user message, so this shows
2800        // the text reached the server.
2801        let echoed = seen.iter().any(|message| match message {
2802            ServerMessage::Notification(n) => {
2803                n.method == "item/completed"
2804                    && n.params.pointer("/item/content/0/text")
2805                        == Some(&json!("Also append STEERED"))
2806            }
2807            _ => false,
2808        });
2809        assert!(echoed, "the server never saw the steered text: {seen:?}");
2810        server.shutdown().await.unwrap();
2811    }
2812
2813    #[tokio::test]
2814    async fn steering_from_another_task_while_events_are_read() {
2815        let mut server = started("held").await;
2816        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2817        let turn = server
2818            .turn_start(TurnStartParams::text(&thread.id, "go"))
2819            .await
2820            .unwrap();
2821
2822        let handle = server.handle();
2823        let (thread_id, turn_id) = (thread.id.clone(), turn.id.clone());
2824        let steer = tokio::spawn(async move {
2825            handle
2826                .turn_steer(&thread_id, &turn_id, vec![UserInput::text("more")])
2827                .await
2828        });
2829
2830        let (done, _) = until_turn_completed(&mut server).await;
2831        assert_eq!(done.turn.status, TurnStatus::Completed);
2832        assert_eq!(steer.await.unwrap().unwrap(), turn.id);
2833        server.shutdown().await.unwrap();
2834    }
2835
2836    #[tokio::test]
2837    async fn steering_the_wrong_turn_is_an_rpc_error_that_names_both_ids() {
2838        let server = started("held").await;
2839        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2840        let turn = server
2841            .turn_start(TurnStartParams::text(&thread.id, "go"))
2842            .await
2843            .unwrap();
2844
2845        let error = server
2846            .turn_steer(&thread.id, "not-the-turn", vec![UserInput::text("x")])
2847            .await
2848            .unwrap_err();
2849        match error {
2850            Error::AppServerRpc {
2851                method,
2852                code,
2853                message,
2854                ..
2855            } => {
2856                assert_eq!(method, "turn/steer");
2857                assert_eq!(code, -32600);
2858                assert_eq!(
2859                    message,
2860                    format!(
2861                        "expected active turn id `not-the-turn` but found `{}`",
2862                        turn.id
2863                    )
2864                );
2865            }
2866            other => panic!("expected an rpc error, got {other:?}"),
2867        }
2868
2869        let error = server
2870            .turn_interrupt(&thread.id, "not-the-turn")
2871            .await
2872            .unwrap_err();
2873        assert!(
2874            matches!(&error, Error::AppServerRpc { message, .. }
2875                if message == &format!("expected active turn id not-the-turn but found {}", turn.id)),
2876            "{error:?}"
2877        );
2878        server.shutdown().await.unwrap();
2879    }
2880
2881    #[tokio::test]
2882    async fn steering_or_interrupting_with_no_active_turn_is_an_rpc_error() {
2883        let server = started("held").await;
2884        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2885
2886        let error = server
2887            .turn_steer(&thread.id, "any", vec![UserInput::text("x")])
2888            .await
2889            .unwrap_err();
2890        assert!(
2891            matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to steer"),
2892            "{error:?}"
2893        );
2894        let error = server.turn_interrupt(&thread.id, "any").await.unwrap_err();
2895        assert!(
2896            matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to interrupt"),
2897            "{error:?}"
2898        );
2899        server.shutdown().await.unwrap();
2900    }
2901
2902    /// codex-cli 0.145.0 sends `items: []` (`itemsView: notLoaded`) in
2903    /// `turn/completed` even when the turn completed, so the answer has to come
2904    /// from the `item/completed` stream.
2905    #[tokio::test]
2906    async fn the_final_answer_is_available_when_turn_completed_carries_no_items() {
2907        let codex = fake("turn")
2908            .env("FAKE_APP_SERVER_ITEMS", "legacy")
2909            .build()
2910            .unwrap();
2911        let mut server = AppServer::builder(&codex).start().await.unwrap();
2912        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2913        server
2914            .turn_start(TurnStartParams::text(&thread.id, "say ok"))
2915            .await
2916            .unwrap();
2917
2918        let (done, seen) = until_turn_completed(&mut server).await;
2919        assert_eq!(done.turn.status, TurnStatus::Completed);
2920        assert!(done.turn.items.is_empty());
2921        assert_eq!(done.turn.final_message(), None);
2922        let answer = seen
2923            .iter()
2924            .filter_map(|message| match message {
2925                ServerMessage::Notification(n) => n.agent_message(),
2926                _ => None,
2927            })
2928            .rfind(AgentMessage::is_final_answer)
2929            .expect("the item stream carries the answer");
2930        assert_eq!(answer.text, "ok");
2931        server.shutdown().await.unwrap();
2932    }
2933
2934    #[tokio::test]
2935    async fn interrupting_ends_the_turn_as_interrupted_with_no_final_message() {
2936        let mut server = started("held").await;
2937        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2938        let turn = server
2939            .turn_start(TurnStartParams::text(&thread.id, "go"))
2940            .await
2941            .unwrap();
2942
2943        server.turn_interrupt(&thread.id, &turn.id).await.unwrap();
2944
2945        let (done, _) = until_turn_completed(&mut server).await;
2946        assert_eq!(done.turn.status, TurnStatus::Interrupted);
2947        assert!(done.turn.items.is_empty());
2948        assert_eq!(done.turn.final_message(), None);
2949        server.shutdown().await.unwrap();
2950    }
2951
2952    #[tokio::test]
2953    async fn a_server_request_is_delivered_and_the_reply_reaches_the_server() {
2954        let mut server = started("approval").await;
2955        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2956        server
2957            .turn_start(TurnStartParams::text(&thread.id, "touch a file"))
2958            .await
2959            .unwrap();
2960
2961        let mut seen = Vec::new();
2962        let request = loop {
2963            let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
2964                .await
2965                .unwrap()
2966                .unwrap()
2967                .unwrap();
2968            if let ServerMessage::Request(request) = message {
2969                break request;
2970            }
2971            seen.push(message);
2972        };
2973        assert_eq!(request.method, "item/commandExecution/requestApproval");
2974        assert_eq!(request.id, RequestId::Number(0));
2975        assert_eq!(
2976            request.params["command"],
2977            "/bin/zsh -lc 'touch created.txt'"
2978        );
2979
2980        server
2981            .respond(request.id, json!({ "decision": "decline" }))
2982            .unwrap();
2983
2984        let (done, after) = until_turn_completed(&mut server).await;
2985        // The fixture reports the decision it received.
2986        assert_eq!(done.turn.final_message(), Some("decision: decline"));
2987        assert!(methods(&after).contains(&"serverRequest/resolved"));
2988        server.shutdown().await.unwrap();
2989    }
2990
2991    #[tokio::test]
2992    async fn concurrent_requests_are_matched_to_their_answers_by_id() {
2993        let server = started("turn").await;
2994        let (first, second, unknown) = tokio::join!(
2995            server.thread_start(ThreadStartParams::new()),
2996            server.request("thread/start", json!({})),
2997            server.request("no/such/method", json!({})),
2998        );
2999        assert!(first.is_ok());
3000        assert!(second.unwrap().pointer("/thread/id").is_some());
3001        match unknown.unwrap_err() {
3002            Error::AppServerRpc { message, .. } => {
3003                assert!(
3004                    message.contains("unknown variant `no/such/method`"),
3005                    "{message}"
3006                );
3007            }
3008            other => panic!("expected an rpc error, got {other:?}"),
3009        }
3010        server.shutdown().await.unwrap();
3011    }
3012
3013    #[tokio::test]
3014    async fn a_second_initialize_is_rejected_by_the_server() {
3015        let server = started("turn").await;
3016        let error = server
3017            .request(
3018                "initialize",
3019                json!({ "clientInfo": { "name": "x", "version": "0" } }),
3020            )
3021            .await
3022            .unwrap_err();
3023        assert!(
3024            matches!(&error, Error::AppServerRpc { message, .. } if message == "Already initialized"),
3025            "{error:?}"
3026        );
3027        server.shutdown().await.unwrap();
3028    }
3029
3030    /// What the client puts on the wire, read back from the fixture's log.
3031    #[tokio::test]
3032    async fn requests_are_written_as_the_server_expects_them() {
3033        let log = std::env::temp_dir().join(format!(
3034            "codex-wrapper-{}-app-server-wire.log",
3035            std::process::id()
3036        ));
3037        let _ = std::fs::remove_file(&log);
3038        let codex = fake("held")
3039            .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
3040            .build()
3041            .unwrap();
3042        let mut server = AppServer::builder(&codex)
3043            .client_info("probe", "1.2.3")
3044            .opt_out_notification("item/agentMessage/delta")
3045            .opt_out_notification("mcpServer/startupStatus/updated")
3046            .start()
3047            .await
3048            .unwrap();
3049        let thread = server
3050            .thread_start(
3051                ThreadStartParams::new()
3052                    .cwd("/tmp/fixture")
3053                    .model("gpt-5.6-sol")
3054                    .approval_policy(ApprovalPolicy::Never)
3055                    .sandbox(SandboxMode::ReadOnly)
3056                    .ephemeral(true),
3057            )
3058            .await
3059            .unwrap();
3060        let schema = json!({ "type": "object", "required": ["answer"] });
3061        let turn = server
3062            .turn_start(
3063                TurnStartParams::text(&thread.id, "hi")
3064                    .model("gpt-5.6-sol")
3065                    .effort("low")
3066                    .output_schema(schema.clone())
3067                    .cwd("/tmp/fixture")
3068                    .approval_policy(ApprovalPolicy::Never)
3069                    .param("summary", json!("none")),
3070            )
3071            .await
3072            .unwrap();
3073        server
3074            .turn_steer(&thread.id, &turn.id, vec![UserInput::text("more")])
3075            .await
3076            .unwrap();
3077        let _ = until_turn_completed(&mut server).await;
3078        server.shutdown().await.unwrap();
3079
3080        let lines: Vec<Value> = std::fs::read_to_string(&log)
3081            .unwrap()
3082            .lines()
3083            .map(|line| serde_json::from_str(line).expect("every client line is JSON"))
3084            .collect();
3085        let _ = std::fs::remove_file(&log);
3086
3087        assert_eq!(
3088            lines[0],
3089            json!({
3090                "id": 0,
3091                "method": "initialize",
3092                "params": {
3093                    "clientInfo": { "name": "probe", "version": "1.2.3" },
3094                    "capabilities": {
3095                        "optOutNotificationMethods": [
3096                            "item/agentMessage/delta",
3097                            "mcpServer/startupStatus/updated"
3098                        ]
3099                    }
3100                }
3101            })
3102        );
3103        assert_eq!(lines[1], json!({ "method": "initialized" }));
3104        assert_eq!(
3105            lines[2],
3106            json!({
3107                "id": 1,
3108                "method": "thread/start",
3109                "params": {
3110                    "cwd": "/tmp/fixture",
3111                    "model": "gpt-5.6-sol",
3112                    "approvalPolicy": "never",
3113                    "sandbox": "read-only",
3114                    "ephemeral": true
3115                }
3116            })
3117        );
3118        assert_eq!(
3119            lines[3],
3120            json!({
3121                "id": 2,
3122                "method": "turn/start",
3123                "params": {
3124                    "threadId": thread.id,
3125                    "input": [{ "type": "text", "text": "hi", "text_elements": [] }],
3126                    "model": "gpt-5.6-sol",
3127                    "effort": "low",
3128                    "outputSchema": schema,
3129                    "cwd": "/tmp/fixture",
3130                    "approvalPolicy": "never",
3131                    "summary": "none"
3132                }
3133            })
3134        );
3135        assert_eq!(
3136            lines[4],
3137            json!({
3138                "id": 3,
3139                "method": "turn/steer",
3140                "params": {
3141                    "threadId": thread.id,
3142                    "expectedTurnId": turn.id,
3143                    "input": [{ "type": "text", "text": "more", "text_elements": [] }]
3144                }
3145            })
3146        );
3147    }
3148
3149    /// A server that exits 0 before it answers has been reaped by the time the
3150    /// failure is reported, so there is nothing left to terminate. Waiting out
3151    /// the grace period (and signalling a pid that is no longer ours) is the
3152    /// failure this guards.
3153    #[tokio::test]
3154    async fn a_server_that_exits_cleanly_before_answering_fails_the_start_without_waiting() {
3155        let codex = fake("exit-clean").build().unwrap();
3156        let started_at = std::time::Instant::now();
3157        let error = AppServer::builder(&codex).start().await.unwrap_err();
3158        assert!(
3159            matches!(error, Error::AppServerProtocol { .. }),
3160            "{error:?}"
3161        );
3162        assert!(
3163            started_at.elapsed() < Duration::from_secs(3),
3164            "start waited out the grace period for a server that had already exited"
3165        );
3166    }
3167
3168    /// The reader kills the server when the stream breaks. That must not be
3169    /// mistaken for the server failing by itself, or the useful message is
3170    /// replaced by an exit status.
3171    #[tokio::test]
3172    async fn invalid_json_during_the_handshake_is_reported_as_invalid_json() {
3173        let codex = fake_with_grace("bad-init", FORCED_STOP_GRACE)
3174            .build()
3175            .unwrap();
3176        let error = AppServer::builder(&codex).start().await.unwrap_err();
3177        assert!(
3178            matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
3179            "{error:?}"
3180        );
3181        assert_eq!(error.exit_code(), None);
3182    }
3183
3184    /// A response that names a waiting request but has neither `result` nor
3185    /// `error` is not a valid answer. Ignoring it would leave the request
3186    /// waiting for one that will never come.
3187    #[tokio::test]
3188    async fn a_response_with_neither_result_nor_error_fails_the_request_it_names() {
3189        let server = started("no-result").await;
3190        let error = server
3191            .thread_start(ThreadStartParams::new())
3192            .await
3193            .unwrap_err();
3194        assert!(
3195            matches!(&error, Error::AppServerProtocol { message }
3196                if message.contains("neither result nor error") && message.contains("thread/start")),
3197            "{error:?}"
3198        );
3199        // The session itself is still usable.
3200        assert!(server.notify("initialized", Value::Null).is_ok());
3201        server.shutdown().await.unwrap();
3202    }
3203
3204    /// The reader task holds a way to kill the server. It must stop being able
3205    /// to once the client is done with the child: after that the pid may
3206    /// belong to someone else.
3207    #[tokio::test]
3208    async fn the_readers_kill_switch_is_revoked_when_the_client_is_done_with_the_child() {
3209        // Never signals this process: the target is a `sleep` started here.
3210        let sleeper = |seconds: &str| {
3211            std::process::Command::new("sleep")
3212                .arg(seconds)
3213                .spawn()
3214                .unwrap()
3215        };
3216        let (events, _received) = mpsc::unbounded_channel();
3217
3218        let mut live = sleeper("60");
3219        let shared = Shared::new(
3220            events.clone(),
3221            Some(KillTarget {
3222                pid: Some(live.id()),
3223                group: false,
3224            }),
3225            Limits::default(),
3226            "test",
3227        );
3228        shared.fire_kill();
3229        assert!(
3230            live.wait().unwrap().code().is_none(),
3231            "the switch should have killed the process it was armed with"
3232        );
3233
3234        let mut revoked = sleeper("60");
3235        let shared = Shared::new(
3236            events,
3237            Some(KillTarget {
3238                pid: Some(revoked.id()),
3239                group: false,
3240            }),
3241            Limits::default(),
3242            "test",
3243        );
3244        shared.revoke_kill();
3245        shared.fire_kill();
3246        std::thread::sleep(Duration::from_millis(200));
3247        assert!(
3248            revoked.try_wait().unwrap().is_none(),
3249            "a revoked switch still killed the process"
3250        );
3251        revoked.kill().unwrap();
3252        revoked.wait().unwrap();
3253    }
3254
3255    #[tokio::test]
3256    async fn every_way_of_ending_the_session_revokes_the_kill_switch() {
3257        let armed = |shared: &Shared| locked(&shared.kill).is_some();
3258
3259        let server = started("turn").await;
3260        let shared = Arc::clone(&server.handle.shared);
3261        assert!(armed(&shared));
3262        server.shutdown().await.unwrap();
3263        assert!(!armed(&shared), "shutdown left the switch armed");
3264
3265        let codex = fake_with_grace("turn", FORCED_STOP_GRACE).build().unwrap();
3266        let server = AppServer::builder(&codex).start().await.unwrap();
3267        let shared = Arc::clone(&server.handle.shared);
3268        server.terminate().await.unwrap();
3269        assert!(!armed(&shared), "terminate left the switch armed");
3270
3271        let server = started("turn").await;
3272        let shared = Arc::clone(&server.handle.shared);
3273        drop(server);
3274        assert!(!armed(&shared), "dropping left the switch armed");
3275    }
3276
3277    #[test]
3278    fn the_previewed_command_includes_the_clients_global_args() {
3279        let codex = Codex::builder()
3280            .binary("/bin/echo")
3281            .config("model=\"o3\"")
3282            .build()
3283            .unwrap();
3284        let builder = AppServer::builder(&codex);
3285        assert_eq!(builder.args(), ["app-server", "--listen", "stdio://"]);
3286        assert_eq!(
3287            builder.to_command_string(),
3288            "/bin/echo -c 'model=\"o3\"' app-server --listen stdio://"
3289        );
3290    }
3291
3292    #[tokio::test]
3293    async fn a_silent_server_times_out_the_handshake_and_is_stopped() {
3294        let pid = Arc::new(Mutex::new(None));
3295        let observed = Arc::clone(&pid);
3296        let codex = fake("silent")
3297            .timeout(Duration::from_millis(300))
3298            .on_spawn(Arc::new(move |info| {
3299                *observed.lock().unwrap() = Some(info.pid);
3300            }))
3301            .build()
3302            .unwrap();
3303
3304        let error = AppServer::builder(&codex).start().await.unwrap_err();
3305        assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
3306
3307        let pid = pid.lock().unwrap().expect("the server was spawned");
3308        assert!(
3309            wait_until_gone(pid).await,
3310            "the silent server ({pid}) survived a failed start"
3311        );
3312    }
3313
3314    #[tokio::test]
3315    async fn a_server_that_exits_at_startup_is_reported_with_its_stderr() {
3316        let codex = fake("exit-on-start").build().unwrap();
3317        let error = AppServer::builder(&codex).start().await.unwrap_err();
3318        assert_eq!(error.exit_code(), Some(1), "{error:?}");
3319        assert_eq!(
3320            error.failure_kind(),
3321            Some(crate::FailureKind::Config),
3322            "{error:?}"
3323        );
3324        assert!(error.to_string().contains("bogus_key"), "{error}");
3325    }
3326
3327    /// A server that dies at startup can be noticed by the client's write (the
3328    /// pipe is closed, EPIPE) before its read (the stream has ended). Either
3329    /// way the server went away by itself, and what says why is its stderr and
3330    /// exit status, which the reader reports at the end of the stream. A write
3331    /// error must not become the session's failure and hide that; this was
3332    /// seen as a flaky failure on Linux CI.
3333    ///
3334    /// An in-memory pipe stands in for the child's stdin. A real one made this
3335    /// test hang under load: on macOS a pipe's close-on-exec flag is set after
3336    /// it is created, so a process forked by a concurrent test can inherit the
3337    /// read end, and then the write never fails.
3338    #[tokio::test]
3339    async fn a_broken_stdin_pipe_leaves_the_verdict_to_the_reader() {
3340        let (stdin, server_end) = tokio::io::duplex(64);
3341        drop(server_end);
3342
3343        let (events, _received) = mpsc::unbounded_channel();
3344        let shared = Arc::new(Shared::new(events, None, Limits::default(), "test"));
3345        let (lines, receiver) = mpsc::unbounded_channel();
3346        lines
3347            .send(Outgoing::Line(ReservedLine {
3348                bytes: b"{}\n".to_vec(),
3349                budget: Arc::clone(&shared.outbound),
3350            }))
3351            .unwrap();
3352
3353        // Ends by itself when the write fails. If it did not fail, `lines` is
3354        // still open and this would wait forever, so bound it.
3355        tokio::time::timeout(
3356            Duration::from_secs(10),
3357            write_stdin(stdin, receiver, Arc::clone(&shared)),
3358        )
3359        .await
3360        .expect("the write to a closed pipe did not fail");
3361
3362        assert!(
3363            locked(&shared.state).closed.is_none(),
3364            "a write to a closed pipe was recorded as the session's failure"
3365        );
3366        drop(lines);
3367    }
3368
3369    /// End to end: a server that closes its input and then fails is reported
3370    /// by its exit status and stderr. The race that once made this flaky on
3371    /// Linux CI is pinned by `a_broken_stdin_pipe_leaves_the_verdict_to_the_reader`.
3372    #[tokio::test]
3373    async fn a_server_that_closes_its_input_and_then_fails_is_reported_by_its_exit_status() {
3374        let codex = fake("close-stdin").build().unwrap();
3375        let error = AppServer::builder(&codex).start().await.unwrap_err();
3376        assert_eq!(error.exit_code(), Some(1), "{error:?}");
3377        assert_eq!(
3378            error.failure_kind(),
3379            Some(crate::FailureKind::Config),
3380            "{error:?}"
3381        );
3382        assert!(error.to_string().contains("bogus_key"), "{error}");
3383    }
3384
3385    /// The server writes about 500 KB to stderr before its first answer. An
3386    /// undrained pipe holds about 64 KB, so this hangs if stderr is not read.
3387    #[tokio::test]
3388    async fn heavy_stderr_does_not_stall_the_session() {
3389        let codex = fake("noisy-stderr").build().unwrap();
3390        let server =
3391            tokio::time::timeout(Duration::from_secs(20), AppServer::builder(&codex).start())
3392                .await
3393                .expect("the handshake stalled behind an undrained stderr pipe")
3394                .unwrap();
3395        server.shutdown().await.unwrap();
3396    }
3397
3398    #[tokio::test]
3399    async fn a_server_that_exits_mid_request_fails_it_with_the_stderr() {
3400        let mut server = started("exit-on-turn").await;
3401        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
3402        let error = server
3403            .turn_start(TurnStartParams::text(&thread.id, "go"))
3404            .await
3405            .unwrap_err();
3406        let text = error.to_string();
3407        assert!(text.contains("turn/start"), "{text}");
3408        assert!(
3409            text.contains("connection to the model provider was lost"),
3410            "{text}"
3411        );
3412
3413        // Earlier messages are still delivered, then the stream ends cleanly.
3414        while server.next_message().await.unwrap().is_some() {}
3415        assert!(server.next_message().await.unwrap().is_none());
3416
3417        // New requests fail at once instead of waiting for a timeout.
3418        let again = server.request("thread/start", json!({})).await.unwrap_err();
3419        assert!(
3420            matches!(again, Error::AppServerProtocol { .. }),
3421            "{again:?}"
3422        );
3423
3424        // The exit status is reported by shutdown.
3425        let error = server.shutdown().await.unwrap_err();
3426        assert_eq!(error.exit_code(), Some(5), "{error:?}");
3427    }
3428
3429    #[tokio::test]
3430    async fn the_output_limit_ends_the_session_and_kills_the_server() {
3431        let pid = Arc::new(Mutex::new(None));
3432        let observed = Arc::clone(&pid);
3433        let codex = fake("flood")
3434            .output_limit(2048)
3435            .on_spawn(Arc::new(move |info| {
3436                *observed.lock().unwrap() = Some(info.pid);
3437            }))
3438            .build()
3439            .unwrap();
3440        let mut server = AppServer::builder(&codex).start().await.unwrap();
3441
3442        let error = loop {
3443            match server.next_message().await {
3444                Ok(Some(_)) => {}
3445                Ok(None) => panic!("the limit error was swallowed"),
3446                Err(error) => break error,
3447            }
3448        };
3449        assert!(
3450            matches!(
3451                error,
3452                Error::OutputLimitExceeded {
3453                    stream: OutputStream::Stdout,
3454                    limit_bytes: 2048
3455                }
3456            ),
3457            "{error:?}"
3458        );
3459        assert!(server.next_message().await.unwrap().is_none());
3460
3461        let pid = pid.lock().unwrap().expect("the server was spawned");
3462        assert!(
3463            wait_until_gone(pid).await,
3464            "the server ({pid}) kept running after the output limit"
3465        );
3466    }
3467
3468    #[tokio::test]
3469    async fn invalid_json_ends_the_session() {
3470        let mut server = started("bad-json").await;
3471        let error = loop {
3472            match server.next_message().await {
3473                Ok(Some(_)) => {}
3474                Ok(None) => panic!("the malformed line was swallowed"),
3475                Err(error) => break error,
3476            }
3477        };
3478        assert!(
3479            matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
3480            "{error:?}"
3481        );
3482    }
3483
3484    #[tokio::test]
3485    async fn terminate_stops_the_whole_process_group() {
3486        let pid_file = PidFile::new("app-server-terminate");
3487        let codex = fake("spawns-child")
3488            .env(
3489                "CODEX_WRAPPER_TEST_PIDFILE",
3490                pid_file.path().to_str().unwrap(),
3491            )
3492            // Long enough for the fixture's SIGTERM handler to run on a
3493            // loaded machine, so the marker below means what it says.
3494            .termination_grace(Duration::from_secs(1))
3495            .build()
3496            .unwrap();
3497        let server = AppServer::builder(&codex).start().await.unwrap();
3498        let (parent, child) = read_pids(&pid_file).await;
3499        assert!(is_running_for_test(parent) && is_running_for_test(child));
3500
3501        server.terminate().await.unwrap();
3502
3503        // The direct child has been reaped. Its subprocess got SIGKILL at the
3504        // same moment, but nothing waits for it, so allow it a moment to die.
3505        assert!(
3506            wait_until_gone(parent).await,
3507            "the server ({parent}) survived"
3508        );
3509        assert!(
3510            wait_until_gone(child).await,
3511            "the server's subprocess ({child}) survived terminate"
3512        );
3513        // The fixture writes this marker only if it is asked to stop with
3514        // SIGTERM first, which is what separates terminate from a kill.
3515        let marker = term_marker(&pid_file);
3516        assert!(
3517            marker.exists(),
3518            "terminate killed the server without asking it to stop first"
3519        );
3520        let _ = std::fs::remove_file(marker);
3521    }
3522
3523    #[tokio::test]
3524    async fn dropping_during_app_server_termination_grace_kills_the_group() {
3525        let fixture = crate::test_support::GracePeriodFixture::new("app-server-grace-drop");
3526        let codex = fixture.configure(fake("ignores-eof")).build().unwrap();
3527        let server = AppServer::builder(&codex).start().await.unwrap();
3528        fixture.assert_drop_during_grace(server.terminate()).await;
3529    }
3530
3531    #[tokio::test]
3532    async fn dropping_the_client_kills_the_process_group() {
3533        let pid_file = PidFile::new("app-server-drop");
3534        let codex = fake("spawns-child")
3535            .env(
3536                "CODEX_WRAPPER_TEST_PIDFILE",
3537                pid_file.path().to_str().unwrap(),
3538            )
3539            .build()
3540            .unwrap();
3541        let server = AppServer::builder(&codex).start().await.unwrap();
3542        let (parent, child) = read_pids(&pid_file).await;
3543
3544        drop(server);
3545
3546        assert!(
3547            wait_until_gone(parent).await,
3548            "the server ({parent}) survived"
3549        );
3550        assert!(
3551            wait_until_gone(child).await,
3552            "the server's subprocess ({child}) survived the drop"
3553        );
3554        // Dropping is the abrupt path: no SIGTERM, so no marker.
3555        assert!(!term_marker(&pid_file).exists());
3556    }
3557
3558    #[tokio::test]
3559    async fn shutdown_lets_a_server_that_exits_on_eof_finish_by_itself() {
3560        // A fallback to terminate would wait out the whole grace, so a long
3561        // grace makes the two paths easy to tell apart without a tight bound.
3562        let codex = fake("turn")
3563            .termination_grace(Duration::from_secs(4))
3564            .build()
3565            .unwrap();
3566        let server = AppServer::builder(&codex).start().await.unwrap();
3567        let pid = server.pid().expect("running");
3568        let started_at = std::time::Instant::now();
3569        server.shutdown().await.unwrap();
3570        assert!(
3571            started_at.elapsed() < Duration::from_secs(3),
3572            "shutdown waited out the grace instead of seeing the exit"
3573        );
3574        assert!(wait_until_gone(pid).await);
3575    }
3576
3577    #[tokio::test]
3578    async fn shutdown_reports_a_nonzero_exit_on_eof() {
3579        let error = started("exit-on-eof").await.shutdown().await.unwrap_err();
3580        assert!(matches!(error, Error::CommandFailed { exit_code: 17, .. }));
3581    }
3582
3583    #[tokio::test]
3584    async fn shutdown_allows_a_clean_exit_without_a_process_group() {
3585        let codex = fake("turn").process_group(false).build().unwrap();
3586        let server = AppServer::builder(&codex).start().await.unwrap();
3587        server.shutdown().await.unwrap();
3588    }
3589
3590    #[tokio::test]
3591    async fn shutdown_reports_a_nonzero_exit_without_a_process_group() {
3592        let codex = fake("exit-on-eof").process_group(false).build().unwrap();
3593        let server = AppServer::builder(&codex).start().await.unwrap();
3594        let error = server.shutdown().await.unwrap_err();
3595        assert!(matches!(error, Error::CommandFailed { exit_code: 17, .. }));
3596    }
3597
3598    #[tokio::test]
3599    async fn shutdown_reports_a_signal_the_wrapper_did_not_send() {
3600        let error = started("signal-on-eof").await.shutdown().await.unwrap_err();
3601        assert!(
3602            matches!(error, Error::AppServerSignaled { status, .. } if status.signal() == Some(libc::SIGUSR1)),
3603            "{error:?}"
3604        );
3605        assert_eq!(error.exit_code(), None);
3606    }
3607
3608    #[tokio::test]
3609    async fn shutdown_falls_back_to_termination_when_the_server_ignores_eof() {
3610        let pid_file = PidFile::new("app-server-ignores-eof");
3611        let codex = fake("ignores-eof")
3612            .env(
3613                "CODEX_WRAPPER_TEST_PIDFILE",
3614                pid_file.path().to_str().unwrap(),
3615            )
3616            // Long enough for the fixture's SIGTERM handler to run on a
3617            // loaded machine, so the marker below means what it says.
3618            .termination_grace(Duration::from_secs(1))
3619            .build()
3620            .unwrap();
3621        let server = AppServer::builder(&codex).start().await.unwrap();
3622        let (parent, child) = read_pids(&pid_file).await;
3623
3624        let error = server.shutdown().await.unwrap_err();
3625        assert!(
3626            matches!(error, Error::AppServerForcedShutdown {
3627                action: ShutdownAction::Signal(crate::TerminationSignal::Terminate),
3628                status,
3629                ..
3630            } if status.success()),
3631            "{error:?}"
3632        );
3633
3634        // Asked to stop before it was killed, not just killed.
3635        let marker = term_marker(&pid_file);
3636        assert!(
3637            marker.exists(),
3638            "shutdown killed the server without asking it to stop"
3639        );
3640        let _ = std::fs::remove_file(marker);
3641
3642        assert!(
3643            wait_until_gone(parent).await,
3644            "the server ({parent}) survived"
3645        );
3646        assert!(
3647            wait_until_gone(child).await,
3648            "the server's subprocess ({child}) survived shutdown"
3649        );
3650    }
3651
3652    #[tokio::test]
3653    async fn shutdown_reports_sigterm_and_the_exit_code_from_the_handler() {
3654        for code in [0, 17] {
3655            let codex = fake_with_grace("exit-on-term", FORCED_STOP_GRACE)
3656                .env("FAKE_APP_SERVER_TERM_EXIT_CODE", code.to_string())
3657                .build()
3658                .unwrap();
3659            let server = AppServer::builder(&codex).start().await.unwrap();
3660            let error = server.shutdown().await.unwrap_err();
3661            assert!(
3662                matches!(error, Error::AppServerForcedShutdown {
3663                    action: ShutdownAction::Signal(crate::TerminationSignal::Terminate),
3664                    status,
3665                    ..
3666                } if status.code() == Some(code)),
3667                "{error:?}"
3668            );
3669            assert_eq!(error.exit_code(), Some(code));
3670            assert!(error.to_string().contains("SIGTERM"));
3671        }
3672    }
3673
3674    #[tokio::test]
3675    async fn shutdown_reports_sigkill_with_or_without_a_process_group() {
3676        for process_group in [true, false] {
3677            let codex = fake_with_grace("ignores-term", FORCED_STOP_GRACE)
3678                .process_group(process_group)
3679                .build()
3680                .unwrap();
3681            let server = AppServer::builder(&codex).start().await.unwrap();
3682            let error = server.shutdown().await.unwrap_err();
3683            assert!(
3684                matches!(error, Error::AppServerForcedShutdown {
3685                    action: ShutdownAction::Kill,
3686                    status,
3687                    ..
3688                } if status.signal() == Some(libc::SIGKILL)),
3689                "{error:?}"
3690            );
3691            assert!(error.to_string().contains("SIGKILL"));
3692        }
3693    }
3694
3695    #[tokio::test]
3696    async fn shutdown_reports_a_hard_stop_already_sent_on_a_transport_failure() {
3697        let mut server = started("bad-json").await;
3698        loop {
3699            match server.next_message().await {
3700                Ok(Some(_)) => {}
3701                Err(Error::AppServerProtocol { .. }) => break,
3702                result => panic!("expected a protocol error, got {result:?}"),
3703            }
3704        }
3705        let error = server.shutdown().await.unwrap_err();
3706        assert!(
3707            matches!(error, Error::AppServerForcedShutdown {
3708                action: ShutdownAction::Kill,
3709                status,
3710                ..
3711            } if status.signal() == Some(libc::SIGKILL)),
3712            "{error:?}"
3713        );
3714    }
3715
3716    #[tokio::test]
3717    async fn shutdown_preserves_an_independent_exit_during_the_second_grace() {
3718        let term = PidFile::new("app-server-late-exit-term");
3719        let gate = PidFile::new("app-server-late-exit-gate");
3720        let codex = fake_with_grace("late-exit", Duration::from_secs(2))
3721            .env("FAKE_APP_SERVER_TERM_MARKER", term.path().to_str().unwrap())
3722            .env("FAKE_APP_SERVER_EXIT_GATE", gate.path().to_str().unwrap())
3723            .build()
3724            .unwrap();
3725        let server = AppServer::builder(&codex).start().await.unwrap();
3726        let release = async {
3727            tokio::time::timeout(Duration::from_secs(4), async {
3728                while !term.path().exists() {
3729                    tokio::time::sleep(Duration::from_millis(10)).await;
3730                }
3731            })
3732            .await
3733            .expect("the server did not observe SIGTERM");
3734            std::fs::write(gate.path(), "").unwrap();
3735        };
3736        let (result, ()) = tokio::join!(server.shutdown(), release);
3737        let error = result.unwrap_err();
3738        assert!(
3739            matches!(error, Error::AppServerForcedShutdown {
3740                action: ShutdownAction::Signal(crate::TerminationSignal::Terminate),
3741                status,
3742                ..
3743            } if status.code() == Some(17)),
3744            "{error:?}"
3745        );
3746    }
3747
3748    #[tokio::test]
3749    async fn requests_after_shutdown_fail_on_a_surviving_handle() {
3750        let server = started("turn").await;
3751        let handle = server.handle();
3752        server.shutdown().await.unwrap();
3753        let error = handle.request("thread/start", json!({})).await.unwrap_err();
3754        assert!(
3755            matches!(error, Error::AppServerProtocol { .. }),
3756            "{error:?}"
3757        );
3758        assert!(handle.notify("initialized", Value::Null).is_err());
3759    }
3760
3761    fn term_marker(pid_file: &PidFile) -> std::path::PathBuf {
3762        let mut path = pid_file.path().as_os_str().to_owned();
3763        path.push(".term");
3764        std::path::PathBuf::from(path)
3765    }
3766
3767    async fn read_pids(pid_file: &PidFile) -> (u32, u32) {
3768        // Up to ten seconds: starting bash can be slow on a loaded machine.
3769        for _ in 0..1000 {
3770            if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
3771                let field = |key: &str| {
3772                    contents
3773                        .lines()
3774                        .find_map(|line| line.strip_prefix(key))
3775                        .and_then(|value| value.trim().parse::<u32>().ok())
3776                };
3777                if let (Some(parent), Some(child)) = (field("parent="), field("child=")) {
3778                    return (parent, child);
3779                }
3780            }
3781            tokio::time::sleep(Duration::from_millis(10)).await;
3782        }
3783        panic!("the fake server never recorded its pids");
3784    }
3785
3786    #[tokio::test]
3787    async fn a_request_that_times_out_leaves_the_session_usable_and_no_entry_behind() {
3788        // The short timeout is for the requests below, not the handshake,
3789        // which has to be allowed to take as long as a loaded machine needs.
3790        let server = started("mute-after-init").await;
3791        let mut handle = server.handle();
3792        handle.timeout = Some(Duration::from_millis(150));
3793
3794        for _ in 0..2 {
3795            let error = handle.request("thread/start", json!({})).await.unwrap_err();
3796            assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
3797        }
3798        assert!(
3799            locked(&handle.shared.state).pending.is_empty(),
3800            "a timed-out request left its slot behind"
3801        );
3802        // A timeout is a verdict on one request, not on the session.
3803        assert!(handle.notify("initialized", Value::Null).is_ok());
3804        server.shutdown().await.unwrap();
3805    }
3806
3807    /// A request future that is dropped after it has queued its line must not
3808    /// leave half a line behind: the next request still gets a clean answer,
3809    /// and every line the server received is whole JSON.
3810    #[tokio::test]
3811    async fn dropping_a_request_future_does_not_corrupt_the_wire() {
3812        let log = std::env::temp_dir().join(format!(
3813            "codex-wrapper-{}-app-server-dropped.log",
3814            std::process::id()
3815        ));
3816        let _ = std::fs::remove_file(&log);
3817        let codex = fake("turn")
3818            .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
3819            .build()
3820            .unwrap();
3821        let server = AppServer::builder(&codex).start().await.unwrap();
3822
3823        for _ in 0..20 {
3824            // Poll once, so the line is queued, then drop the future before
3825            // any answer can be read.
3826            let request = server.request("thread/start", json!({ "ephemeral": true }));
3827            let mut request = std::pin::pin!(request);
3828            let mut context = std::task::Context::from_waker(std::task::Waker::noop());
3829            assert!(request.as_mut().poll(&mut context).is_pending());
3830        }
3831        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
3832        assert!(!thread.id.is_empty());
3833        server.shutdown().await.unwrap();
3834
3835        let text = std::fs::read_to_string(&log).unwrap();
3836        let _ = std::fs::remove_file(&log);
3837        let mut count = 0;
3838        for line in text.lines() {
3839            serde_json::from_str::<Value>(line).expect("the server received a partial line");
3840            count += 1;
3841        }
3842        // initialize, initialized, twenty abandoned requests, one that was awaited.
3843        assert_eq!(count, 23, "{text}");
3844    }
3845
3846    #[tokio::test]
3847    async fn next_message_loses_nothing_when_its_future_is_dropped() {
3848        let mut server = started("turn").await;
3849        let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
3850        server
3851            .turn_start(TurnStartParams::text(&thread.id, "go"))
3852            .await
3853            .unwrap();
3854
3855        // Poll with a timeout that keeps expiring, so the future is dropped
3856        // over and over while messages arrive. Bounded by time, not by the
3857        // number of polls, so a slow machine only makes it take longer.
3858        let mut seen = Vec::new();
3859        let mut finished = false;
3860        let deadline = std::time::Instant::now() + Duration::from_secs(20);
3861        while std::time::Instant::now() < deadline {
3862            if let Ok(next) =
3863                tokio::time::timeout(Duration::from_micros(200), server.next_message()).await
3864            {
3865                let message = next.unwrap().expect("the stream ended early");
3866                if let ServerMessage::Notification(n) = &message {
3867                    finished |= n.turn_completed().is_some();
3868                }
3869                seen.push(message);
3870            }
3871            if finished {
3872                break;
3873            }
3874        }
3875        assert!(
3876            finished,
3877            "never saw the turn complete: {:?}",
3878            methods(&seen)
3879        );
3880        let methods = methods(&seen);
3881        // Every message the fixture sends after `initialized`, in order.
3882        let expected = [
3883            "remoteControl/status/changed",
3884            "thread/started",
3885            "thread/status/changed",
3886            "turn/started",
3887            "item/started",
3888            "item/agentMessage/delta",
3889            "item/completed",
3890            "thread/tokenUsage/updated",
3891            "thread/status/changed",
3892            "turn/completed",
3893        ];
3894        assert_eq!(methods, expected);
3895        server.shutdown().await.unwrap();
3896    }
3897
3898    #[test]
3899    fn turn_final_message_takes_the_last_final_answer_and_ignores_commentary() {
3900        let turn: Turn = serde_json::from_value(json!({
3901            "id": "t",
3902            "status": "completed",
3903            "items": [
3904                { "type": "agentMessage", "text": "working", "phase": "commentary" },
3905                { "type": "commandExecution", "text": "not a message", "phase": "final_answer" },
3906                { "type": "agentMessage", "text": "first", "phase": "final_answer" },
3907                { "type": "agentMessage", "text": "last", "phase": "final_answer" }
3908            ]
3909        }))
3910        .unwrap();
3911        assert_eq!(turn.final_message(), Some("last"));
3912    }
3913
3914    #[test]
3915    fn agent_messages_are_decoded_from_item_completed_only() {
3916        let message = |phase: Option<&str>| Notification {
3917            method: "item/completed".into(),
3918            params: json!({
3919                "item": {
3920                    "type": "agentMessage",
3921                    "id": "m",
3922                    "text": "DONE STEERED",
3923                    "phase": phase,
3924                },
3925                "threadId": "th",
3926                "turnId": "tu",
3927            }),
3928        };
3929        let answer = message(Some("final_answer")).agent_message().unwrap();
3930        assert_eq!(answer.text, "DONE STEERED");
3931        assert_eq!(
3932            (answer.thread_id.as_str(), answer.turn_id.as_str()),
3933            ("th", "tu")
3934        );
3935        assert!(answer.is_final_answer());
3936        assert!(
3937            !message(Some("commentary"))
3938                .agent_message()
3939                .unwrap()
3940                .is_final_answer()
3941        );
3942        assert!(!message(None).agent_message().unwrap().is_final_answer());
3943
3944        // Other items, other methods, and a delta are not agent messages.
3945        let mut command = message(None);
3946        command.params["item"]["type"] = json!("commandExecution");
3947        assert!(command.agent_message().is_none());
3948        let mut delta = message(None);
3949        delta.method = "item/agentMessage/delta".into();
3950        assert!(delta.agent_message().is_none());
3951    }
3952
3953    #[test]
3954    fn an_unknown_turn_status_is_kept_apart_from_the_known_ones() {
3955        let turn: Turn =
3956            serde_json::from_value(json!({ "id": "t", "status": "someFutureStatus" })).unwrap();
3957        assert_eq!(turn.status, TurnStatus::Unknown);
3958    }
3959
3960    #[test]
3961    fn only_a_well_formed_turn_completed_notification_decodes() {
3962        let other = Notification {
3963            method: "turn/started".into(),
3964            params: json!({}),
3965        };
3966        assert!(other.turn_completed().is_none());
3967        let malformed = Notification {
3968            method: "turn/completed".into(),
3969            params: json!({ "threadId": "x" }),
3970        };
3971        assert!(malformed.turn_completed().is_none());
3972    }
3973
3974    #[test]
3975    fn request_ids_round_trip_as_numbers_and_strings() {
3976        assert_eq!(serde_json::to_string(&RequestId::Number(7)).unwrap(), "7");
3977        assert_eq!(
3978            serde_json::to_string(&RequestId::String("a".into())).unwrap(),
3979            "\"a\""
3980        );
3981        assert_eq!(
3982            serde_json::from_str::<RequestId>("0").unwrap(),
3983            RequestId::Number(0)
3984        );
3985        assert_eq!(
3986            serde_json::from_str::<RequestId>("\"x\"").unwrap(),
3987            RequestId::String("x".into())
3988        );
3989    }
3990
3991    #[test]
3992    fn reply_lines_echo_the_servers_id() {
3993        let line = reply_line(
3994            &RequestId::Number(0),
3995            "result",
3996            &json!({ "decision": "decline" }),
3997        )
3998        .unwrap();
3999        assert_eq!(
4000            String::from_utf8(line).unwrap(),
4001            "{\"id\":0,\"result\":{\"decision\":\"decline\"}}\n"
4002        );
4003        let line = reply_line(
4004            &RequestId::String("r-1".into()),
4005            "error",
4006            &json!({ "code": -32601, "message": "no" }),
4007        )
4008        .unwrap();
4009        assert_eq!(
4010            String::from_utf8(line).unwrap(),
4011            "{\"id\":\"r-1\",\"error\":{\"code\":-32601,\"message\":\"no\"}}\n"
4012        );
4013    }
4014
4015    #[test]
4016    fn colour_codes_are_removed_from_server_logs() {
4017        let raw = "\u{1b}[2m2026-09-24T04:17:33Z\u{1b}[0m \u{1b}[31mERROR\u{1b}[0m worker quit";
4018        assert_eq!(strip_ansi(raw), "2026-09-24T04:17:33Z ERROR worker quit");
4019    }
4020
4021    #[test]
4022    fn a_line_that_is_not_a_message_is_ignored_and_bad_json_is_fatal() {
4023        let (events, mut received) = mpsc::unbounded_channel();
4024        let shared = Shared::new(events, None, Limits::default(), "test");
4025        assert!(route(r#"{"unrelated":true}"#, &shared).is_ok());
4026        assert!(
4027            route(
4028                r#"{"id":null,"error":{"code":-32600,"message":"x"}}"#,
4029                &shared
4030            )
4031            .is_ok()
4032        );
4033        assert!(route(r#"{"id":99,"result":{}}"#, &shared).is_ok());
4034        assert!(received.try_recv().is_err(), "nothing should be delivered");
4035
4036        assert!(route(r#"{"method":"a/b","params":{"k":1}}"#, &shared).is_ok());
4037        assert!(matches!(
4038            received.try_recv(),
4039            Ok(Event::Message(ServerMessage::Notification(n), _)) if n.method == "a/b"
4040        ));
4041        assert!(route(r#"{"method":"a/b","id":"s"}"#, &shared).is_ok());
4042        assert!(matches!(
4043            received.try_recv(),
4044            Ok(Event::Message(ServerMessage::Request(r), _)) if r.id == RequestId::String("s".into())
4045        ));
4046        assert!(matches!(
4047            route(r#"{"method": oops"#, &shared),
4048            Err(Closed::Broken(_))
4049        ));
4050    }
4051
4052    fn temp_log(label: &str) -> std::path::PathBuf {
4053        let path = std::env::temp_dir().join(format!(
4054            "codex-wrapper-{}-app-server-{label}.log",
4055            std::process::id()
4056        ));
4057        let _ = std::fs::remove_file(&path);
4058        path
4059    }
4060
4061    fn wire_lines(log: &std::path::Path) -> Vec<Value> {
4062        let lines = std::fs::read_to_string(log)
4063            .unwrap()
4064            .lines()
4065            .map(|line| serde_json::from_str(line).expect("every client line is JSON"))
4066            .collect();
4067        let _ = std::fs::remove_file(log);
4068        lines
4069    }
4070
4071    fn offline() -> Codex {
4072        // Never spawned: these settings are rejected first, and if one were
4073        // not, spawning this path would fail with a different error.
4074        Codex::builder()
4075            .binary("/nonexistent/codex-wrapper-test-binary")
4076            .build()
4077            .unwrap()
4078    }
4079
4080    #[test]
4081    fn initialize_carries_no_capabilities_unless_one_is_set() {
4082        let codex = offline();
4083        let params = AppServer::builder(&codex)
4084            .client_info("probe", "1")
4085            .initialize_params()
4086            .unwrap();
4087        assert_eq!(
4088            params,
4089            json!({ "clientInfo": { "name": "probe", "version": "1" } })
4090        );
4091    }
4092
4093    #[test]
4094    fn capabilities_are_kept_and_both_opt_out_sources_are_combined_once_each() {
4095        let codex = offline();
4096        let params = AppServer::builder(&codex)
4097            .client_info("probe", "1")
4098            .opt_out_notification("item/agentMessage/delta")
4099            .experimental_api(true)
4100            .capability(
4101                "optOutNotificationMethods",
4102                json!(["thread/status/changed", "item/agentMessage/delta"]),
4103            )
4104            .capability("someFutureCapability", json!({ "k": [1, 2] }))
4105            .opt_out_notification("mcpServer/startupStatus/updated")
4106            .opt_out_notification("thread/status/changed")
4107            .initialize_params()
4108            .unwrap();
4109        assert_eq!(
4110            params["capabilities"],
4111            json!({
4112                "experimentalApi": true,
4113                "someFutureCapability": { "k": [1, 2] },
4114                "optOutNotificationMethods": [
4115                    "thread/status/changed",
4116                    "item/agentMessage/delta",
4117                    "mcpServer/startupStatus/updated"
4118                ]
4119            })
4120        );
4121
4122        // A null list is sent as given, or replaced by the builder's list.
4123        let null = AppServer::builder(&codex).capability(OPT_OUT_KEY, Value::Null);
4124        assert_eq!(
4125            null.initialize_params().unwrap()["capabilities"],
4126            json!({ "optOutNotificationMethods": null })
4127        );
4128        let merged = null.opt_out_notification("a/b");
4129        assert_eq!(
4130            merged.initialize_params().unwrap()["capabilities"],
4131            json!({ "optOutNotificationMethods": ["a/b"] })
4132        );
4133    }
4134
4135    #[tokio::test]
4136    async fn invalid_settings_are_rejected_before_anything_is_spawned() {
4137        let codex = offline();
4138        for value in [json!("item/agentMessage/delta"), json!([1]), json!({})] {
4139            let error = AppServer::builder(&codex)
4140                .capability(OPT_OUT_KEY, value.clone())
4141                .start()
4142                .await
4143                .unwrap_err();
4144            assert!(
4145                matches!(&error, Error::AppServerConfig { message } if message.contains(OPT_OUT_KEY)),
4146                "{value}: {error:?}"
4147            );
4148        }
4149        let error = AppServer::builder(&codex)
4150            .connect_unix("")
4151            .start()
4152            .await
4153            .unwrap_err();
4154        assert!(matches!(error, Error::AppServerConfig { .. }), "{error:?}");
4155    }
4156
4157    #[tokio::test]
4158    async fn the_first_handshake_sends_the_combined_capabilities() {
4159        let log = temp_log("capabilities");
4160        let codex = fake("turn")
4161            .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
4162            .build()
4163            .unwrap();
4164        let server = AppServer::builder(&codex)
4165            .client_info("probe", "1.2.3")
4166            .experimental_api(true)
4167            .capability(OPT_OUT_KEY, json!(["thread/status/changed"]))
4168            .opt_out_notification("item/agentMessage/delta")
4169            .start()
4170            .await
4171            .unwrap();
4172        server.shutdown().await.unwrap();
4173        let lines = wire_lines(&log);
4174        assert_eq!(
4175            lines[0],
4176            json!({
4177                "id": 0,
4178                "method": "initialize",
4179                "params": {
4180                    "clientInfo": { "name": "probe", "version": "1.2.3" },
4181                    "capabilities": {
4182                        "experimentalApi": true,
4183                        "optOutNotificationMethods": [
4184                            "thread/status/changed",
4185                            "item/agentMessage/delta"
4186                        ]
4187                    }
4188                }
4189            })
4190        );
4191        assert_eq!(lines[1], json!({ "method": "initialized" }));
4192    }
4193
4194    #[test]
4195    fn a_budget_counts_messages_and_bytes_and_frees_them_on_release() {
4196        let budget = Budget::new(
4197            Some(2),
4198            Some(10),
4199            AppServerLimit::QueuedMessages,
4200            AppServerLimit::QueuedBytes,
4201        );
4202        budget.reserve(4).unwrap();
4203        budget.reserve(4).unwrap();
4204        assert!(matches!(
4205            budget.reserve(1),
4206            Err(Closed::Limit {
4207                limit: AppServerLimit::QueuedMessages,
4208                max: 2
4209            })
4210        ));
4211        budget.release(4);
4212        assert!(matches!(
4213            budget.reserve(7),
4214            Err(Closed::Limit {
4215                limit: AppServerLimit::QueuedBytes,
4216                max: 10
4217            })
4218        ));
4219        // A refused reservation counts nothing.
4220        assert_eq!(budget.used(), (1, 4));
4221        budget.reserve(6).unwrap();
4222        assert_eq!(budget.used(), (2, 10));
4223
4224        let unlimited = Budget::new(
4225            None,
4226            None,
4227            AppServerLimit::QueuedMessages,
4228            AppServerLimit::QueuedBytes,
4229        );
4230        for _ in 0..1000 {
4231            unlimited.reserve(usize::MAX / 2).unwrap();
4232        }
4233    }
4234
4235    #[test]
4236    fn queued_events_count_until_read_and_answers_never_wait_behind_them() {
4237        let line = r#"{"method":"a/b"}"#;
4238        let cost = line.len() + 1;
4239        let (events, mut received) = mpsc::unbounded_channel();
4240        let limits = Limits {
4241            queued_messages: Some(2),
4242            ..Limits::default()
4243        };
4244        let shared = Shared::new(events, None, limits, "test");
4245        route(line, &shared).unwrap();
4246        route(line, &shared).unwrap();
4247        assert_eq!(shared.inbound.used(), (2, 2 * cost));
4248
4249        // The queue is full, and an answer still reaches its request.
4250        let (waiter, mut answer) = oneshot::channel();
4251        locked(&shared.state).pending.insert(7, waiter);
4252        route(r#"{"id":7,"result":{"ok":true}}"#, &shared).unwrap();
4253        assert!(matches!(answer.try_recv(), Ok(Reply::Result(v)) if v["ok"] == true));
4254
4255        assert!(matches!(
4256            route(line, &shared),
4257            Err(Closed::Limit {
4258                limit: AppServerLimit::QueuedMessages,
4259                max: 2
4260            })
4261        ));
4262        // Reading one, as `next_message` does, makes room for one more.
4263        let Ok(Event::Message(_, bytes)) = received.try_recv() else {
4264            panic!("a message was queued");
4265        };
4266        assert_eq!(bytes, cost);
4267        shared.inbound.release(bytes);
4268        route(line, &shared).unwrap();
4269
4270        let (events, _received) = mpsc::unbounded_channel();
4271        let limits = Limits {
4272            queued_bytes: Some(2 * cost),
4273            ..Limits::default()
4274        };
4275        let shared = Shared::new(events, None, limits, "test");
4276        route(line, &shared).unwrap();
4277        route(line, &shared).unwrap();
4278        assert!(matches!(
4279            route(line, &shared),
4280            Err(Closed::Limit {
4281                limit: AppServerLimit::QueuedBytes,
4282                ..
4283            })
4284        ));
4285    }
4286
4287    #[tokio::test]
4288    async fn a_line_longer_than_the_frame_limit_is_rejected_without_buffering_it() {
4289        let read = |input: &'static [u8], max: usize| async move {
4290            let mut reader = BufReader::new(input);
4291            read_frame(&mut reader, &mut 0, None, Some(max), &None).await
4292        };
4293        assert_eq!(
4294            read(b"abc\n", 4)
4295                .await
4296                .unwrap()
4297                .as_ref()
4298                .map(|(line, _)| line.as_str()),
4299            Some("abc")
4300        );
4301        assert!(matches!(
4302            read(b"abc\n", 3).await,
4303            Err(Closed::Limit {
4304                limit: AppServerLimit::FrameBytes,
4305                max: 3
4306            })
4307        ));
4308
4309        // A line that never ends: bounded by the limit, not the input.
4310        let mut endless = BufReader::new(tokio::io::repeat(b'x'));
4311        let result = tokio::time::timeout(
4312            Duration::from_secs(10),
4313            read_frame(&mut endless, &mut 0, None, Some(64 * 1024), &None),
4314        )
4315        .await
4316        .expect("an unterminated line was read without bound");
4317        assert!(matches!(
4318            result,
4319            Err(Closed::Limit {
4320                limit: AppServerLimit::FrameBytes,
4321                ..
4322            })
4323        ));
4324    }
4325
4326    #[tokio::test]
4327    async fn the_frame_limit_ends_the_session_and_kills_the_server() {
4328        let pid = Arc::new(Mutex::new(None));
4329        let observed = Arc::clone(&pid);
4330        let codex = fake("flood")
4331            .on_spawn(Arc::new(move |info| {
4332                *observed.lock().unwrap() = Some(info.pid);
4333            }))
4334            .build()
4335            .unwrap();
4336        let mut server = AppServer::builder(&codex)
4337            .max_frame_bytes(1024)
4338            .start()
4339            .await
4340            .unwrap();
4341        let (_, error) = read_until_error(&mut server).await;
4342        assert!(
4343            matches!(
4344                error,
4345                Error::AppServerLimitExceeded {
4346                    limit: AppServerLimit::FrameBytes,
4347                    max: 1024
4348                }
4349            ),
4350            "{error:?}"
4351        );
4352        let pid = pid.lock().unwrap().expect("the server was spawned");
4353        assert!(wait_until_gone(pid).await, "the server ({pid}) survived");
4354    }
4355
4356    async fn wait_until_closed(server: &AppServer) {
4357        for _ in 0..2000 {
4358            if server.handle.shared.closed_reason().is_some() {
4359                return;
4360            }
4361            tokio::time::sleep(Duration::from_millis(10)).await;
4362        }
4363        panic!("the session never failed");
4364    }
4365
4366    async fn read_until_error(server: &mut AppServer) -> (Vec<ServerMessage>, Error) {
4367        let mut seen = Vec::new();
4368        loop {
4369            let next = tokio::time::timeout(Duration::from_secs(10), server.next_message())
4370                .await
4371                .expect("the stream should end with an error");
4372            match next {
4373                Ok(Some(message)) => seen.push(message),
4374                Ok(None) => panic!("the stream ended without an error: {:?}", methods(&seen)),
4375                Err(error) => return (seen, error),
4376            }
4377        }
4378    }
4379
4380    #[tokio::test]
4381    async fn answers_pass_a_burst_of_unread_events_and_reading_them_frees_the_queue() {
4382        // remoteControl/status/changed, 30 status changes, thread/started.
4383        let codex = fake("burst")
4384            .env("FAKE_APP_SERVER_BURST", "30")
4385            .build()
4386            .unwrap();
4387        let mut server = AppServer::builder(&codex)
4388            .max_queued_messages(32)
4389            .start()
4390            .await
4391            .unwrap();
4392        // Answered while the burst sits unread in the queue.
4393        server.thread_start(ThreadStartParams::new()).await.unwrap();
4394        for _ in 0..32 {
4395            tokio::time::timeout(Duration::from_secs(10), server.next_message())
4396                .await
4397                .unwrap()
4398                .unwrap()
4399                .unwrap();
4400        }
4401        assert_eq!(server.handle.shared.inbound.used(), (0, 0));
4402        // Another 31 fit only because the first 32 were read.
4403        server.thread_start(ThreadStartParams::new()).await.unwrap();
4404        for _ in 0..31 {
4405            tokio::time::timeout(Duration::from_secs(10), server.next_message())
4406                .await
4407                .unwrap()
4408                .unwrap()
4409                .unwrap();
4410        }
4411        server.shutdown().await.unwrap();
4412    }
4413
4414    #[tokio::test]
4415    async fn a_queue_overflow_fails_the_request_waiting_behind_it() {
4416        let codex = fake_with_grace("burst", FORCED_STOP_GRACE)
4417            .env("FAKE_APP_SERVER_BURST", "30")
4418            .build()
4419            .unwrap();
4420        let mut server = AppServer::builder(&codex)
4421            .max_queued_messages(5)
4422            .start()
4423            .await
4424            .unwrap();
4425        let error = server
4426            .thread_start(ThreadStartParams::new())
4427            .await
4428            .unwrap_err();
4429        assert!(
4430            matches!(
4431                error,
4432                Error::AppServerLimitExceeded {
4433                    limit: AppServerLimit::QueuedMessages,
4434                    max: 5
4435                }
4436            ),
4437            "{error:?}"
4438        );
4439        let (seen, error) = read_until_error(&mut server).await;
4440        assert_eq!(seen.len(), 5);
4441        assert!(matches!(error, Error::AppServerLimitExceeded { .. }));
4442        server.terminate().await.unwrap();
4443    }
4444
4445    /// Neither an approval request nor a turn's terminal event is dropped to
4446    /// stay under the limit: the one that does not fit ends the session, and
4447    /// the caller sees the error after the messages that did fit.
4448    #[tokio::test]
4449    async fn approvals_and_terminal_events_that_do_not_fit_fail_the_session() {
4450        // Five messages precede the approval request, ten end the turn.
4451        for (mode, max, last_fitting) in [
4452            ("approval", 5, "item/started"),
4453            ("turn", 9, "thread/status/changed"),
4454        ] {
4455            let codex = fake_with_grace(mode, FORCED_STOP_GRACE).build().unwrap();
4456            let mut server = AppServer::builder(&codex)
4457                .max_queued_messages(max)
4458                .start()
4459                .await
4460                .unwrap();
4461            let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
4462            server
4463                .turn_start(TurnStartParams::text(&thread.id, "go"))
4464                .await
4465                .unwrap();
4466            // Read nothing until the overflow, so it happens where expected.
4467            wait_until_closed(&server).await;
4468
4469            let (seen, error) = read_until_error(&mut server).await;
4470            assert!(
4471                matches!(
4472                    error,
4473                    Error::AppServerLimitExceeded {
4474                        limit: AppServerLimit::QueuedMessages,
4475                        max: m
4476                    } if m == max
4477                ),
4478                "{mode}: {error:?}"
4479            );
4480            assert_eq!(seen.len(), max, "{mode}");
4481            assert_eq!(methods(&seen).last(), Some(&last_fitting), "{mode}");
4482            assert!(
4483                !seen.iter().any(|m| matches!(m, ServerMessage::Request(_))),
4484                "{mode}"
4485            );
4486            assert!(server.next_message().await.unwrap().is_none());
4487
4488            // Nothing more is accepted.
4489            let again = server.request("thread/start", json!({})).await.unwrap_err();
4490            assert!(
4491                matches!(again, Error::AppServerLimitExceeded { .. }),
4492                "{again:?}"
4493            );
4494            assert!(server.respond(RequestId::Number(0), json!({})).is_err());
4495            server.terminate().await.unwrap();
4496        }
4497    }
4498
4499    #[tokio::test]
4500    async fn a_line_being_written_holds_its_place_until_the_write_finishes() {
4501        let (stdin, mut server_end) = tokio::io::duplex(8);
4502        let line = notification_line("a/b", &json!({ "pad": "x".repeat(10) })).unwrap();
4503        let cost = line.len();
4504        let limits = Limits {
4505            // Room for one line, not two.
4506            writer_bytes: Some(cost + cost / 2),
4507            ..Limits::default()
4508        };
4509        let (events, _received) = mpsc::unbounded_channel();
4510        let shared = Arc::new(Shared::new(events, None, limits, "test"));
4511        let (writer, lines) = mpsc::unbounded_channel();
4512        let task = tokio::spawn(write_stdin(stdin, lines, Arc::clone(&shared)));
4513        let handle = AppServerHandle {
4514            shared: Arc::clone(&shared),
4515            writer,
4516            timeout: None,
4517        };
4518
4519        handle
4520            .notify("a/b", json!({ "pad": "x".repeat(10) }))
4521            .unwrap();
4522        // The writer has taken the line and is stuck: the pipe holds 8 bytes.
4523        tokio::time::sleep(Duration::from_millis(50)).await;
4524        assert_eq!(shared.outbound.used(), (1, cost));
4525
4526        let drained = |shared: Arc<Shared>| async move {
4527            for _ in 0..500 {
4528                if shared.outbound.used() == (0, 0) {
4529                    return;
4530                }
4531                tokio::time::sleep(Duration::from_millis(10)).await;
4532            }
4533            panic!(
4534                "a written line kept its place: {:?}",
4535                shared.outbound.used()
4536            );
4537        };
4538        let mut received = vec![0; cost];
4539        server_end.read_exact(&mut received).await.unwrap();
4540        assert_eq!(received, line);
4541        drained(Arc::clone(&shared)).await;
4542        // Fits again now that the first line is written.
4543        handle
4544            .notify("a/b", json!({ "pad": "x".repeat(10) }))
4545            .unwrap();
4546        server_end.read_exact(&mut received).await.unwrap();
4547        drained(Arc::clone(&shared)).await;
4548
4549        // Two at once do not fit while the writer is stuck on the first.
4550        handle
4551            .notify("a/b", json!({ "pad": "x".repeat(10) }))
4552            .unwrap();
4553        let error = handle
4554            .notify("a/b", json!({ "pad": "x".repeat(10) }))
4555            .unwrap_err();
4556        assert!(
4557            matches!(
4558                error,
4559                Error::AppServerLimitExceeded {
4560                    limit: AppServerLimit::WriterQueueBytes,
4561                    ..
4562                }
4563            ),
4564            "{error:?}"
4565        );
4566        drop(handle);
4567        drop(server_end);
4568        tokio::time::timeout(Duration::from_secs(10), task)
4569            .await
4570            .expect("the writer stopped")
4571            .unwrap();
4572        assert_eq!(shared.outbound.used(), (0, 0));
4573    }
4574
4575    #[tokio::test]
4576    async fn a_server_that_stops_reading_fails_the_session_at_the_writer_limit() {
4577        let pid = Arc::new(Mutex::new(None));
4578        let observed = Arc::clone(&pid);
4579        let codex = fake("stops-reading")
4580            .on_spawn(Arc::new(move |info| {
4581                *observed.lock().unwrap() = Some(info.pid);
4582            }))
4583            .build()
4584            .unwrap();
4585        let limit = 256 * 1024;
4586        let server = AppServer::builder(&codex)
4587            .max_writer_queue_bytes(limit)
4588            .start()
4589            .await
4590            .unwrap();
4591        let handle = server.handle();
4592        let waiting = tokio::spawn(async move { handle.request("thread/start", json!({})).await });
4593
4594        let pad = "x".repeat(4096);
4595        let mut failure = None;
4596        // Far more than a pipe and the limit hold together.
4597        for _ in 0..4096 {
4598            match server.notify("fixture/pad", json!({ "pad": pad })) {
4599                // Let the writer fill the pipe, so the limit is reached with
4600                // a write blocked rather than only by queueing.
4601                Ok(()) => tokio::task::yield_now().await,
4602                Err(error) => {
4603                    failure = Some(error);
4604                    break;
4605                }
4606            }
4607        }
4608        let error = failure.expect("the writer limit was never reached");
4609        assert!(
4610            matches!(
4611                error,
4612                Error::AppServerLimitExceeded {
4613                    limit: AppServerLimit::WriterQueueBytes,
4614                    max
4615                } if max == limit
4616            ),
4617            "{error:?}"
4618        );
4619        let waited = tokio::time::timeout(Duration::from_secs(10), waiting)
4620            .await
4621            .expect("the waiting request was not settled")
4622            .unwrap()
4623            .unwrap_err();
4624        assert!(
4625            matches!(waited, Error::AppServerLimitExceeded { .. }),
4626            "{waited:?}"
4627        );
4628        assert!(server.notify("fixture/pad", json!({})).is_err());
4629
4630        let pid = pid.lock().unwrap().expect("the server was spawned");
4631        assert!(wait_until_gone(pid).await, "the server ({pid}) survived");
4632        server.terminate().await.unwrap();
4633    }
4634    struct SocketFixture {
4635        path: PathBuf,
4636        listener: tokio::net::UnixListener,
4637    }
4638    impl SocketFixture {
4639        fn new() -> Self {
4640            static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
4641            let path = std::env::temp_dir().join(format!(
4642                "cw-{}-{}.sock",
4643                std::process::id(),
4644                NEXT.fetch_add(1, Ordering::Relaxed)
4645            ));
4646            let listener = tokio::net::UnixListener::bind(&path).unwrap();
4647            Self { path, listener }
4648        }
4649        async fn accept(&self) -> tokio_tungstenite::WebSocketStream<tokio::net::UnixStream> {
4650            let (stream, _) = self.listener.accept().await.unwrap();
4651            let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
4652            let init: Value =
4653                serde_json::from_str(socket.next().await.unwrap().unwrap().to_text().unwrap())
4654                    .unwrap();
4655            assert_eq!(init["method"], "initialize");
4656            assert_eq!(init["params"]["capabilities"]["experimentalApi"], true);
4657            socket
4658                .send(WsMessage::Text(
4659                    json!({"id":init["id"],"result":{"userAgent":"fixture"}})
4660                        .to_string()
4661                        .into(),
4662                ))
4663                .await
4664                .unwrap();
4665            let initialized: Value =
4666                serde_json::from_str(socket.next().await.unwrap().unwrap().to_text().unwrap())
4667                    .unwrap();
4668            assert_eq!(initialized["method"], "initialized");
4669            socket
4670        }
4671        fn builder<'a>(&self, codex: &'a Codex) -> AppServerBuilder<'a> {
4672            AppServer::builder(codex)
4673                .connect_unix(&self.path)
4674                .experimental_api(true)
4675        }
4676    }
4677    impl Drop for SocketFixture {
4678        fn drop(&mut self) {
4679            let _ = std::fs::remove_file(&self.path);
4680        }
4681    }
4682
4683    #[tokio::test]
4684    async fn attached_clients_own_no_process_and_teardown_is_connection_local() {
4685        let fixture = SocketFixture::new();
4686        let codex = Codex::builder()
4687            .binary("/bin/echo")
4688            .on_spawn(Arc::new(|_| panic!("attached mode must not spawn")))
4689            .timeout(Duration::from_secs(5))
4690            .build()
4691            .unwrap();
4692        let (client, peer) = tokio::join!(fixture.builder(&codex).start(), fixture.accept());
4693        let client = client.unwrap();
4694        let (other, mut other_peer) =
4695            tokio::join!(fixture.builder(&codex).start(), fixture.accept());
4696        let other = other.unwrap();
4697        assert_eq!(client.pid(), None);
4698        assert!(!client.transport().owns_server());
4699        assert!(fixture.builder(&codex).args().is_empty());
4700        assert!(fixture.builder(&codex).to_command_string().is_empty());
4701        let handle = client.handle();
4702        let pending = tokio::spawn(async move { handle.request("thread/list", Value::Null).await });
4703        let mut peer = peer;
4704        peer.next().await.unwrap().unwrap();
4705        drop(client);
4706        assert!(pending.await.unwrap().is_err());
4707        tokio::time::timeout(Duration::from_secs(2), peer.next())
4708            .await
4709            .unwrap();
4710        let answer = async {
4711            let request: Value =
4712                serde_json::from_str(other_peer.next().await.unwrap().unwrap().to_text().unwrap())
4713                    .unwrap();
4714            other_peer
4715                .send(WsMessage::Text(
4716                    json!({"id":request["id"],"result":{"data":[]}})
4717                        .to_string()
4718                        .into(),
4719                ))
4720                .await
4721                .unwrap();
4722        };
4723        let (result, ()) = tokio::join!(other.request("thread/list", Value::Null), answer);
4724        assert_eq!(result.unwrap(), json!({"data":[]}));
4725        other.shutdown().await.unwrap();
4726        tokio::time::timeout(Duration::from_secs(2), other_peer.next())
4727            .await
4728            .unwrap();
4729        // The listening endpoint is still usable after both owners disappear.
4730        let (third, mut peer) = tokio::join!(fixture.builder(&codex).start(), fixture.accept());
4731        third.unwrap().terminate().await.unwrap();
4732        tokio::time::timeout(Duration::from_secs(2), peer.next())
4733            .await
4734            .unwrap();
4735    }
4736
4737    #[tokio::test]
4738    async fn attached_peer_loss_fails_pending_without_reading_events() {
4739        let fixture = SocketFixture::new();
4740        let codex = offline();
4741        let (client, mut peer) = tokio::join!(fixture.builder(&codex).start(), fixture.accept());
4742        let client = client.unwrap();
4743        let handle = client.handle();
4744        let pending = tokio::spawn(async move { handle.request("thread/list", Value::Null).await });
4745        peer.next().await.unwrap().unwrap();
4746        drop(peer);
4747        let result = tokio::time::timeout(Duration::from_secs(2), pending)
4748            .await
4749            .unwrap()
4750            .unwrap();
4751        assert!(matches!(result, Err(Error::AppServerProtocol { .. })));
4752        assert!(client.notify("initialized", Value::Null).is_err());
4753    }
4754
4755    #[tokio::test]
4756    async fn attached_handshake_cancellation_closes_the_socket() {
4757        let fixture = SocketFixture::new();
4758        let socket = fixture.path.clone();
4759        let task = tokio::spawn(async move {
4760            let codex = offline();
4761            AppServer::builder(&codex)
4762                .connect_unix(socket)
4763                .start()
4764                .await
4765        });
4766        let (stream, _) = fixture.listener.accept().await.unwrap();
4767        let mut peer = tokio_tungstenite::accept_async(stream).await.unwrap();
4768        peer.next().await.unwrap().unwrap();
4769        task.abort();
4770        assert!(task.await.unwrap_err().is_cancelled());
4771        tokio::time::timeout(Duration::from_secs(2), peer.next())
4772            .await
4773            .unwrap();
4774    }
4775
4776    #[tokio::test]
4777    async fn attached_frames_queues_and_timeouts_fail_explicitly() {
4778        for mode in ["frame", "queue", "timeout", "binary"] {
4779            let fixture = SocketFixture::new();
4780            let codex = Codex::builder()
4781                .binary("/bin/echo")
4782                .timeout(Duration::from_millis(500))
4783                .build()
4784                .unwrap();
4785            let builder = fixture
4786                .builder(&codex)
4787                .max_frame_bytes(256)
4788                .max_queued_messages(1);
4789            let (client, mut peer) = tokio::join!(builder.start(), fixture.accept());
4790            let mut client = client.unwrap();
4791            let act = async {
4792                let request: Value =
4793                    serde_json::from_str(peer.next().await.unwrap().unwrap().to_text().unwrap())
4794                        .unwrap();
4795                match mode {
4796                    "frame" => peer
4797                        .send(WsMessage::Text("x".repeat(257).into()))
4798                        .await
4799                        .unwrap(),
4800                    "binary" => peer
4801                        .send(WsMessage::Binary(vec![0; 4].into()))
4802                        .await
4803                        .unwrap(),
4804                    "queue" => {
4805                        let event = WsMessage::Text(json!({"method":"thread/status/changed","params":{"threadId":"fixture","status":{"type":"idle"}}}).to_string().into());
4806                        peer.send(event.clone()).await.unwrap();
4807                        peer.send(event).await.unwrap();
4808                    }
4809                    _ => {
4810                        let _ = request;
4811                    }
4812                }
4813            };
4814            let (result, ()) = tokio::join!(client.request("thread/list", Value::Null), act);
4815            match mode {
4816                "frame" => assert!(matches!(
4817                    result,
4818                    Err(Error::AppServerLimitExceeded {
4819                        limit: AppServerLimit::FrameBytes,
4820                        max: 256
4821                    })
4822                )),
4823                "queue" => {
4824                    assert!(matches!(
4825                        result,
4826                        Err(Error::AppServerLimitExceeded {
4827                            limit: AppServerLimit::QueuedMessages,
4828                            max: 1
4829                        })
4830                    ));
4831                    assert!(client.next_message().await.unwrap().is_some());
4832                    assert!(matches!(
4833                        client.next_message().await,
4834                        Err(Error::AppServerLimitExceeded { .. })
4835                    ));
4836                }
4837                "timeout" => assert!(matches!(result, Err(Error::Timeout { .. }))),
4838                _ => assert!(matches!(result, Err(Error::AppServerProtocol { .. }))),
4839            }
4840            client.shutdown().await.unwrap();
4841        }
4842    }
4843
4844    #[tokio::test]
4845    async fn attached_response_routing_and_ping_progress_without_consuming_events() {
4846        let fixture = SocketFixture::new();
4847        let codex = offline();
4848        let (client, mut peer) = tokio::join!(
4849            fixture.builder(&codex).max_queued_messages(1).start(),
4850            fixture.accept()
4851        );
4852        let mut client = client.unwrap();
4853        let act = async {
4854            let request: Value =
4855                serde_json::from_str(peer.next().await.unwrap().unwrap().to_text().unwrap())
4856                    .unwrap();
4857            peer.send(WsMessage::Text(
4858                json!({"method":"thread/status/changed","params":{}})
4859                    .to_string()
4860                    .into(),
4861            ))
4862            .await
4863            .unwrap();
4864            peer.send(WsMessage::Ping(b"fixture".to_vec().into()))
4865                .await
4866                .unwrap();
4867            let pong = tokio::time::timeout(Duration::from_secs(2), peer.next())
4868                .await
4869                .unwrap()
4870                .unwrap()
4871                .unwrap();
4872            assert!(matches!(pong, WsMessage::Pong(_)));
4873            peer.send(WsMessage::Text(
4874                json!({"id":request["id"],"result":{"data":[]}})
4875                    .to_string()
4876                    .into(),
4877            ))
4878            .await
4879            .unwrap();
4880        };
4881        let (result, ()) = tokio::join!(client.request("thread/list", Value::Null), act);
4882        assert!(result.is_ok());
4883        assert!(client.next_message().await.unwrap().is_some());
4884        client.shutdown().await.unwrap();
4885    }
4886
4887    #[tokio::test]
4888    async fn closure_wakes_idle_and_blocked_writers_with_surviving_handles() {
4889        for blocked in [false, true] {
4890            let (stdin, _peer) = tokio::io::duplex(1);
4891            let (events, _received) = mpsc::unbounded_channel();
4892            let shared = Arc::new(Shared::new(events, None, Limits::default(), "test"));
4893            let (writer, receiver) = mpsc::unbounded_channel();
4894            let handle = AppServerHandle {
4895                shared: Arc::clone(&shared),
4896                writer,
4897                timeout: None,
4898            };
4899            let task = tokio::spawn(write_stdin(stdin, receiver, Arc::clone(&shared)));
4900            if blocked {
4901                handle.notify("initialized", Value::Null).unwrap();
4902            }
4903            tokio::task::yield_now().await;
4904            shared.fail(Closed::Limit {
4905                limit: AppServerLimit::QueuedMessages,
4906                max: 0,
4907            });
4908            tokio::time::timeout(Duration::from_secs(2), task)
4909                .await
4910                .unwrap()
4911                .unwrap();
4912            assert_eq!(*locked(&shared.outbound.used), (0, 0));
4913            assert!(handle.notify("initialized", Value::Null).is_err());
4914        }
4915    }
4916
4917    #[tokio::test]
4918    async fn queued_bytes_use_actual_crlf_and_unterminated_wire_lengths() {
4919        let line = r#"{"method":"thread/status/changed","params":{}}"#;
4920        for delimiter in ["\r\n", "\n", ""] {
4921            let input = format!("{line}{delimiter}");
4922            let wire_bytes = input.len();
4923            let mut reader = BufReader::new(input.as_bytes());
4924            let (text, bytes) = read_frame(&mut reader, &mut 0, None, None, &None)
4925                .await
4926                .unwrap()
4927                .unwrap();
4928            assert_eq!(text, line);
4929            assert_eq!(bytes, wire_bytes);
4930            let (events, _received) = mpsc::unbounded_channel();
4931            let shared = Shared::new(
4932                events,
4933                None,
4934                Limits {
4935                    queued_bytes: Some(wire_bytes),
4936                    ..Limits::default()
4937                },
4938                "test",
4939            );
4940            route_bytes(&text, bytes, &shared).unwrap();
4941            assert_eq!(*locked(&shared.inbound.used), (1, wire_bytes));
4942            assert!(route_bytes(&text, bytes, &shared).is_err());
4943        }
4944    }
4945    #[tokio::test]
4946    async fn attached_fragmented_messages_cannot_bypass_frame_budget() {
4947        use tokio_tungstenite::tungstenite::protocol::frame::{
4948            Frame,
4949            coding::{Data, OpCode},
4950        };
4951        let fixture = SocketFixture::new();
4952        let codex = offline();
4953        let (client, mut peer) = tokio::join!(
4954            fixture.builder(&codex).max_frame_bytes(256).start(),
4955            fixture.accept()
4956        );
4957        let client = client.unwrap();
4958        let send = async {
4959            peer.next().await.unwrap().unwrap();
4960            for (opcode, final_) in [
4961                (Data::Text, false),
4962                (Data::Continue, false),
4963                (Data::Continue, true),
4964            ] {
4965                peer.send(WsMessage::Frame(Frame::message(
4966                    vec![b'x'; 100],
4967                    OpCode::Data(opcode),
4968                    final_,
4969                )))
4970                .await
4971                .unwrap();
4972            }
4973        };
4974        let (result, ()) = tokio::join!(client.request("thread/list", Value::Null), send);
4975        assert!(matches!(
4976            result,
4977            Err(Error::AppServerLimitExceeded {
4978                limit: AppServerLimit::FrameBytes,
4979                max: 256
4980            })
4981        ));
4982    }
4983
4984    #[tokio::test]
4985    async fn attached_blocked_writer_overflow_settles_and_releases_reservations() {
4986        let fixture = SocketFixture::new();
4987        let codex = offline();
4988        let (client, _peer) = tokio::join!(
4989            fixture.builder(&codex).max_writer_queue_messages(1).start(),
4990            fixture.accept()
4991        );
4992        let client = client.unwrap();
4993        let handle = client.handle();
4994        let pending = tokio::spawn(async move {
4995            handle
4996                .request(
4997                    "thread/start",
4998                    json!({"fixture": "x".repeat(4 * 1024 * 1024)}),
4999                )
5000                .await
5001        });
5002        tokio::time::timeout(Duration::from_secs(2), async {
5003            while locked(&client.handle.shared.outbound.used).0 == 0 {
5004                tokio::task::yield_now().await;
5005            }
5006        })
5007        .await
5008        .unwrap();
5009        assert!(matches!(
5010            client.notify("initialized", Value::Null),
5011            Err(Error::AppServerLimitExceeded {
5012                limit: AppServerLimit::WriterQueueMessages,
5013                max: 1
5014            })
5015        ));
5016        assert!(matches!(
5017            pending.await.unwrap(),
5018            Err(Error::AppServerLimitExceeded { .. })
5019        ));
5020        tokio::time::timeout(Duration::from_secs(2), async {
5021            while *locked(&client.handle.shared.outbound.used) != (0, 0) {
5022                tokio::task::yield_now().await;
5023            }
5024        })
5025        .await
5026        .unwrap();
5027        client.shutdown().await.unwrap();
5028    }
5029    #[tokio::test]
5030    async fn review_regression_shutdown_notifications_preserve_accepted_writes() {
5031        let (stdin, mut peer) = tokio::io::duplex(4);
5032        let (events, _received) = mpsc::unbounded_channel();
5033        let shared = Arc::new(Shared::new(events, None, Limits::default(), "test"));
5034        let (writer, receiver) = mpsc::unbounded_channel();
5035        let handle = AppServerHandle {
5036            shared: Arc::clone(&shared),
5037            writer,
5038            timeout: None,
5039        };
5040        let expected = notification_line("initialized", &Value::Null).unwrap();
5041        handle.notify("initialized", Value::Null).unwrap();
5042        let task = tokio::spawn(write_stdin(stdin, receiver, Arc::clone(&shared)));
5043        tokio::task::yield_now().await;
5044        shared.end(Closed::Terminated, false);
5045        if let Err(reason) = route(r#"{"method":"thread/status/changed","params":{}}"#, &shared) {
5046            shared.fatal(reason);
5047        }
5048        handle.writer.send(Outgoing::Close).unwrap();
5049        let mut output = Vec::new();
5050        tokio::time::timeout(Duration::from_secs(2), peer.read_to_end(&mut output))
5051            .await
5052            .unwrap()
5053            .unwrap();
5054        task.await.unwrap();
5055        assert_eq!(output, expected, "shutdown truncated an accepted message");
5056    }
5057
5058    #[tokio::test]
5059    async fn review_regression_peer_close_is_acknowledged() {
5060        let fixture = SocketFixture::new();
5061        let codex = offline();
5062        let (client, mut peer) = tokio::join!(fixture.builder(&codex).start(), fixture.accept());
5063        let client = client.unwrap();
5064        peer.close(None).await.unwrap();
5065        let reply = tokio::time::timeout(Duration::from_secs(2), peer.next())
5066            .await
5067            .unwrap();
5068        assert!(
5069            matches!(reply, Some(Ok(WsMessage::Close(_)))),
5070            "missing close reply: {reply:?}"
5071        );
5072        assert!(client.request("thread/list", Value::Null).await.is_err());
5073    }
5074}
5075
5076#[cfg(all(test, windows))]
5077#[tokio::test]
5078async fn a_fatal_limit_terminates_the_windows_child_without_an_event_consumer() {
5079    use tokio::process::Command;
5080
5081    let mut child = Command::new("powershell.exe")
5082        .args(["-NoProfile", "-Command", "Start-Sleep -Seconds 60"])
5083        .kill_on_drop(true)
5084        .spawn()
5085        .unwrap();
5086    let (events, _unread) = mpsc::unbounded_channel();
5087    let shared = Shared::new(
5088        events,
5089        Some(KillTarget {
5090            pid: child.id(),
5091            group: false,
5092            handle: child.raw_handle().map(|handle| handle as usize),
5093        }),
5094        Limits::default(),
5095        "test",
5096    );
5097    shared.fatal(Closed::Limit {
5098        limit: AppServerLimit::QueuedMessages,
5099        max: 0,
5100    });
5101    shared.revoke_kill();
5102    let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
5103        .await
5104        .unwrap()
5105        .unwrap();
5106    assert!(!status.success());
5107    assert!(matches!(shared.closed_reason(), Some(Closed::Limit { .. })));
5108}