codex-wrapper 0.2.0

A type-safe Codex CLI wrapper for Rust
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
//! Domain types shared across commands: enums for CLI options, version parsing,
//! and structured JSONL events.

#[cfg(feature = "json")]
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

/// Sandbox policy for model-generated shell commands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SandboxMode {
    /// Read-only filesystem access.
    ReadOnly,
    /// Write access limited to the workspace directory (default).
    #[default]
    WorkspaceWrite,
    /// Full filesystem access -- use with extreme caution.
    DangerFullAccess,
}

impl SandboxMode {
    pub(crate) fn as_arg(self) -> &'static str {
        match self {
            Self::ReadOnly => "read-only",
            Self::WorkspaceWrite => "workspace-write",
            Self::DangerFullAccess => "danger-full-access",
        }
    }
}

/// When the model should ask for human approval before executing commands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ApprovalPolicy {
    /// Only run trusted commands without asking.
    Untrusted,
    /// Ask on failure (deprecated -- prefer `OnRequest` or `Never`).
    OnFailure,
    /// The model decides when to ask (default).
    #[default]
    OnRequest,
    /// Never ask for approval.
    Never,
}

impl ApprovalPolicy {
    pub(crate) fn as_arg(self) -> &'static str {
        match self {
            Self::Untrusted => "untrusted",
            Self::OnFailure => "on-failure",
            Self::OnRequest => "on-request",
            Self::Never => "never",
        }
    }
}

/// Color output mode for exec commands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Color {
    /// Always emit color codes.
    Always,
    /// Never emit color codes.
    Never,
    /// Auto-detect terminal support (default).
    #[default]
    Auto,
}

impl Color {
    pub(crate) fn as_arg(self) -> &'static str {
        match self {
            Self::Always => "always",
            Self::Never => "never",
            Self::Auto => "auto",
        }
    }
}

/// A single parsed JSONL event from `--json` output.
///
/// The `event_type` field corresponds to the `"type"` key in the JSON.
/// All other fields are captured in `extra`.
#[cfg(feature = "json")]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JsonLineEvent {
    #[serde(rename = "type", default)]
    pub event_type: String,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

#[cfg(feature = "json")]
impl JsonLineEvent {
    /// Returns the `session_id` field, if present and a string.
    #[must_use]
    pub fn session_id(&self) -> Option<&str> {
        self.extra.get("session_id").and_then(|v| v.as_str())
    }

    /// Returns the `thread_id` field, if present and a string.
    #[must_use]
    pub fn thread_id(&self) -> Option<&str> {
        self.extra.get("thread_id").and_then(|v| v.as_str())
    }

    /// Returns `true` when the event type is `"completed"`.
    #[must_use]
    pub fn is_completed(&self) -> bool {
        self.event_type == "completed"
    }

    /// Returns the nested `result.text` field, if present and a string.
    #[must_use]
    pub fn result_text(&self) -> Option<&str> {
        self.extra
            .get("result")
            .and_then(|v| v.get("text"))
            .and_then(|v| v.as_str())
    }

    /// Returns the nested `result.cost` field in USD, if present and numeric.
    #[must_use]
    pub fn cost_usd(&self) -> Option<f64> {
        self.extra
            .get("result")
            .and_then(|v| v.get("cost"))
            .and_then(|v| v.as_f64())
    }

    /// Returns the `role` field, if present and a string.
    #[must_use]
    pub fn role(&self) -> Option<&str> {
        self.extra.get("role").and_then(|v| v.as_str())
    }

    /// Extracts concatenated text from a `content` blocks array.
    ///
    /// Each block with `"type": "text"` contributes its `"text"` value.
    /// Returns `None` if there is no `content` array or no text blocks.
    #[must_use]
    pub fn content_text(&self) -> Option<String> {
        let blocks = self.extra.get("content").and_then(|v| v.as_array())?;
        let text: String = blocks
            .iter()
            .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("text"))
            .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
            .collect::<Vec<_>>()
            .join("");
        if text.is_empty() { None } else { Some(text) }
    }
}

