codex-codes 0.101.1

A tightly typed Rust interface for the OpenAI Codex CLI JSON protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Synchronous multi-turn client for the Codex app-server.
//!
//! Spawns `codex app-server --listen stdio://` and communicates over
//! newline-delimited JSON-RPC. The connection stays open for multiple
//! turns until explicitly shut down.
//!
//! This is the blocking counterpart to [`crate::client_async::AsyncClient`].
//! Prefer the async client for applications that already use tokio.
//!
//! # Lifecycle
//!
//! 1. Create a client with [`SyncClient::start`] (spawns and initializes the app-server)
//! 2. Call [`SyncClient::thread_start`] to create a conversation session
//! 3. Call [`SyncClient::turn_start`] to send user input
//! 4. Iterate over [`SyncClient::events`] until `turn/completed`
//! 5. Handle approval requests via [`SyncClient::respond`]
//! 6. Repeat steps 3-5 for follow-up turns
//!
//! # Example
//!
//! ```ignore
//! use codex_codes::{SyncClient, ThreadStartParams, TurnStartParams, UserInput, ServerMessage};
//!
//! let mut client = SyncClient::start()?;
//! let thread = client.thread_start(&ThreadStartParams::default())?;
//!
//! client.turn_start(&TurnStartParams {
//!     thread_id: thread.thread_id().to_string(),
//!     input: vec![UserInput::Text { text: "Hello!".into() }],
//!     model: None,
//!     reasoning_effort: None,
//!     sandbox_policy: None,
//! })?;
//!
//! for result in client.events() {
//!     match result? {
//!         ServerMessage::Notification { method, .. } => {
//!             if method == "turn/completed" { break; }
//!         }
//!         _ => {}
//!     }
//! }
//! ```

use crate::cli::AppServerBuilder;
use crate::error::{Error, Result};
use crate::jsonrpc::{
    JsonRpcError, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, RequestId,
};
use crate::protocol::{
    ClientInfo, InitializeParams, InitializeResponse, ServerMessage, ThreadArchiveParams,
    ThreadArchiveResponse, ThreadStartParams, ThreadStartResponse, TurnInterruptParams,
    TurnInterruptResponse, TurnStartParams, TurnStartResponse,
};
use log::{debug, warn};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::process::Child;

/// Buffer size for reading stdout (10MB).
const STDOUT_BUFFER_SIZE: usize = 10 * 1024 * 1024;

/// Synchronous multi-turn client for the Codex app-server.
///
/// Communicates with a long-lived `codex app-server` process via
/// newline-delimited JSON-RPC over stdio. Manages request/response
/// correlation and buffers incoming notifications that arrive while
/// waiting for RPC responses.
///
/// The client automatically kills the app-server process when dropped.
pub struct SyncClient {
    child: Child,
    writer: BufWriter<std::process::ChildStdin>,
    reader: BufReader<std::process::ChildStdout>,
    next_id: i64,
    buffered: VecDeque<ServerMessage>,
}

impl SyncClient {
    /// Start an app-server with default settings.
    ///
    /// Spawns `codex app-server --listen stdio://`, performs the required
    /// `initialize` handshake, and returns a connected client ready for
    /// `thread_start()`.
    ///
    /// # Errors
    ///
    /// Returns an error if the `codex` CLI is not installed, the version is
    /// incompatible, the process fails to start, or the initialization
    /// handshake fails.
    pub fn start() -> Result<Self> {
        Self::start_with(AppServerBuilder::new())
    }

    /// Start an app-server with a custom [`AppServerBuilder`].
    ///
    /// Performs the required `initialize` handshake before returning.
    /// Use this to configure a custom binary path or working directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the process fails to start, stdio pipes
    /// cannot be established, or the initialization handshake fails.
    pub fn start_with(builder: AppServerBuilder) -> Result<Self> {
        let mut client = Self::spawn(builder)?;
        client.initialize(&InitializeParams {
            client_info: ClientInfo {
                name: "codex-codes".to_string(),
                version: env!("CARGO_PKG_VERSION").to_string(),
                title: None,
            },
            capabilities: None,
        })?;
        Ok(client)
    }

    /// Spawn an app-server without performing the `initialize` handshake.
    ///
    /// Use this if you need to send a custom [`InitializeParams`] (e.g., with
    /// specific capabilities). You **must** call [`SyncClient::initialize`]
    /// before any other requests.
    pub fn spawn(builder: AppServerBuilder) -> Result<Self> {
        crate::version::check_codex_version()?;

        let mut child = builder.spawn_sync()?;

        let stdin = child
            .stdin
            .take()
            .ok_or_else(|| Error::Protocol("Failed to get stdin".to_string()))?;
        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| Error::Protocol("Failed to get stdout".to_string()))?;

