Skip to main content

codex_wrapper/
structured.rs

1//! Structured output: owned `--output-schema` files and typed decoding.
2//!
3//! `codex exec`, `exec resume` and `exec review` take a JSON Schema as a file
4//! path (`--output-schema <path>`). [`OutputSchema`] serializes a
5//! [`serde_json::Value`] to a private temporary file and removes it on drop,
6//! so a caller can build the schema in code:
7//!
8//! ```no_run
9//! # #[cfg(feature = "json")]
10//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
11//! use codex_wrapper::structured::OutputSchema;
12//! use codex_wrapper::{Codex, ExecCommand};
13//!
14//! #[derive(serde::Deserialize)]
15//! struct Person {
16//!     name: String,
17//! }
18//!
19//! let codex = Codex::builder().build()?;
20//! let schema = OutputSchema::new(&serde_json::json!({
21//!     "type": "object",
22//!     "properties": {"name": {"type": "string"}},
23//!     "required": ["name"],
24//!     "additionalProperties": false
25//! }))?;
26//!
27//! let result = ExecCommand::new("Extract the name from: Hi, I'm Ada Lovelace.")
28//!     .output_schema(schema.path().to_string_lossy())
29//!     .execute_json(&codex)
30//!     .await?;
31//! let person: Person = result.decode_structured()?;
32//! # let _ = person.name;
33//! // `schema` is dropped here, after the process has exited.
34//! # Ok(()) }
35//! ```
36//!
37//! The file lives exactly as long as the [`OutputSchema`] value, so keep it in
38//! scope until the awaited call or the stream that uses it has finished. The
39//! builders only store the path; building or formatting argv never creates a
40//! file.
41//!
42//! ## Decoding
43//!
44//! Codex enforces the schema natively. This crate does not re-validate the
45//! decoded value against it; decoding into a caller-chosen
46//! [`DeserializeOwned`] type is the caller-side check.
47//! [`QueryResult::decode_structured`](crate::types::QueryResult::decode_structured)
48//! reads the final agent message, the last completed `agent_message` item
49//! after the last `turn.started`, and applies these rules in order:
50//!
51//! 1. The last terminal turn event is `turn.failed`:
52//!    [`StructuredOutputError::TurnFailed`], even when an agent message was
53//!    produced before the failure.
54//! 2. No `turn.completed` event: [`StructuredOutputError::NoTerminal`].
55//! 3. No final agent message, or its text is empty or `null`:
56//!    [`StructuredOutputError::Missing`].
57//! 4. The text is not JSON: [`StructuredOutputError::InvalidJson`].
58//! 5. The JSON is neither an object nor an array:
59//!    [`StructuredOutputError::NotObjectOrArray`].
60//! 6. It does not deserialize into `T`: [`StructuredOutputError::Decode`].
61//!
62//! Process failures (a non-zero exit, unparseable JSONL, timeouts,
63//! cancellation) are reported by the execution call as [`crate::Error`]
64//! before any decoding happens. Decoding never starts a process.
65
66use std::path::{Path, PathBuf};
67use std::sync::atomic::{AtomicU64, Ordering};
68
69#[cfg(feature = "json")]
70use serde::de::DeserializeOwned;
71
72#[cfg(feature = "json")]
73use crate::types::JsonLineEvent;
74
75/// A JSON Schema written to a private temporary file for `--output-schema`.
76///
77/// The file is created with mode `0600` on Unix and removed when this value
78/// is dropped.
79#[derive(Debug)]
80pub struct OutputSchema {
81    path: PathBuf,
82}
83
84impl OutputSchema {
85    /// Serialize `schema` to a new temporary file.
86    #[cfg(feature = "json")]
87    pub fn new(schema: &serde_json::Value) -> std::io::Result<Self> {
88        Self::from_json_string(&schema.to_string())
89    }
90
91    /// Write already-encoded schema JSON to a new temporary file.
92    ///
93    /// The text is written as given; Codex reports an invalid schema when the
94    /// run starts.
95    pub fn from_json_string(schema: &str) -> std::io::Result<Self> {
96        static COUNTER: AtomicU64 = AtomicU64::new(0);
97
98        let path = std::env::temp_dir().join(format!(
99            "codex-wrapper-schema-{}-{}.json",
100            std::process::id(),
101            COUNTER.fetch_add(1, Ordering::Relaxed)
102        ));
103
104        let mut options = std::fs::OpenOptions::new();
105        options.write(true).create_new(true);
106        #[cfg(unix)]
107        {
108            use std::os::unix::fs::OpenOptionsExt;
109            options.mode(0o600);
110        }
111
112        let guard = Self { path };
113        let mut file = options.open(&guard.path)?;
114        std::io::Write::write_all(&mut file, schema.as_bytes())?;
115        Ok(guard)
116    }
117
118    /// The schema file's path, to pass to `output_schema(...)`.
119    #[must_use]
120    pub fn path(&self) -> &Path {
121        &self.path
122    }
123}
124
125impl Drop for OutputSchema {
126    fn drop(&mut self) {
127        let _ = std::fs::remove_file(&self.path);
128    }
129}
130
131/// Why a run's structured output could not be decoded.
132#[cfg(feature = "json")]
133#[derive(Debug, thiserror::Error)]
134#[non_exhaustive]
135pub enum StructuredOutputError {
136    /// The turn ended with `turn.failed`. `message` is the native failure
137    /// message, when present.
138    #[error("the turn failed: {}", message.as_deref().unwrap_or("no message"))]
139    TurnFailed {
140        /// The `turn.failed` error message, when present.
141        message: Option<String>,
142    },
143    /// The event stream had no `turn.completed` event.
144    #[error("the event stream had no turn.completed event")]
145    NoTerminal,
146    /// The final turn had no agent message, or its text was empty or `null`.
147    #[error("the final turn had no structured agent message")]
148    Missing,
149    /// The final agent message was not valid JSON.
150    #[error("the final agent message was not valid JSON: {0}")]
151    InvalidJson(#[source] serde_json::Error),
152    /// The final agent message was JSON, but neither an object nor an array.
153    #[error("the final agent message was neither a JSON object nor an array")]
154    NotObjectOrArray,
155    /// The JSON did not deserialize into the requested type.
156    #[error("the final agent message did not match the requested type: {0}")]
157    Decode(#[source] serde_json::Error),
158}
159
160/// The text of the last completed agent message after the last
161/// `turn.started`.
162#[cfg(feature = "json")]
163pub(crate) fn final_message(events: &[JsonLineEvent]) -> Option<String> {
164    let start = events
165        .iter()
166        .rposition(|event| event.event_type == "turn.started")
167        .map_or(0, |index| index + 1);
168
169    events[start..]
170        .iter()
171        .rev()
172        .filter(|event| event.event_type == "item.completed")
173        .find_map(JsonLineEvent::agent_message_text)
174}
175
176/// Apply the decoding rules in the module docs.
177#[cfg(feature = "json")]
178pub(crate) fn decode<T: DeserializeOwned>(
179    events: &[JsonLineEvent],
180) -> Result<T, StructuredOutputError> {
181    let terminal = events
182        .iter()
183        .rev()
184        .find(|event| event.is_turn_completed() || event.is_turn_failed());
185
186    match terminal {
187        Some(event) if event.is_turn_failed() => {
188            return Err(StructuredOutputError::TurnFailed {
189                message: event.turn_failure_message().map(str::to_owned),
190            });
191        }
192        Some(_) => {}
193        None => return Err(StructuredOutputError::NoTerminal),
194    }
195
196    let text = final_message(events).ok_or(StructuredOutputError::Missing)?;
197    if text.trim().is_empty() {
198        return Err(StructuredOutputError::Missing);
199    }
200
201    let value: serde_json::Value =
202        serde_json::from_str(&text).map_err(StructuredOutputError::InvalidJson)?;
203
204    match value {
205        serde_json::Value::Null => Err(StructuredOutputError::Missing),
206        serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
207            T::deserialize(value).map_err(StructuredOutputError::Decode)
208        }
209        _ => Err(StructuredOutputError::NotObjectOrArray),
210    }
211}
212
213#[cfg(all(test, feature = "json"))]
214mod tests {
215    use super::*;
216
217    fn events(lines: &[&str]) -> Vec<JsonLineEvent> {
218        lines
219            .iter()
220            .map(|line| serde_json::from_str(line).unwrap())
221            .collect()
222    }
223
224    fn message(id: &str, text: &str) -> String {
225        serde_json::json!({
226            "type": "item.completed",
227            "item": {"id": id, "type": "agent_message", "text": text}
228        })
229        .to_string()
230    }
231
232    #[derive(Debug, serde::Deserialize)]
233    struct Person {
234        name: String,
235    }
236
237    #[test]
238    fn schema_file_is_private_and_removed_on_drop() {
239        let schema = OutputSchema::new(&serde_json::json!({"type": "object"})).unwrap();
240        let path = schema.path().to_path_buf();
241        assert_eq!(
242            std::fs::read_to_string(&path).unwrap(),
243            r#"{"type":"object"}"#
244        );
245
246        #[cfg(unix)]
247        {
248            use std::os::unix::fs::PermissionsExt;
249            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
250            assert_eq!(mode & 0o777, 0o600);
251        }
252
253        drop(schema);
254        assert!(!path.exists());
255    }
256
257    #[test]
258    fn final_message_is_the_last_agent_message_of_the_last_turn() {
259        let draft = message("a", r#"{"name":"draft"}"#);
260        let last = message("b", r#"{"name":"final"}"#);
261        let stream = events(&[
262            r#"{"type":"turn.started"}"#,
263            &draft,
264            r#"{"type":"item.completed","item":{"id":"r","type":"reasoning","text":"x"}}"#,
265            &last,
266            r#"{"type":"turn.completed"}"#,
267        ]);
268        assert_eq!(decode::<Person>(&stream).unwrap().name, "final");
269    }
270
271    #[test]
272    fn failures_are_distinct() {
273        let partial = message("a", r#"{"name":"partial"}"#);
274        let failed = events(&[
275            r#"{"type":"turn.started"}"#,
276            &partial,
277            r#"{"type":"turn.failed","error":{"message":"boom"}}"#,
278        ]);
279        assert!(matches!(
280            decode::<Person>(&failed),
281            Err(StructuredOutputError::TurnFailed { message: Some(m) }) if m == "boom"
282        ));
283
284        let ok = message("a", r#"{"name":"Ada"}"#);
285        let unterminated = events(&[r#"{"type":"turn.started"}"#, &ok]);
286        assert!(matches!(
287            decode::<Person>(&unterminated),
288            Err(StructuredOutputError::NoTerminal)
289        ));
290
291        let cases = [
292            (None, "missing"),
293            (Some("null"), "missing"),
294            (Some(r#"{"name":"#), "invalid"),
295            (Some(r#""Ada""#), "scalar"),
296            (Some(r#"{"nope":1}"#), "decode"),
297        ];
298        for (text, kind) in cases {
299            let item = text.map(|t| message("a", t));
300            let mut lines = vec![r#"{"type":"turn.started"}"#];
301            if let Some(item) = item.as_deref() {
302                lines.push(item);
303            }
304            lines.push(r#"{"type":"turn.completed"}"#);
305            let err = decode::<Person>(&events(&lines)).unwrap_err();
306            let matched = match kind {
307                "missing" => matches!(err, StructuredOutputError::Missing),
308                "invalid" => matches!(err, StructuredOutputError::InvalidJson(_)),
309                "scalar" => matches!(err, StructuredOutputError::NotObjectOrArray),
310                _ => matches!(err, StructuredOutputError::Decode(_)),
311            };
312            assert!(matched, "{kind}: unexpected {err:?}");
313        }
314    }
315}