/// A typed summary of a completed `codex exec` run, assembled from the JSONL
/// event stream.
///
/// This mirrors the shape of `claude-wrapper`'s `QueryResult` so a downstream
/// abstraction can treat both wrappers uniformly. The full parsed event stream
/// is retained in [`events`](QueryResult::events) as an escape hatch for fields
/// not surfaced here.
#[cfg(feature = "json")]
#[derive(Debug, Clone)]
pub struct QueryResult {
    /// Final assistant text from the terminal `completed` event.
    ///
    /// Empty if no `completed` event carried a `result.text` value.
    pub result: String,
    /// The `session_id` captured from the event stream, if any.
    pub session_id: Option<String>,
    /// The `thread_id` captured from the event stream, if any.
    ///
    /// This is Codex's native identifier for resuming a conversation.
    pub thread_id: Option<String>,
    /// Total cost in USD from the `completed` event, if reported.
    pub cost_usd: Option<f64>,
    /// The full parsed event stream this result was assembled from.
    pub events: Vec<JsonLineEvent>,
}

#[cfg(feature = "json")]
impl QueryResult {
    /// Assemble a [`QueryResult`] from a parsed JSONL event stream.
    ///
    /// `result` and `cost_usd` are taken from the last `completed` event;
    /// `session_id` and `thread_id` are the first occurrences in the stream.
    #[must_use]
    pub fn from_events(events: Vec<JsonLineEvent>) -> Self {
        let completed = events.iter().rev().find(|e| e.is_completed());
        let result = completed
            .and_then(JsonLineEvent::result_text)
            .unwrap_or_default()
            .to_string();
        let cost_usd = completed.and_then(JsonLineEvent::cost_usd);
        let session_id = events
            .iter()
            .find_map(JsonLineEvent::session_id)
            .map(str::to_string);
        let thread_id = events
            .iter()
            .find_map(JsonLineEvent::thread_id)
            .map(str::to_string);
        Self {
            result,
            session_id,
            thread_id,
            cost_usd,
            events,
        }
    }
}

/// Parsed semantic version of the Codex CLI (`major.minor.patch`).
///
/// Supports comparison and ordering for version-gating logic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CliVersion {
    pub major: u32,
    pub minor: u32,
    pub patch: u32,
}

impl CliVersion {
    #[must_use]
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    pub fn parse_version_output(output: &str) -> Result<Self, VersionParseError> {
        output
            .split_whitespace()
            .find_map(|token| token.parse().ok())
            .ok_or_else(|| VersionParseError(output.trim().to_string()))
    }

    #[must_use]
    pub fn satisfies_minimum(&self, minimum: &CliVersion) -> bool {
        self >= minimum
    }
}

impl PartialOrd for CliVersion {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for CliVersion {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.major
            .cmp(&other.major)
            .then(self.minor.cmp(&other.minor))
            .then(self.patch.cmp(&other.patch))
    }
}

impl fmt::Display for CliVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

impl FromStr for CliVersion {
    type Err = VersionParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('.').collect();
        if parts.len() != 3 {
            return Err(VersionParseError(s.to_string()));
        }

        Ok(Self {
            major: parts[0]
                .parse()
                .map_err(|_| VersionParseError(s.to_string()))?,
            minor: parts[1]
                .parse()
                .map_err(|_| VersionParseError(s.to_string()))?,
            patch: parts[2]
                .parse()
                .map_err(|_| VersionParseError(s.to_string()))?,
        })
    }
}