        Ok(Self {
            child,
            writer: BufWriter::new(stdin),
            reader: BufReader::with_capacity(STDOUT_BUFFER_SIZE, stdout),
            next_id: 1,
            buffered: VecDeque::new(),
        })
    }

    /// Send a JSON-RPC request and wait for the matching response.
    ///
    /// Any notifications or server requests that arrive before the response
    /// are buffered and can be retrieved via [`SyncClient::next_message`].
    ///
    /// # Errors
    ///
    /// - [`Error::JsonRpc`] if the server returns a JSON-RPC error
    /// - [`Error::ServerClosed`] if the connection drops before a response arrives
    /// - [`Error::Json`] if response deserialization fails
    pub fn request<P: Serialize, R: DeserializeOwned>(
        &mut self,
        method: &str,
        params: &P,
    ) -> Result<R> {
        let id = RequestId::Integer(self.next_id);
        self.next_id += 1;

        let req = JsonRpcRequest {
            id: id.clone(),
            method: method.to_string(),
            params: Some(serde_json::to_value(params).map_err(Error::Json)?),
        };

        self.send_raw(&req)?;

        loop {
            let msg = self.read_message()?;
            match msg {
                JsonRpcMessage::Response(resp) if resp.id == id => {
                    let result: R = serde_json::from_value(resp.result).map_err(Error::Json)?;
                    return Ok(result);
                }
                JsonRpcMessage::Error(err) if err.id == id => {
                    return Err(Error::JsonRpc {
                        code: err.error.code,
                        message: err.error.message,
                    });
                }
                JsonRpcMessage::Notification(notif) => {
                    self.buffered.push_back(ServerMessage::Notification {
                        method: notif.method,
                        params: notif.params,
                    });
                }
                JsonRpcMessage::Request(req) => {
                    self.buffered.push_back(ServerMessage::Request {
                        id: req.id,
                        method: req.method,
                        params: req.params,
                    });
                }
                JsonRpcMessage::Response(resp) => {
                    warn!(
                        "[CLIENT] Unexpected response for id={}, expected id={}",
                        resp.id, id
                    );
                }
                JsonRpcMessage::Error(err) => {
                    warn!(
                        "[CLIENT] Unexpected error for id={}, expected id={}",
                        err.id, id
                    );
                }
            }
        }
    }

    /// Start a new thread (conversation session).
    ///
    /// A thread must be created before any turns can be started. The returned
    /// [`ThreadStartResponse`] contains the `thread_id` needed for subsequent calls.
    pub fn thread_start(&mut self, params: &ThreadStartParams) -> Result<ThreadStartResponse> {
        self.request(crate::protocol::methods::THREAD_START, params)
    }

    /// Start a new turn within a thread.
    ///
    /// Sends user input to the agent. After calling this, use [`SyncClient::events`]
    /// or [`SyncClient::next_message`] to consume notifications until `turn/completed`.
    pub fn turn_start(&mut self, params: &TurnStartParams) -> Result<TurnStartResponse> {
        self.request(crate::protocol::methods::TURN_START, params)
    }

    /// Interrupt an active turn.
    pub fn turn_interrupt(
        &mut self,
        params: &TurnInterruptParams,
    ) -> Result<TurnInterruptResponse> {
        self.request(crate::protocol::methods::TURN_INTERRUPT, params)
    }

    /// Archive a thread.
    pub fn thread_archive(
        &mut self,
        params: &ThreadArchiveParams,
    ) -> Result<ThreadArchiveResponse> {
        self.request(crate::protocol::methods::THREAD_ARCHIVE, params)
    }

    /// Perform the `initialize` handshake with the app-server.
    ///
    /// Sends `initialize` with the given params and then sends the
    /// `initialized` notification. This must be the first request after
    /// spawning the process.
    pub fn initialize(&mut self, params: &InitializeParams) -> Result<InitializeResponse> {
        let resp: InitializeResponse =
            self.request(crate::protocol::methods::INITIALIZE, params)?;
        self.send_notification(crate::protocol::methods::INITIALIZED)?;
        Ok(resp)
    }

    /// Respond to a server-to-client request (e.g., approval flow).
    ///
    /// When the server sends a [`ServerMessage::Request`], it expects a response.
    /// Use this method with the request's `id` and a result payload. For command
    /// approval, pass a [`CommandExecutionApprovalResponse`](crate::CommandExecutionApprovalResponse).
    /// For file change approval, pass a [`FileChangeApprovalResponse`](crate::FileChangeApprovalResponse).
    pub fn respond<R: Serialize>(&mut self, id: RequestId, result: &R) -> Result<()> {
        let resp = JsonRpcResponse {
            id,
            result: serde_json::to_value(result).map_err(Error::Json)?,
        };
        self.send_raw(&resp)
    }

    /// Respond to a server-to-client request with an error.
    pub fn respond_error(&mut self, id: RequestId, code: i64, message: &str) -> Result<()> {
        let err = JsonRpcError {
            id,
            error: crate::jsonrpc::JsonRpcErrorData {
                code,
                message: message.to_string(),
                data: None,
            },
        };
        self.send_raw(&err)
    }

    /// Read the next incoming server message (notification or server request).
    ///
    /// Returns buffered messages first (from notifications that arrived during
    /// a [`SyncClient::request`] call), then reads from the wire.
    ///
    /// Returns `Ok(None)` when the app-server closes the connection (EOF).
    pub fn next_message(&mut self) -> Result<Option<ServerMessage>> {
        if let Some(msg) = self.buffered.pop_front() {
            return Ok(Some(msg));
        }

        loop {
            let msg = match self.read_message_opt()? {
                Some(m) => m,
                None => return Ok(None),
            };

            match msg {
                JsonRpcMessage::Notification(notif) => {
                    return Ok(Some(ServerMessage::Notification {
                        method: notif.method,
                        params: notif.params,
                    }));
                }
                JsonRpcMessage::Request(req) => {
                    return Ok(Some(ServerMessage::Request {
                        id: req.id,
                        method: req.method,
                        params: req.params,
                    }));
                }
                JsonRpcMessage::Response(resp) => {
                    warn!(
                        "[CLIENT] Unexpected response (no pending request): id={}",
                        resp.id
                    );
                }
                JsonRpcMessage::Error(err) => {
                    warn!(
                        "[CLIENT] Unexpected error (no pending request): id={} code={}",
                        err.id, err.error.code
                    );
                }
            }
        }
    }

    /// Return an iterator over [`ServerMessage`]s.
    ///
    /// The iterator yields `Result<ServerMessage>` and terminates when the
    /// connection closes (EOF). This is the idiomatic way to consume a turn's
    /// notifications in synchronous code.
    pub fn events(&mut self) -> EventIterator<'_> {
        EventIterator { client: self }
    }

    /// Shut down the child process.
    ///
    /// Kills the process if it's still running. Called automatically on [`Drop`].
    pub fn shutdown(&mut self) -> Result<()> {
        debug!("[CLIENT] Shutting down");
        match self.child.try_wait() {
            Ok(Some(_)) => Ok(()),
            Ok(None) => {
                self.child.kill().map_err(Error::Io)?;
                self.child.wait().map_err(Error::Io)?;
                Ok(())
            }
            Err(e) => Err(Error::Io(e)),
        }
    }

    // -- internal --

    fn send_notification(&mut self, method: &str) -> Result<()> {
        let notif = JsonRpcNotification {
            method: method.to_string(),
            params: None,
        };
        self.send_raw(&notif)
    }

    fn send_raw<T: Serialize>(&mut self, msg: &T) -> Result<()> {
        let json = serde_json::to_string(msg).map_err(Error::Json)?;
        debug!("[CLIENT] Sending: {}", json);
        self.writer.write_all(json.as_bytes()).map_err(Error::Io)?;
        self.writer.write_all(b"\n").map_err(Error::Io)?;
        self.writer.flush().map_err(Error::Io)?;
        Ok(())
    }

    fn read_message(&mut self) -> Result<JsonRpcMessage> {
        self.read_message_opt()?.ok_or(Error::ServerClosed)
    }

    fn read_message_opt(&mut self) -> Result<Option<JsonRpcMessage>> {
        loop {
            let mut line = String::new();
            match self.reader.read_line(&mut line) {
                Ok(0) => {
                    debug!("[CLIENT] Stream closed (EOF)");
                    return Ok(None);
                }
                Ok(_) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }

                    debug!("[CLIENT] Received: {}", trimmed);

                    match serde_json::from_str::<JsonRpcMessage>(trimmed) {
                        Ok(msg) => return Ok(Some(msg)),
                        Err(e) => {
                            warn!(
                                "[CLIENT] Failed to deserialize message. \
                                 Please report this at https://github.com/meawoppl/rust-code-agent-sdks/issues"
                            );
                            warn!("[CLIENT] Parse error: {}", e);
                            warn!("[CLIENT] Raw: {}", trimmed);
                            return Err(Error::Deserialization(format!(
                                "{} (raw: {})",
                                e, trimmed
                            )));
                        }
                    }
                }
                Err(e) => {
                    debug!("[CLIENT] Error reading stdout: {}", e);
                    return Err(Error::Io(e));
                }
            }
        }
    }
}

impl Drop for SyncClient {
    fn drop(&mut self) {
        if let Err(e) = self.shutdown() {
            debug!("[CLIENT] Error during shutdown: {}", e);
        }
    }
}

/// Iterator over [`ServerMessage`]s from a [`SyncClient`].
pub struct EventIterator<'a> {
    client: &'a mut SyncClient,
}

impl Iterator for EventIterator<'_> {
    type Item = Result<ServerMessage>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.client.next_message() {
            Ok(Some(msg)) => Some(Ok(msg)),
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_buffer_size() {
        assert_eq!(STDOUT_BUFFER_SIZE, 10 * 1024 * 1024);
    }
}