Skip to main content

codex_codes/
client_sync.rs

1//! Synchronous multi-turn client for the Codex app-server.
2//!
3//! Spawns `codex app-server --listen stdio://` and communicates over
4//! newline-delimited JSON-RPC. The connection stays open for multiple
5//! turns until explicitly shut down.
6//!
7//! This is the blocking counterpart to [`crate::client_async::AsyncClient`].
8//! Prefer the async client for applications that already use tokio.
9//!
10//! # Lifecycle
11//!
12//! 1. Create a client with [`SyncClient::start`] (spawns and initializes the app-server)
13//! 2. Call [`SyncClient::thread_start`] to create a conversation session
14//! 3. Call [`SyncClient::turn_start`] to send user input
15//! 4. Iterate over [`SyncClient::events`] until `turn/completed`
16//! 5. Handle approval requests via [`SyncClient::respond`]
17//! 6. Repeat steps 3-5 for follow-up turns
18//!
19//! # Example
20//!
21//! ```ignore
22//! use codex_codes::{SyncClient, ThreadStartParams, TurnStartParams, UserInput, ServerMessage};
23//!
24//! let mut client = SyncClient::start()?;
25//! let thread = client.thread_start(&ThreadStartParams::default())?;
26//!
27//! client.turn_start(&TurnStartParams {
28//!     thread_id: thread.thread_id().to_string(),
29//!     input: vec![UserInput::Text { text: "Hello!".into() }],
30//!     model: None,
31//!     reasoning_effort: None,
32//!     sandbox_policy: None,
33//! })?;
34//!
35//! for result in client.events() {
36//!     match result? {
37//!         ServerMessage::Notification(n) => {
38//!             if let codex_codes::Notification::TurnCompleted(_) = n { break; }
39//!         }
40//!         _ => {}
41//!     }
42//! }
43//! ```
44
45use crate::cli::AppServerBuilder;
46use crate::error::{Error, ParseError, Result};
47use crate::jsonrpc::{
48    JsonRpcError, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, RequestId,
49};
50use crate::messages::{Notification, ServerMessage, ServerRequest};
51use crate::protocol::{
52    ClientInfo, InitializeParams, InitializeResponse, ThreadArchiveParams, ThreadArchiveResponse,
53    ThreadDeleteParams, ThreadDeleteResponse, ThreadForkParams, ThreadForkResponse,
54    ThreadItemsListParams, ThreadItemsListResponse, ThreadResumeParams, ThreadResumeResponse,
55    ThreadRevertParams, ThreadRevertResponse, ThreadStartParams, ThreadStartResponse,
56    ThreadTurnsListParams, ThreadTurnsListResponse, TurnInterruptParams, TurnInterruptResponse,
57    TurnStartParams, TurnStartResponse, TurnSteerParams, TurnSteerResponse,
58};
59use log::{debug, warn};
60use serde::de::DeserializeOwned;
61use serde::Serialize;
62use std::collections::VecDeque;
63use std::io::{BufRead, BufReader, BufWriter, Write};
64use std::process::Child;
65
66/// Buffer size for reading stdout (10MB).
67const STDOUT_BUFFER_SIZE: usize = 10 * 1024 * 1024;
68
69/// Synchronous multi-turn client for the Codex app-server.
70///
71/// Communicates with a long-lived `codex app-server` process via
72/// newline-delimited JSON-RPC over stdio. Manages request/response
73/// correlation and buffers incoming notifications that arrive while
74/// waiting for RPC responses.
75///
76/// The client automatically kills the app-server process when dropped.
77pub struct SyncClient {
78    child: Child,
79    writer: BufWriter<std::process::ChildStdin>,
80    reader: BufReader<std::process::ChildStdout>,
81    /// Handle to the background thread draining the child's stderr pipe.
82    /// Kept alive for the lifetime of the client; the thread exits on EOF
83    /// when the child is killed.
84    _stderr_drain: std::thread::JoinHandle<()>,
85    next_id: i64,
86    buffered: VecDeque<ServerMessage>,
87}
88
89impl SyncClient {
90    /// Create a client from an existing child process.
91    ///
92    /// The child's stdin, stdout, and stderr must all be piped. This does not
93    /// perform the app-server `initialize` handshake or a Codex version check.
94    /// Use [`AppServerBuilder::build_command_sync`] to retain the SDK's
95    /// command-line and stdio configuration while customizing how the process
96    /// is spawned.
97    pub fn new(mut child: Child) -> Result<Self> {
98        let stdin = child
99            .stdin
100            .take()
101            .ok_or_else(|| Error::Protocol("Failed to get stdin".to_string()))?;
102        let stdout = child
103            .stdout
104            .take()
105            .ok_or_else(|| Error::Protocol("Failed to get stdout".to_string()))?;
106        let stderr = child
107            .stderr
108            .take()
109            .ok_or_else(|| Error::Protocol("Failed to get stderr".to_string()))?;
110
111        // The app-server emits ~200 KB/s of tracing to stderr. Without an
112        // active reader, the ~64 KB kernel pipe fills almost instantly and
113        // the child blocks. Drain in the background and route lines through
114        // the `log` crate (see [`crate::stderr_drain`]).
115        let stderr_drain = crate::stderr_drain::spawn_sync(stderr);
116
117        Ok(Self {
118            child,
119            writer: BufWriter::new(stdin),
120            reader: BufReader::with_capacity(STDOUT_BUFFER_SIZE, stdout),
121            _stderr_drain: stderr_drain,
122            next_id: 1,
123            buffered: VecDeque::new(),
124        })
125    }
126
127    /// Start an app-server with default settings.
128    ///
129    /// Spawns `codex app-server --listen stdio://`, performs the required
130    /// `initialize` handshake, and returns a connected client ready for
131    /// `thread_start()`.
132    ///
133    /// # Errors
134    ///
135    /// Returns an error if the `codex` CLI is not installed, the version is
136    /// incompatible, the process fails to start, or the initialization
137    /// handshake fails.
138    pub fn start() -> Result<Self> {
139        Self::start_with(AppServerBuilder::new())
140    }
141
142    /// Start an app-server with a custom [`AppServerBuilder`].
143    ///
144    /// Performs the required `initialize` handshake before returning.
145    /// Use this to configure the binary path, working directory, environment,
146    /// or CLI arguments.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if the process fails to start, stdio pipes
151    /// cannot be established, or the initialization handshake fails.
152    pub fn start_with(builder: AppServerBuilder) -> Result<Self> {
153        let mut client = Self::spawn(builder)?;
154        client.initialize(&InitializeParams {
155            client_info: ClientInfo {
156                name: "codex-codes".to_string(),
157                version: env!("CARGO_PKG_VERSION").to_string(),
158                title: None,
159            },
160            capabilities: None,
161        })?;
162        Ok(client)
163    }
164
165    /// Spawn an app-server without performing the `initialize` handshake.
166    ///
167    /// Use this if you need to send a custom [`InitializeParams`] (e.g., with
168    /// specific capabilities). You **must** call [`SyncClient::initialize`]
169    /// before any other requests.
170    pub fn spawn(builder: AppServerBuilder) -> Result<Self> {
171        crate::version::check_codex_version()?;
172        Self::new(builder.spawn_sync()?)
173    }
174
175    /// Send a JSON-RPC request and wait for the matching response.
176    ///
177    /// Any notifications or server requests that arrive before the response
178    /// are buffered and can be retrieved via [`SyncClient::next_message`].
179    ///
180    /// # Errors
181    ///
182    /// - [`Error::JsonRpc`] if the server returns a JSON-RPC error
183    /// - [`Error::ServerClosed`] if the connection drops before a response arrives
184    /// - [`Error::Json`] if response deserialization fails
185    pub fn request<P: Serialize, R: DeserializeOwned>(
186        &mut self,
187        method: &str,
188        params: &P,
189    ) -> Result<R> {
190        let id = RequestId::Integer(self.next_id);
191        self.next_id += 1;
192
193        let req = JsonRpcRequest {
194            id: id.clone(),
195            method: method.to_string(),
196            params: Some(serde_json::to_value(params).map_err(Error::Json)?),
197        };
198
199        self.send_raw(&req)?;
200
201        loop {
202            let msg = self.read_message()?;
203            match msg {
204                JsonRpcMessage::Response(resp) if resp.id == id => {
205                    let result: R = serde_json::from_value(resp.result).map_err(Error::Json)?;
206                    return Ok(result);
207                }
208                JsonRpcMessage::Error(err) if err.id == id => {
209                    return Err(err.error.into());
210                }
211                JsonRpcMessage::Notification(notif) => {
212                    let typed = Notification::from_envelope(&notif.method, notif.params)
213                        .map_err(Error::Json)?;
214                    self.buffered.push_back(ServerMessage::Notification(typed));
215                }
216                JsonRpcMessage::Request(req) => {
217                    let typed = ServerRequest::from_envelope(&req.method, req.params)
218                        .map_err(Error::Json)?;
219                    self.buffered.push_back(ServerMessage::Request {
220                        id: req.id,
221                        request: typed,
222                    });
223                }
224                JsonRpcMessage::Response(resp) => {
225                    warn!(
226                        "[CLIENT] Unexpected response for id={}, expected id={}",
227                        resp.id, id
228                    );
229                }
230                JsonRpcMessage::Error(err) => {
231                    warn!(
232                        "[CLIENT] Unexpected error for id={}, expected id={}",
233                        err.id, id
234                    );
235                }
236            }
237        }
238    }
239
240    /// Start a new thread (conversation session).
241    ///
242    /// A thread must be created before any turns can be started. The returned
243    /// [`ThreadStartResponse`] contains the `thread_id` needed for subsequent calls.
244    pub fn thread_start(&mut self, params: &ThreadStartParams) -> Result<ThreadStartResponse> {
245        self.request(crate::protocol::methods::THREAD_START, params)
246    }
247
248    /// Resume a previously persisted thread by id.
249    ///
250    /// Replays the thread's history so turns can continue where they left off.
251    pub fn thread_resume(&mut self, params: &ThreadResumeParams) -> Result<ThreadResumeResponse> {
252        self.request(crate::protocol::methods::THREAD_RESUME, params)
253    }
254
255    /// Fork an existing thread into a new independent thread.
256    pub fn thread_fork(&mut self, params: &ThreadForkParams) -> Result<ThreadForkResponse> {
257        self.request(crate::protocol::methods::THREAD_FORK, params)
258    }
259
260    /// Start a new turn within a thread.
261    ///
262    /// Sends user input to the agent. After calling this, use [`SyncClient::events`]
263    /// or [`SyncClient::next_message`] to consume notifications until `turn/completed`.
264    pub fn turn_start(&mut self, params: &TurnStartParams) -> Result<TurnStartResponse> {
265        self.request(crate::protocol::methods::TURN_START, params)
266    }
267
268    /// Steer an active turn with additional user input (`turn/steer`).
269    pub fn turn_steer(&mut self, params: &TurnSteerParams) -> Result<TurnSteerResponse> {
270        self.request(crate::protocol::methods::TURN_STEER, params)
271    }
272
273    /// Page through a thread's items in canonical order (`thread/items/list`).
274    pub fn thread_items_list(
275        &mut self,
276        params: &ThreadItemsListParams,
277    ) -> Result<ThreadItemsListResponse> {
278        self.request(crate::protocol::methods::THREAD_ITEMS_LIST, params)
279    }
280
281    /// Page through a thread's turns (`thread/turns/list`).
282    pub fn thread_turns_list(
283        &mut self,
284        params: &ThreadTurnsListParams,
285    ) -> Result<ThreadTurnsListResponse> {
286        self.request(crate::protocol::methods::THREAD_TURNS_LIST, params)
287    }
288
289    /// Revert a thread's durable history to before one turn (`thread/revert`).
290    pub fn thread_revert(&mut self, params: &ThreadRevertParams) -> Result<ThreadRevertResponse> {
291        self.request(crate::protocol::methods::THREAD_REVERT, params)
292    }
293
294    /// Interrupt an active turn.
295    pub fn turn_interrupt(
296        &mut self,
297        params: &TurnInterruptParams,
298    ) -> Result<TurnInterruptResponse> {
299        self.request(crate::protocol::methods::TURN_INTERRUPT, params)
300    }
301
302    /// Archive a thread.
303    pub fn thread_archive(
304        &mut self,
305        params: &ThreadArchiveParams,
306    ) -> Result<ThreadArchiveResponse> {
307        self.request(crate::protocol::methods::THREAD_ARCHIVE, params)
308    }
309
310    /// Delete a thread.
311    pub fn thread_delete(&mut self, params: &ThreadDeleteParams) -> Result<ThreadDeleteResponse> {
312        self.request(crate::protocol::methods::THREAD_DELETE, params)
313    }
314
315    /// Perform the `initialize` handshake with the app-server.
316    ///
317    /// Sends `initialize` with the given params and then sends the
318    /// `initialized` notification. This must be the first request after
319    /// spawning the process.
320    pub fn initialize(&mut self, params: &InitializeParams) -> Result<InitializeResponse> {
321        let resp: InitializeResponse =
322            self.request(crate::protocol::methods::INITIALIZE, params)?;
323        self.send_notification(crate::protocol::methods::INITIALIZED)?;
324        Ok(resp)
325    }
326
327    /// Respond to a server-to-client request (e.g., approval flow).
328    ///
329    /// When the server sends a [`ServerMessage::Request`], it expects a response.
330    /// Use this method with the request's `id` and a result payload. For command
331    /// approval, pass a [`CommandExecutionApprovalResponse`](crate::CommandExecutionApprovalResponse).
332    /// For file change approval, pass a [`FileChangeApprovalResponse`](crate::FileChangeApprovalResponse).
333    pub fn respond<R: Serialize>(&mut self, id: RequestId, result: &R) -> Result<()> {
334        let resp = JsonRpcResponse {
335            id,
336            result: serde_json::to_value(result).map_err(Error::Json)?,
337        };
338        self.send_raw(&resp)
339    }
340
341    /// Respond to a server-to-client request with an error.
342    pub fn respond_error(&mut self, id: RequestId, code: i64, message: &str) -> Result<()> {
343        let err = JsonRpcError {
344            id,
345            error: crate::jsonrpc::JsonRpcErrorData {
346                code,
347                message: message.to_string(),
348                data: None,
349            },
350        };
351        self.send_raw(&err)
352    }
353
354    /// Read the next incoming server message (notification or server request).
355    ///
356    /// Returns buffered messages first (from notifications that arrived during
357    /// a [`SyncClient::request`] call), then reads from the wire.
358    ///
359    /// Returns `Ok(None)` when the app-server closes the connection (EOF).
360    pub fn next_message(&mut self) -> Result<Option<ServerMessage>> {
361        if let Some(msg) = self.buffered.pop_front() {
362            return Ok(Some(msg));
363        }
364
365        loop {
366            let msg = match self.read_message_opt()? {
367                Some(m) => m,
368                None => return Ok(None),
369            };
370
371            match msg {
372                JsonRpcMessage::Notification(notif) => {
373                    let JsonRpcNotification { method, params } = notif;
374                    let typed =
375                        Notification::from_envelope(&method, params.clone()).map_err(|e| {
376                            Error::Deserialization(ParseError::from_envelope(method, params, e))
377                        })?;
378                    return Ok(Some(ServerMessage::Notification(typed)));
379                }
380                JsonRpcMessage::Request(req) => {
381                    let JsonRpcRequest { id, method, params } = req;
382                    let typed =
383                        ServerRequest::from_envelope(&method, params.clone()).map_err(|e| {
384                            Error::Deserialization(ParseError::from_envelope(method, params, e))
385                        })?;
386                    return Ok(Some(ServerMessage::Request { id, request: typed }));
387                }
388                JsonRpcMessage::Response(resp) => {
389                    warn!(
390                        "[CLIENT] Unexpected response (no pending request): id={}",
391                        resp.id
392                    );
393                }
394                JsonRpcMessage::Error(err) => {
395                    warn!(
396                        "[CLIENT] Unexpected error (no pending request): id={} code={}",
397                        err.id, err.error.code
398                    );
399                }
400            }
401        }
402    }
403
404    /// Return an iterator over [`ServerMessage`]s.
405    ///
406    /// The iterator yields `Result<ServerMessage>` and terminates when the
407    /// connection closes (EOF). This is the idiomatic way to consume a turn's
408    /// notifications in synchronous code.
409    pub fn events(&mut self) -> EventIterator<'_> {
410        EventIterator { client: self }
411    }
412
413    /// Shut down the child process.
414    ///
415    /// Kills the process if it's still running. Called automatically on [`Drop`].
416    pub fn shutdown(&mut self) -> Result<()> {
417        debug!("[CLIENT] Shutting down");
418        match self.child.try_wait() {
419            Ok(Some(_)) => Ok(()),
420            Ok(None) => {
421                self.child.kill().map_err(Error::Io)?;
422                self.child.wait().map_err(Error::Io)?;
423                Ok(())
424            }
425            Err(e) => Err(Error::Io(e)),
426        }
427    }
428
429    // -- internal --
430
431    fn send_notification(&mut self, method: &str) -> Result<()> {
432        let notif = JsonRpcNotification {
433            method: method.to_string(),
434            params: None,
435        };
436        self.send_raw(&notif)
437    }
438
439    fn send_raw<T: Serialize>(&mut self, msg: &T) -> Result<()> {
440        let json = serde_json::to_string(msg).map_err(Error::Json)?;
441        debug!("[CLIENT] Sending: {}", json);
442        self.writer.write_all(json.as_bytes()).map_err(Error::Io)?;
443        self.writer.write_all(b"\n").map_err(Error::Io)?;
444        self.writer.flush().map_err(Error::Io)?;
445        Ok(())
446    }
447
448    fn read_message(&mut self) -> Result<JsonRpcMessage> {
449        self.read_message_opt()?.ok_or(Error::ServerClosed)
450    }
451
452    fn read_message_opt(&mut self) -> Result<Option<JsonRpcMessage>> {
453        loop {
454            let mut line = String::new();
455            match self.reader.read_line(&mut line) {
456                Ok(0) => {
457                    debug!("[CLIENT] Stream closed (EOF)");
458                    return Ok(None);
459                }
460                Ok(_) => {
461                    let trimmed = line.trim();
462                    if trimmed.is_empty() {
463                        continue;
464                    }
465
466                    debug!("[CLIENT] Received: {}", trimmed);
467
468                    match serde_json::from_str::<JsonRpcMessage>(trimmed) {
469                        Ok(msg) => return Ok(Some(msg)),
470                        Err(e) => {
471                            warn!(
472                                "[CLIENT] Failed to deserialize message. \
473                                 Please report this at https://github.com/meawoppl/rust-code-agent-sdks/issues"
474                            );
475                            warn!("[CLIENT] Parse error: {}", e);
476                            warn!("[CLIENT] Raw: {}", trimmed);
477                            return Err(Error::Deserialization(ParseError::from_line(trimmed, e)));
478                        }
479                    }
480                }
481                Err(e) => {
482                    debug!("[CLIENT] Error reading stdout: {}", e);
483                    return Err(Error::Io(e));
484                }
485            }
486        }
487    }
488}
489
490impl Drop for SyncClient {
491    fn drop(&mut self) {
492        if let Err(e) = self.shutdown() {
493            debug!("[CLIENT] Error during shutdown: {}", e);
494        }
495    }
496}
497
498/// Iterator over [`ServerMessage`]s from a [`SyncClient`].
499pub struct EventIterator<'a> {
500    client: &'a mut SyncClient,
501}
502
503impl Iterator for EventIterator<'_> {
504    type Item = Result<ServerMessage>;
505
506    fn next(&mut self) -> Option<Self::Item> {
507        match self.client.next_message() {
508            Ok(Some(msg)) => Some(Ok(msg)),
509            Ok(None) => None,
510            Err(e) => Some(Err(e)),
511        }
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    #[test]
520    fn test_buffer_size() {
521        assert_eq!(STDOUT_BUFFER_SIZE, 10 * 1024 * 1024);
522    }
523}