Skip to main content

codex_wrapper/
app_server.rs

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