#[derive(Debug, Clone, thiserror::Error)]
#[error("invalid version string: {0:?}")]
pub struct VersionParseError(pub String);

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

    #[test]
    fn parses_codex_version_output() {
        let version = CliVersion::parse_version_output("codex-cli 0.145.0").unwrap();
        assert_eq!(version, CliVersion::new(0, 145, 0));
    }

    #[test]
    fn parses_plain_version_output() {
        let version = CliVersion::parse_version_output("0.145.0").unwrap();
        assert_eq!(version, CliVersion::new(0, 145, 0));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_session_and_thread_id() {
        let event: JsonLineEvent = serde_json::from_str(
            r#"{"type":"message.created","session_id":"sess_abc","thread_id":"thread_123"}"#,
        )
        .unwrap();
        assert_eq!(event.session_id(), Some("sess_abc"));
        assert_eq!(event.thread_id(), Some("thread_123"));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_is_completed() {
        let completed: JsonLineEvent = serde_json::from_str(r#"{"type":"completed"}"#).unwrap();
        assert!(completed.is_completed());

        let other: JsonLineEvent = serde_json::from_str(r#"{"type":"message.created"}"#).unwrap();
        assert!(!other.is_completed());
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_result_text_and_cost() {
        let event: JsonLineEvent = serde_json::from_str(
            r#"{"type":"completed","result":{"text":"hello world","cost":0.0042}}"#,
        )
        .unwrap();
        assert_eq!(event.result_text(), Some("hello world"));
        assert!((event.cost_usd().unwrap() - 0.0042).abs() < f64::EPSILON);
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_result_text_missing() {
        let event: JsonLineEvent = serde_json::from_str(r#"{"type":"completed"}"#).unwrap();
        assert_eq!(event.result_text(), None);
        assert_eq!(event.cost_usd(), None);
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_role() {
        let event: JsonLineEvent =
            serde_json::from_str(r#"{"type":"message.created","role":"assistant"}"#).unwrap();
        assert_eq!(event.role(), Some("assistant"));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_content_text() {
        let event: JsonLineEvent = serde_json::from_str(
            r#"{"type":"message.delta","content":[{"type":"text","text":"Hello "},{"type":"text","text":"world"}]}"#,
        )
        .unwrap();
        assert_eq!(event.content_text(), Some("Hello world".to_string()));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_content_text_skips_non_text_blocks() {
        let event: JsonLineEvent = serde_json::from_str(
            r#"{"type":"message.delta","content":[{"type":"image","url":"x"},{"type":"text","text":"only this"}]}"#,
        )
        .unwrap();
        assert_eq!(event.content_text(), Some("only this".to_string()));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_content_text_none_when_empty() {
        let event: JsonLineEvent =
            serde_json::from_str(r#"{"type":"message.delta","content":[]}"#).unwrap();
        assert_eq!(event.content_text(), None);
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_line_event_content_text_none_when_missing() {
        let event: JsonLineEvent = serde_json::from_str(r#"{"type":"message.delta"}"#).unwrap();
        assert_eq!(event.content_text(), None);
    }

    #[cfg(feature = "json")]
    #[test]
    fn query_result_from_events() {
        let events: Vec<JsonLineEvent> = vec![
            serde_json::from_str(
                r#"{"type":"thread.started","session_id":"sess_1","thread_id":"thread_1"}"#,
            )
            .unwrap(),
            serde_json::from_str(r#"{"type":"message.created","role":"assistant"}"#).unwrap(),
            serde_json::from_str(r#"{"type":"completed","result":{"text":"done","cost":0.02}}"#)
                .unwrap(),
        ];
        let result = QueryResult::from_events(events);
        assert_eq!(result.result, "done");
        assert_eq!(result.session_id.as_deref(), Some("sess_1"));
        assert_eq!(result.thread_id.as_deref(), Some("thread_1"));
        assert_eq!(result.cost_usd, Some(0.02));
        assert_eq!(result.events.len(), 3);
    }

    #[cfg(feature = "json")]
    #[test]
    fn query_result_from_events_no_completed() {
        let events: Vec<JsonLineEvent> =
            vec![serde_json::from_str(r#"{"type":"message.created"}"#).unwrap()];
        let result = QueryResult::from_events(events);
        assert_eq!(result.result, "");
        assert_eq!(result.cost_usd, None);
        assert!(result.session_id.is_none());
        assert!(result.thread_id.is_none());
    }
}