Skip to main content

codex_wrapper/
types.rs

1//! Domain types shared across commands: enums for CLI options, version parsing,
2//! and structured JSONL events.
3//!
4//! # JSONL schema: what is verified and what is assumed
5//!
6//! This parser was rewritten in #73 after the previous one was found to match
7//! an event shape the CLI never emits. It matched a fixture that invented the
8//! schema, so every test passed while real output produced empty results. The
9//! split below exists so the next person can check the assumptions instead of
10//! rediscovering the bug.
11//!
12//! **Verified** against `codex-cli` 0.145.0, from the compiled serde tag list
13//! and live runs of both `codex exec --json` and `codex exec review --json`:
14//!
15//! - The event vocabulary is `thread.started`, `turn.started`, `turn.completed`,
16//!   `turn.failed`, `item.started`, `item.updated`, `item.completed`. There is
17//!   no bare `completed`. Review emits the same vocabulary as exec.
18//! - `thread.started` carries `thread_id`.
19//! - A completed turn reports token counts, never a monetary cost. The `usage`
20//!   object carries `input_tokens`, `cached_input_tokens`,
21//!   `cache_write_input_tokens`, `output_tokens`, and
22//!   `reasoning_output_tokens`. It does **not** carry `total_tokens`, so
23//!   [`TokenUsage::total`] reaches a total through its input plus output
24//!   fallback on every real run.
25//! - Assistant text arrives as an `item.completed` event whose `item` has a
26//!   `type` of `agent_message` and its text in a `text` field. A review's
27//!   diff-reading steps arrive as `command_execution` items on the same event.
28//! - A review's `turn.completed` reports a usage object of all zeros.
29//! - Exhausting the native rollout budget emits an `error` event followed by
30//!   `turn.failed`, both with `shared rollout token budget exhausted`. The
31//!   terminal event carries no usage object on 0.145.0 even though Codex used
32//!   its internal meter to make the decision.
33//! - An upstream API rejection emits an `error` event followed by
34//!   `turn.failed`, and the CLI exits 1. Verified on 0.149.0 with two
35//!   distinct output-schema rejections. Both terminal events carry the
36//!   upstream error as a JSON **document nested inside the `error.message`
37//!   string**, not as sibling fields: `{"type":"error","error":{"type":
38//!   "invalid_request_error","code":"invalid_json_schema","message":...,
39//!   "param":"text.format.schema"},"status":400}`. The human message differs
40//!   between the two runs; `type`, `code`, and `status` do not. This is why
41//!   [`JsonLineEvent::turn_failure_api_error`] parses the message rather than
42//!   reading a sibling code, and it corrects the earlier note that Codex
43//!   emits no machine-readable error code.
44//!
45//! - The stream carries **no incremental text**. Three captured runs, a
46//!   one-word exec, a four-sentence exec, and a review, each delivered the
47//!   whole assistant message in a single `item.completed`. No `item.updated`,
48//!   no partial or delta fields, and `codex exec --help` has no flag that
49//!   changes output granularity. There is nothing to assemble, which is why
50//!   this module has no equivalent of `claude-wrapper`'s `PartialMessageEvent`
51//!   (#84).
52//!
53//! **Assumed**, still: nothing load-bearing.
54//! [`JsonLineEvent::agent_message_text`] also accepts an `item_type`
55//! discriminator and a `content` block array, neither of which has been seen
56//! in real output. That tolerance stays because the failure mode when this
57//! parser guesses wrong is an empty result rather than an error, which is how
58//! #73 went unnoticed.
59//!
60//! To re-confirm after a CLI upgrade, capture a run and check `result` is
61//! non-empty:
62//!
63//! ```sh
64//! codex exec --json --ephemeral --skip-git-repo-check "reply with: ok" > turn.jsonl
65//! ```
66
67#[cfg(feature = "json")]
68use std::collections::HashMap;
69use std::fmt;
70use std::str::FromStr;
71
72use serde::{Deserialize, Serialize};
73
74/// Sandbox policy for model-generated shell commands.
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "kebab-case")]
77pub enum SandboxMode {
78    /// Read-only filesystem access.
79    ReadOnly,
80    /// Write access limited to the workspace directory (default).
81    #[default]
82    WorkspaceWrite,
83    /// Full filesystem access -- use with extreme caution.
84    DangerFullAccess,
85}
86
87impl SandboxMode {
88    pub(crate) fn as_arg(self) -> &'static str {
89        match self {
90            Self::ReadOnly => "read-only",
91            Self::WorkspaceWrite => "workspace-write",
92            Self::DangerFullAccess => "danger-full-access",
93        }
94    }
95}
96
97/// When the model should ask for human approval before executing commands.
98///
99/// These are the values accepted by the `--ask-for-approval` flag on
100/// [`ForkCommand`](crate::ForkCommand) and [`ResumeCommand`](crate::ResumeCommand).
101/// The exec family sets the same setting through the `approval_policy` config
102/// key, which accepts a larger value set -- see [`ApprovalPolicyConfig`].
103#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "kebab-case")]
105pub enum ApprovalPolicy {
106    /// Only run trusted commands without asking.
107    Untrusted,
108    /// The model decides when to ask (default).
109    #[default]
110    OnRequest,
111    /// Never ask for approval.
112    Never,
113}
114
115impl ApprovalPolicy {
116    pub(crate) fn as_arg(self) -> &'static str {
117        match self {
118            Self::Untrusted => "untrusted",
119            Self::OnRequest => "on-request",
120            Self::Never => "never",
121        }
122    }
123}
124
125/// Approval policy values accepted by the `approval_policy` config key.
126///
127/// `codex-cli` 0.145.0 removed `--ask-for-approval` from the exec family; the
128/// config key is the supported equivalent. It accepts two values the flag does
129/// not ([`OnFailure`](Self::OnFailure) and [`Granular`](Self::Granular)), which
130/// is why this is a separate type from [`ApprovalPolicy`] rather than an alias.
131/// The three shared values convert implicitly:
132///
133/// ```
134/// use codex_wrapper::{ApprovalPolicy, ApprovalPolicyConfig};
135///
136/// let config: ApprovalPolicyConfig = ApprovalPolicy::Never.into();
137/// assert_eq!(config, ApprovalPolicyConfig::Never);
138/// ```
139#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "kebab-case")]
141pub enum ApprovalPolicyConfig {
142    /// Only run trusted commands without asking.
143    Untrusted,
144    /// Ask after a command fails.
145    ///
146    /// Not accepted by `--ask-for-approval`, so it has no [`ApprovalPolicy`]
147    /// counterpart.
148    OnFailure,
149    /// The model decides when to ask (default).
150    #[default]
151    OnRequest,
152    /// Ask per-operation rather than per-command.
153    ///
154    /// Not accepted by `--ask-for-approval`, so it has no [`ApprovalPolicy`]
155    /// counterpart.
156    Granular,
157    /// Never ask for approval.
158    Never,
159}
160
161impl ApprovalPolicyConfig {
162    pub(crate) fn as_config_value(self) -> &'static str {
163        match self {
164            Self::Untrusted => "untrusted",
165            Self::OnFailure => "on-failure",
166            Self::OnRequest => "on-request",
167            Self::Granular => "granular",
168            Self::Never => "never",
169        }
170    }
171}
172
173impl From<ApprovalPolicy> for ApprovalPolicyConfig {
174    fn from(policy: ApprovalPolicy) -> Self {
175        match policy {
176            ApprovalPolicy::Untrusted => Self::Untrusted,
177            ApprovalPolicy::OnRequest => Self::OnRequest,
178            ApprovalPolicy::Never => Self::Never,
179        }
180    }
181}
182
183impl TryFrom<ApprovalPolicyConfig> for ApprovalPolicy {
184    type Error = ApprovalPolicyConfig;
185
186    /// Narrow to the flag-accepted subset.
187    ///
188    /// Returns the original value as the error for
189    /// [`OnFailure`](ApprovalPolicyConfig::OnFailure) and
190    /// [`Granular`](ApprovalPolicyConfig::Granular), which `--ask-for-approval`
191    /// rejects.
192    fn try_from(config: ApprovalPolicyConfig) -> std::result::Result<Self, Self::Error> {
193        match config {
194            ApprovalPolicyConfig::Untrusted => Ok(Self::Untrusted),
195            ApprovalPolicyConfig::OnRequest => Ok(Self::OnRequest),
196            ApprovalPolicyConfig::Never => Ok(Self::Never),
197            other => Err(other),
198        }
199    }
200}
201
202/// Web search mode, set through the `web_search` config key.
203///
204/// `codex-cli` 0.145.0 removed `--search` from the exec family. The config key
205/// replacing it is an enum rather than the flag's boolean;
206/// [`Live`](Self::Live) is what `--search` meant.
207///
208/// `--search` is still a valid flag on [`ForkCommand`](crate::ForkCommand) and
209/// [`ResumeCommand`](crate::ResumeCommand), which keep their boolean setters.
210#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(rename_all = "kebab-case")]
212pub enum WebSearchMode {
213    /// No web search.
214    #[default]
215    Disabled,
216    /// Serve results from cache only.
217    Cached,
218    /// Search a prebuilt index.
219    Indexed,
220    /// Live web search. The `--search` flag's former behavior.
221    Live,
222}
223
224impl WebSearchMode {
225    pub(crate) fn as_config_value(self) -> &'static str {
226        match self {
227            Self::Disabled => "disabled",
228            Self::Cached => "cached",
229            Self::Indexed => "indexed",
230            Self::Live => "live",
231        }
232    }
233}
234
235/// Color output mode for exec commands.
236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "lowercase")]
238pub enum Color {
239    /// Always emit color codes.
240    Always,
241    /// Never emit color codes.
242    Never,
243    /// Auto-detect terminal support (default).
244    #[default]
245    Auto,
246}
247
248impl Color {
249    pub(crate) fn as_arg(self) -> &'static str {
250        match self {
251            Self::Always => "always",
252            Self::Never => "never",
253            Self::Auto => "auto",
254        }
255    }
256}
257
258/// A single parsed JSONL event from `--json` output.
259///
260/// The `event_type` field corresponds to the `"type"` key in the JSON.
261/// All other fields are captured in `extra`.
262#[cfg(feature = "json")]
263#[derive(Debug, Clone, Deserialize, Serialize)]
264pub struct JsonLineEvent {
265    #[serde(rename = "type", default)]
266    pub event_type: String,
267    #[serde(flatten)]
268    pub extra: HashMap<String, serde_json::Value>,
269}
270
271/// A terminal `turn.failed` classification from the Codex JSONL stream.
272///
273/// Two classes are typed. The budget class is pinned to the stable message
274/// captured from 0.145.0. The API-rejection class reads the machine-readable
275/// code the upstream API supplies, captured from 0.149.0; see
276/// [`ApiFailure`]. Unknown failures remain distinguishable rather than being
277/// forced into either class.
278#[cfg(feature = "json")]
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280#[non_exhaustive]
281pub enum TurnFailureKind {
282    /// Codex stopped after exhausting its native shared rollout budget.
283    RolloutBudgetExhausted,
284    /// The upstream API rejected the request before generation began.
285    ///
286    /// The turn produced no output and had no side effects, so a caller may
287    /// correct the request and try again. [`JsonLineEvent::turn_failure_api_error`]
288    /// carries the code that distinguishes which part of the request was
289    /// rejected.
290    ApiRequestRejected,
291    /// A terminal failure not classified by this wrapper.
292    Other,
293}
294
295/// A structured API error carried by a terminal `turn.failed` event.
296///
297/// Codex nests the upstream API error as a JSON document inside the
298/// `error.message` string rather than as sibling fields, so reaching the code
299/// means parsing that string. Captured from `codex-cli` 0.149.0:
300///
301/// ```text
302/// {"type":"turn.failed","error":{"message":"{\n  \"type\": \"error\",
303///   \n  \"error\": {\n    \"type\": \"invalid_request_error\",
304///   \n    \"code\": \"invalid_json_schema\", ... },\n  \"status\": 400\n}"}}
305/// ```
306#[cfg(feature = "json")]
307#[derive(Debug, Clone, PartialEq, Eq, Default)]
308#[non_exhaustive]
309pub struct ApiFailure {
310    /// The API error class, such as `invalid_request_error`.
311    pub error_type: Option<String>,
312    /// The machine-readable code, such as `invalid_json_schema`.
313    pub code: Option<String>,
314    /// The HTTP status the API returned, such as 400.
315    pub status: Option<u64>,
316}
317
318#[cfg(feature = "json")]
319impl ApiFailure {
320    /// Whether the API rejected the request itself, before generation.
321    ///
322    /// A 4xx status other than 429 means the request was refused rather than
323    /// throttled or failed midway.
324    #[must_use]
325    pub fn rejected_request(&self) -> bool {
326        if self.error_type.as_deref() == Some("invalid_request_error") {
327            return true;
328        }
329        self.status
330            .is_some_and(|status| (400..500).contains(&status) && status != 429)
331    }
332}
333
334#[cfg(feature = "json")]
335impl JsonLineEvent {
336    /// Returns the `session_id` field, if present and a string.
337    #[must_use]
338    pub fn session_id(&self) -> Option<&str> {
339        self.extra.get("session_id").and_then(|v| v.as_str())
340    }
341
342    /// Returns the `thread_id` field, if present and a string.
343    #[must_use]
344    pub fn thread_id(&self) -> Option<&str> {
345        self.extra.get("thread_id").and_then(|v| v.as_str())
346    }
347
348    /// Returns `true` when this is the terminal event of a successful turn.
349    #[must_use]
350    pub fn is_turn_completed(&self) -> bool {
351        self.event_type == "turn.completed"
352    }
353
354    /// Returns `true` when this is the terminal event of a failed turn.
355    #[must_use]
356    pub fn is_turn_failed(&self) -> bool {
357        self.event_type == "turn.failed"
358    }
359
360    /// The message carried by a terminal `turn.failed` event.
361    ///
362    /// The captured CLI shape nests it under `error.message`.
363    #[must_use]
364    pub fn turn_failure_message(&self) -> Option<&str> {
365        if !self.is_turn_failed() {
366            return None;
367        }
368        self.extra
369            .get("error")
370            .and_then(|error| error.get("message"))
371            .and_then(serde_json::Value::as_str)
372    }
373
374    /// The structured API error carried by a terminal `turn.failed` event.
375    ///
376    /// Returns `None` on any other event, and when the failure message is not
377    /// the JSON document the API produces. A local failure such as an
378    /// exhausted rollout budget carries plain prose and yields `None` here.
379    #[must_use]
380    pub fn turn_failure_api_error(&self) -> Option<ApiFailure> {
381        let message = self.turn_failure_message()?;
382        let document: serde_json::Value = serde_json::from_str(message).ok()?;
383        let error = document.get("error")?;
384        let failure = ApiFailure {
385            error_type: error
386                .get("type")
387                .and_then(serde_json::Value::as_str)
388                .map(str::to_owned),
389            code: error
390                .get("code")
391                .and_then(serde_json::Value::as_str)
392                .map(str::to_owned),
393            status: document.get("status").and_then(serde_json::Value::as_u64),
394        };
395        (failure != ApiFailure::default()).then_some(failure)
396    }
397
398    /// Classify a terminal `turn.failed` event without downstream string matching.
399    #[must_use]
400    pub fn turn_failure_kind(&self) -> Option<TurnFailureKind> {
401        self.is_turn_failed().then(|| {
402            if self
403                .turn_failure_message()
404                .is_some_and(|message| message.contains("shared rollout token budget exhausted"))
405            {
406                TurnFailureKind::RolloutBudgetExhausted
407            } else if self
408                .turn_failure_api_error()
409                .is_some_and(|error| error.rejected_request())
410            {
411                TurnFailureKind::ApiRequestRejected
412            } else {
413                TurnFailureKind::Other
414            }
415        })
416    }
417
418    /// Token counts reported by a `turn.completed` event.
419    ///
420    /// Returns `None` on any other event, or when no `usage` object is
421    /// present. The CLI reports tokens, not money; see [`TokenUsage`].
422    #[must_use]
423    pub fn usage(&self) -> Option<TokenUsage> {
424        self.extra.get("usage").map(TokenUsage::from_json)
425    }
426
427    /// Assistant text carried by an `item.completed` agent-message item.
428    ///
429    /// Returns `None` for any other event or item type.
430    ///
431    /// Real output uses a `type` discriminator and a `text` field; see the
432    /// schema block at the top of this module. An `item_type` discriminator
433    /// and a `content` block array are also accepted, neither of them
434    /// observed. Tolerating the unobserved shapes is deliberate: the previous
435    /// parser committed to one exact layout and silently yielded empty results
436    /// when it was wrong, which is the bug this replaces.
437    #[must_use]
438    pub fn agent_message_text(&self) -> Option<String> {
439        if self.event_type != "item.completed" {
440            return None;
441        }
442        let item = self.extra.get("item")?;
443        let kind = item
444            .get("item_type")
445            .or_else(|| item.get("type"))
446            .and_then(|v| v.as_str())?;
447        if kind != "agent_message" {
448            return None;
449        }
450
451        if let Some(text) = item.get("text").and_then(|v| v.as_str())
452            && !text.is_empty()
453        {
454            return Some(text.to_string());
455        }
456
457        let blocks = item.get("content").and_then(|v| v.as_array())?;
458        let text: String = blocks
459            .iter()
460            .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
461            .collect::<Vec<_>>()
462            .join("");
463        if text.is_empty() { None } else { Some(text) }
464    }
465
466    /// Returns the `role` field, if present and a string.
467    #[must_use]
468    pub fn role(&self) -> Option<&str> {
469        self.extra.get("role").and_then(|v| v.as_str())
470    }
471
472    /// Extracts concatenated text from a `content` blocks array.
473    ///
474    /// Each block with `"type": "text"` contributes its `"text"` value.
475    /// Returns `None` if there is no `content` array or no text blocks.
476    #[must_use]
477    pub fn content_text(&self) -> Option<String> {
478        let blocks = self.extra.get("content").and_then(|v| v.as_array())?;
479        let text: String = blocks
480            .iter()
481            .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("text"))
482            .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
483            .collect::<Vec<_>>()
484            .join("");
485        if text.is_empty() { None } else { Some(text) }
486    }
487
488    /// The `item` discriminator on an `item.*` event.
489    ///
490    /// `agent_message` and `command_execution` are the observed values. This
491    /// is the field to match on when narrowing an item event, and it is
492    /// present on `item.started` as well as `item.completed`.
493    ///
494    /// Accepts `item_type` as well as `type` for the same reason
495    /// [`agent_message_text`](Self::agent_message_text) does.
496    #[must_use]
497    pub fn item_type(&self) -> Option<&str> {
498        let item = self.extra.get("item")?;
499        item.get("type").or_else(|| item.get("item_type"))?.as_str()
500    }
501
502    /// A shell command the model ran, from a `command_execution` item.
503    ///
504    /// `None` for any other item. `exit_code` and `status` are only populated
505    /// on `item.completed`; an `item.started` for the same command carries the
506    /// command alone.
507    #[must_use]
508    pub fn command_execution(&self) -> Option<CommandExecution> {
509        if self.item_type()? != "command_execution" {
510            return None;
511        }
512        let item = self.extra.get("item")?;
513        let string = |key: &str| item.get(key).and_then(|v| v.as_str()).map(str::to_string);
514        Some(CommandExecution {
515            command: string("command"),
516            status: string("status"),
517            exit_code: item
518                .get("exit_code")
519                .and_then(serde_json::Value::as_i64)
520                .and_then(|code| i32::try_from(code).ok()),
521            aggregated_output: string("aggregated_output"),
522        })
523    }
524}
525
526/// A typed summary of a completed `codex exec` run, assembled from the JSONL
527/// event stream.
528///
529/// This mirrors the shape of `claude-wrapper`'s `QueryResult` so a downstream
530/// abstraction can treat both wrappers uniformly. The full parsed event stream
531/// is retained in [`events`](QueryResult::events) as an escape hatch for fields
532/// not surfaced here.
533#[cfg(feature = "json")]
534#[derive(Debug, Clone)]
535pub struct QueryResult {
536    /// Assistant text, concatenated from the turn's agent-message items.
537    ///
538    /// Empty when the turn produced no agent message. A failed turn can still
539    /// carry text produced before its terminal failure; native rollout-budget
540    /// exhaustion is one observed example.
541    pub result: String,
542    /// The `session_id` captured from the event stream, if any.
543    ///
544    /// Observed live runs carry only `thread_id`, so this is usually `None`.
545    /// Retained because it costs nothing and the field may exist under auth
546    /// modes not yet observed.
547    pub session_id: Option<String>,
548    /// The `thread_id` captured from the event stream, if any.
549    ///
550    /// Codex's native identifier for resuming a conversation, emitted on
551    /// `thread.started`.
552    pub thread_id: Option<String>,
553    /// Token counts from the terminal `turn.completed` event, if present.
554    ///
555    /// The CLI reports tokens, not money. There is no cost field to read; see
556    /// [`TokenUsage`].
557    pub usage: Option<TokenUsage>,
558    /// The full parsed event stream this result was assembled from.
559    ///
560    /// The escape hatch for anything not surfaced above, including whatever
561    /// this parser gets wrong.
562    pub events: Vec<JsonLineEvent>,
563}
564
565#[cfg(feature = "json")]
566impl QueryResult {
567    /// Assemble a [`QueryResult`] from a parsed JSONL event stream.
568    ///
569    /// `usage` comes from the last `turn.completed` event; `result` is every
570    /// agent-message item concatenated in order; `session_id` and `thread_id`
571    /// are the first occurrences in the stream.
572    #[must_use]
573    pub fn from_events(events: Vec<JsonLineEvent>) -> Self {
574        let usage = events
575            .iter()
576            .rev()
577            .find(|e| e.is_turn_completed())
578            .and_then(JsonLineEvent::usage);
579        let result = events
580            .iter()
581            .filter_map(JsonLineEvent::agent_message_text)
582            .collect::<Vec<_>>()
583            .join("");
584        let session_id = events
585            .iter()
586            .find_map(JsonLineEvent::session_id)
587            .map(str::to_string);
588        let thread_id = events
589            .iter()
590            .find_map(JsonLineEvent::thread_id)
591            .map(str::to_string);
592        Self {
593            result,
594            session_id,
595            thread_id,
596            usage,
597            events,
598        }
599    }
600}
601
602/// A shell command the model ran, from a `command_execution` item.
603///
604/// Every field is optional: an `item.started` carries the command with no
605/// outcome yet, and the CLI has added fields to this item before.
606#[cfg(feature = "json")]
607#[derive(Debug, Clone, Default, PartialEq, Eq)]
608#[non_exhaustive]
609pub struct CommandExecution {
610    /// The command line, as the CLI recorded it.
611    pub command: Option<String>,
612    /// Reported status, `completed` being the observed value.
613    pub status: Option<String>,
614    /// Exit code, once the command has finished.
615    pub exit_code: Option<i32>,
616    /// Combined stdout and stderr, when the CLI included it.
617    pub aggregated_output: Option<String>,
618}
619
620/// Token counts reported on a completed turn.
621///
622/// `codex-cli` 0.145.0 reports token usage and no monetary cost. Converting
623/// tokens to dollars needs a per-model price table the CLI does not provide,
624/// so this crate does not attempt it: a hardcoded table would go stale
625/// silently, which is the same class of bug as #73.
626///
627/// Every field is optional, and absence is normal rather than exceptional:
628/// observed runs carry five of the six and never `total_tokens`, which is why
629/// [`TokenUsage::total`] falls back to input plus output.
630#[cfg(feature = "json")]
631#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
632pub struct TokenUsage {
633    /// Input tokens for the turn.
634    pub input_tokens: Option<u64>,
635    /// Input tokens served from cache.
636    pub cached_input_tokens: Option<u64>,
637    /// Input tokens written to cache.
638    pub cache_write_input_tokens: Option<u64>,
639    /// Output tokens for the turn.
640    pub output_tokens: Option<u64>,
641    /// Output tokens spent on reasoning.
642    pub reasoning_output_tokens: Option<u64>,
643    /// Total tokens, if the CLI ever reports one. Observed runs do not.
644    pub total_tokens: Option<u64>,
645}
646
647#[cfg(feature = "json")]
648impl TokenUsage {
649    fn from_json(value: &serde_json::Value) -> Self {
650        let field = |name: &str| value.get(name).and_then(serde_json::Value::as_u64);
651        Self {
652            input_tokens: field("input_tokens"),
653            cached_input_tokens: field("cached_input_tokens"),
654            cache_write_input_tokens: field("cache_write_input_tokens"),
655            output_tokens: field("output_tokens"),
656            reasoning_output_tokens: field("reasoning_output_tokens"),
657            total_tokens: field("total_tokens"),
658        }
659    }
660
661    /// Best available total for the turn.
662    ///
663    /// Prefers the CLI's own `total_tokens`, falls back to input plus output
664    /// when it is absent, and returns `None` when neither is reported, so a
665    /// missing total is never silently counted as zero.
666    #[must_use]
667    pub fn total(&self) -> Option<u64> {
668        if let Some(total) = self.total_tokens {
669            return Some(total);
670        }
671        match (self.input_tokens, self.output_tokens) {
672            (None, None) => None,
673            (input, output) => Some(input.unwrap_or(0) + output.unwrap_or(0)),
674        }
675    }
676}
677
678/// Parsed semantic version of the Codex CLI (`major.minor.patch`).
679///
680/// Supports comparison and ordering for version-gating logic.
681#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
682pub struct CliVersion {
683    pub major: u32,
684    pub minor: u32,
685    pub patch: u32,
686}
687
688impl CliVersion {
689    #[must_use]
690    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
691        Self {
692            major,
693            minor,
694            patch,
695        }
696    }
697
698    pub fn parse_version_output(output: &str) -> Result<Self, VersionParseError> {
699        output
700            .split_whitespace()
701            .find_map(|token| token.parse().ok())
702            .ok_or_else(|| VersionParseError(output.trim().to_string()))
703    }
704
705    #[must_use]
706    pub fn satisfies_minimum(&self, minimum: &CliVersion) -> bool {
707        self >= minimum
708    }
709
710    /// Classify this version against a tested-against range.
711    ///
712    /// ```
713    /// use codex_wrapper::{CliVersion, CliVersionStatus};
714    ///
715    /// let min = CliVersion::new(0, 145, 0);
716    /// let max = CliVersion::new(0, 146, 0);
717    ///
718    /// assert!(CliVersion::new(0, 145, 3).status_within(&min, &max).is_tested());
719    /// assert!(!CliVersion::new(0, 200, 0).status_within(&min, &max).is_tested());
720    /// ```
721    #[must_use]
722    pub fn status_within(&self, min: &CliVersion, max: &CliVersion) -> CliVersionStatus {
723        if self < min {
724            CliVersionStatus::OlderThanMinimum {
725                found: *self,
726                minimum: *min,
727            }
728        } else if self > max {
729            CliVersionStatus::NewerUntested {
730                found: *self,
731                tested_max: *max,
732            }
733        } else {
734            CliVersionStatus::Tested
735        }
736    }
737}
738
739/// Classification of an installed CLI version against a tested range.
740///
741/// Returned by [`CliVersion::status_within`] and
742/// [`Codex::cli_version_status`](crate::Codex::cli_version_status). Mirrors
743/// `claude-wrapper`'s enum of the same name so a downstream abstraction can
744/// treat both wrappers uniformly.
745///
746/// There is deliberately no `Unparseable` variant: unparseable output is an
747/// error from [`Codex::cli_version`](crate::Codex::cli_version), not a status,
748/// and modeling it twice would fork this shape away from the sibling crate.
749#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
750#[serde(tag = "status", rename_all = "snake_case")]
751pub enum CliVersionStatus {
752    /// Within the tested-against range.
753    Tested,
754    /// Newer than the highest tested version.
755    ///
756    /// The wrapper should still generally work; semantics may have drifted.
757    NewerUntested {
758        /// The installed CLI version.
759        found: CliVersion,
760        /// Highest version this wrapper is tested against.
761        tested_max: CliVersion,
762    },
763    /// Older than the lowest tested version.
764    ///
765    /// Incorrect behavior is likely rather than merely possible: the arguments
766    /// this wrapper emits target the newer CLI, and older releases reject some
767    /// of them outright.
768    OlderThanMinimum {
769        /// The installed CLI version.
770        found: CliVersion,
771        /// Lowest version this wrapper is tested against.
772        minimum: CliVersion,
773    },
774}
775
776impl CliVersionStatus {
777    /// True only for [`Tested`](Self::Tested).
778    ///
779    /// For callers branching on "should I run?" without matching every
780    /// variant.
781    #[must_use]
782    pub fn is_tested(self) -> bool {
783        matches!(self, Self::Tested)
784    }
785}
786
787impl PartialOrd for CliVersion {
788    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
789        Some(self.cmp(other))
790    }
791}
792
793impl Ord for CliVersion {
794    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
795        self.major
796            .cmp(&other.major)
797            .then(self.minor.cmp(&other.minor))
798            .then(self.patch.cmp(&other.patch))
799    }
800}
801
802impl fmt::Display for CliVersion {
803    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
805    }
806}
807
808impl FromStr for CliVersion {
809    type Err = VersionParseError;
810
811    fn from_str(s: &str) -> Result<Self, Self::Err> {
812        let parts: Vec<&str> = s.split('.').collect();
813        if parts.len() != 3 {
814            return Err(VersionParseError(s.to_string()));
815        }
816
817        Ok(Self {
818            major: parts[0]
819                .parse()
820                .map_err(|_| VersionParseError(s.to_string()))?,
821            minor: parts[1]
822                .parse()
823                .map_err(|_| VersionParseError(s.to_string()))?,
824            patch: parts[2]
825                .parse()
826                .map_err(|_| VersionParseError(s.to_string()))?,
827        })
828    }
829}
830
831#[derive(Debug, Clone, thiserror::Error)]
832#[error("invalid version string: {0:?}")]
833pub struct VersionParseError(pub String);
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838
839    #[test]
840    fn parses_codex_version_output() {
841        let version = CliVersion::parse_version_output("codex-cli 0.145.0").unwrap();
842        assert_eq!(version, CliVersion::new(0, 145, 0));
843    }
844
845    #[test]
846    fn parses_plain_version_output() {
847        let version = CliVersion::parse_version_output("0.145.0").unwrap();
848        assert_eq!(version, CliVersion::new(0, 145, 0));
849    }
850
851    #[cfg(feature = "json")]
852    #[test]
853    fn json_line_event_session_and_thread_id() {
854        let event: JsonLineEvent = serde_json::from_str(
855            r#"{"type":"message.created","session_id":"sess_abc","thread_id":"thread_123"}"#,
856        )
857        .unwrap();
858        assert_eq!(event.session_id(), Some("sess_abc"));
859        assert_eq!(event.thread_id(), Some("thread_123"));
860    }
861
862    #[cfg(feature = "json")]
863    #[test]
864    fn json_line_event_turn_terminal_types() {
865        let completed: JsonLineEvent =
866            serde_json::from_str(r#"{"type":"turn.completed"}"#).unwrap();
867        assert!(completed.is_turn_completed());
868        assert!(!completed.is_turn_failed());
869
870        let failed: JsonLineEvent = serde_json::from_str(r#"{"type":"turn.failed"}"#).unwrap();
871        assert!(failed.is_turn_failed());
872        assert!(!failed.is_turn_completed());
873
874        // The pre-#73 parser matched this. The CLI has never emitted it.
875        let bogus: JsonLineEvent = serde_json::from_str(r#"{"type":"completed"}"#).unwrap();
876        assert!(!bogus.is_turn_completed());
877    }
878
879    /// Transcribed from a paid `codex-cli` 0.145.0 run with a one-unit native
880    /// rollout budget. The CLI exposes the limit decision but no usage object.
881    #[cfg(feature = "json")]
882    #[test]
883    fn classifies_captured_rollout_budget_terminal_without_inventing_usage() {
884        let failed: JsonLineEvent = serde_json::from_str(
885            r#"{"type":"turn.failed","error":{"message":"shared rollout token budget exhausted"}}"#,
886        )
887        .unwrap();
888
889        assert_eq!(
890            failed.turn_failure_kind(),
891            Some(TurnFailureKind::RolloutBudgetExhausted)
892        );
893        assert_eq!(failed.usage(), None);
894
895        let other: JsonLineEvent = serde_json::from_str(
896            r#"{"type":"turn.failed","error":{"message":"tool policy rejected"}}"#,
897        )
898        .unwrap();
899        assert_eq!(other.turn_failure_kind(), Some(TurnFailureKind::Other));
900
901        let missing_message: JsonLineEvent =
902            serde_json::from_str(r#"{"type":"turn.failed"}"#).unwrap();
903        assert_eq!(
904            missing_message.turn_failure_kind(),
905            Some(TurnFailureKind::Other)
906        );
907
908        let nonterminal: JsonLineEvent =
909            serde_json::from_str(r#"{"type":"turn.started"}"#).unwrap();
910        assert_eq!(nonterminal.turn_failure_kind(), None);
911    }
912
913    /// Both lines are transcriptions of captured `codex-cli` 0.149.0 runs:
914    /// an output schema whose property omits `type`, and a root-level
915    /// `anyOf`. The human message differs between them; the code does not.
916    #[cfg(feature = "json")]
917    #[test]
918    fn classifies_an_api_request_rejection() {
919        let missing_type: JsonLineEvent = serde_json::from_str(
920            r#"{"type":"turn.failed","error":{"message":"{\n  \"type\": \"error\",\n  \"error\": {\n    \"type\": \"invalid_request_error\",\n    \"code\": \"invalid_json_schema\",\n    \"message\": \"Invalid schema for response_format 'codex_output_schema': In context=('properties', 'ok'), schema must have a 'type' key.\",\n    \"param\": \"text.format.schema\"\n  },\n  \"status\": 400\n}"}}"#,
921        )
922        .unwrap();
923        assert_eq!(
924            missing_type.turn_failure_kind(),
925            Some(TurnFailureKind::ApiRequestRejected)
926        );
927        let error = missing_type.turn_failure_api_error().unwrap();
928        assert_eq!(error.code.as_deref(), Some("invalid_json_schema"));
929        assert_eq!(error.error_type.as_deref(), Some("invalid_request_error"));
930        assert_eq!(error.status, Some(400));
931        assert!(error.rejected_request());
932
933        let root_any_of: JsonLineEvent = serde_json::from_str(
934            r#"{"type":"turn.failed","error":{"message":"{\n  \"type\": \"error\",\n  \"error\": {\n    \"type\": \"invalid_request_error\",\n    \"code\": \"invalid_json_schema\",\n    \"message\": \"Invalid schema for response_format 'codex_output_schema': schema must be a JSON Schema of 'type: \\\"object\\\"', got 'type: \\\"None\\\"'.\",\n    \"param\": \"text.format.schema\"\n  },\n  \"status\": 400\n}"}}"#,
935        )
936        .unwrap();
937        assert_eq!(
938            root_any_of.turn_failure_kind(),
939            Some(TurnFailureKind::ApiRequestRejected)
940        );
941        assert_eq!(
942            root_any_of
943                .turn_failure_api_error()
944                .and_then(|error| error.code),
945            Some("invalid_json_schema".to_string())
946        );
947    }
948
949    /// A local failure carries prose, not the API's JSON document, and must
950    /// not be mistaken for a request rejection.
951    #[cfg(feature = "json")]
952    #[test]
953    fn a_prose_failure_message_carries_no_api_error() {
954        let budget: JsonLineEvent = serde_json::from_str(
955            r#"{"type":"turn.failed","error":{"message":"shared rollout token budget exhausted"}}"#,
956        )
957        .unwrap();
958        assert_eq!(budget.turn_failure_api_error(), None);
959        assert_eq!(
960            budget.turn_failure_kind(),
961            Some(TurnFailureKind::RolloutBudgetExhausted)
962        );
963
964        let other: JsonLineEvent = serde_json::from_str(
965            r#"{"type":"turn.failed","error":{"message":"tool policy rejected"}}"#,
966        )
967        .unwrap();
968        assert_eq!(other.turn_failure_api_error(), None);
969        assert_eq!(other.turn_failure_kind(), Some(TurnFailureKind::Other));
970    }
971
972    /// A server-side or throttling failure is not a rejected request: the
973    /// turn may have done work, so a caller must not treat it as safe to
974    /// replay after editing the request.
975    #[cfg(feature = "json")]
976    #[test]
977    fn server_and_throttling_failures_are_not_request_rejections() {
978        for (status, error_type) in [(500u64, "server_error"), (429, "rate_limit_error")] {
979            let message = format!(
980                r#"{{"type":"error","error":{{"type":"{error_type}","code":"x"}},"status":{status}}}"#
981            );
982            let event = JsonLineEvent {
983                event_type: "turn.failed".to_string(),
984                extra: HashMap::from([(
985                    "error".to_string(),
986                    serde_json::json!({ "message": message }),
987                )]),
988            };
989            assert!(!event.turn_failure_api_error().unwrap().rejected_request());
990            assert_eq!(event.turn_failure_kind(), Some(TurnFailureKind::Other));
991        }
992    }
993
994    #[cfg(feature = "json")]
995    #[test]
996    fn json_line_event_usage() {
997        let event: JsonLineEvent = serde_json::from_str(
998            r#"{"type":"turn.completed","usage":{"input_tokens":120,"output_tokens":45,"total_tokens":165}}"#,
999        )
1000        .unwrap();
1001        let usage = event.usage().unwrap();
1002        assert_eq!(usage.input_tokens, Some(120));
1003        assert_eq!(usage.output_tokens, Some(45));
1004        assert_eq!(usage.total_tokens, Some(165));
1005        // Absent from the observed payload, so absent here rather than zero.
1006        assert_eq!(usage.cache_write_input_tokens, None);
1007        assert_eq!(usage.total(), Some(165));
1008    }
1009
1010    #[cfg(feature = "json")]
1011    #[test]
1012    fn token_usage_total_falls_back_to_input_plus_output() {
1013        let usage = TokenUsage {
1014            input_tokens: Some(10),
1015            output_tokens: Some(5),
1016            ..TokenUsage::default()
1017        };
1018        assert_eq!(usage.total(), Some(15));
1019    }
1020
1021    /// A missing total must not read as zero, which would silently understate
1022    /// a session's usage.
1023    #[cfg(feature = "json")]
1024    #[test]
1025    fn token_usage_total_is_none_when_nothing_reported() {
1026        assert_eq!(TokenUsage::default().total(), None);
1027    }
1028
1029    /// The shape a real run emits: `type` on the item, text in `text`.
1030    #[cfg(feature = "json")]
1031    #[test]
1032    fn agent_message_text_from_item_completed() {
1033        let event: JsonLineEvent = serde_json::from_str(
1034            r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"hello"}}"#,
1035        )
1036        .unwrap();
1037        assert_eq!(event.agent_message_text().as_deref(), Some("hello"));
1038    }
1039
1040    /// `item_type` and content blocks are not shapes the CLI has been seen to
1041    /// emit. The accessor still tolerates them, because the cost of being
1042    /// wrong here is a silently empty result rather than a loud failure, which
1043    /// is how #73 stayed hidden. These cases keep that tolerance covered.
1044    #[cfg(feature = "json")]
1045    #[test]
1046    fn agent_message_text_tolerates_layout_variants() {
1047        let item_type_key: JsonLineEvent = serde_json::from_str(
1048            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"a"}}"#,
1049        )
1050        .unwrap();
1051        assert_eq!(item_type_key.agent_message_text().as_deref(), Some("a"));
1052
1053        let content_blocks: JsonLineEvent = serde_json::from_str(
1054            r#"{"type":"item.completed","item":{"item_type":"agent_message","content":[{"text":"b"},{"text":"c"}]}}"#,
1055        )
1056        .unwrap();
1057        assert_eq!(content_blocks.agent_message_text().as_deref(), Some("bc"));
1058    }
1059
1060    #[cfg(feature = "json")]
1061    #[test]
1062    fn agent_message_text_ignores_other_items_and_events() {
1063        // The item type a review's diff-reading steps arrive as.
1064        let other_item: JsonLineEvent = serde_json::from_str(
1065            r#"{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"git diff","exit_code":0}}"#,
1066        )
1067        .unwrap();
1068        assert_eq!(other_item.agent_message_text(), None);
1069
1070        let other_event: JsonLineEvent = serde_json::from_str(
1071            r#"{"type":"item.started","item":{"id":"item_0","type":"agent_message","text":"x"}}"#,
1072        )
1073        .unwrap();
1074        assert_eq!(other_event.agent_message_text(), None);
1075    }
1076
1077    #[cfg(feature = "json")]
1078    #[test]
1079    fn json_line_event_role() {
1080        let event: JsonLineEvent =
1081            serde_json::from_str(r#"{"type":"message.created","role":"assistant"}"#).unwrap();
1082        assert_eq!(event.role(), Some("assistant"));
1083    }
1084
1085    #[cfg(feature = "json")]
1086    #[test]
1087    fn json_line_event_content_text() {
1088        let event: JsonLineEvent = serde_json::from_str(
1089            r#"{"type":"message.delta","content":[{"type":"text","text":"Hello "},{"type":"text","text":"world"}]}"#,
1090        )
1091        .unwrap();
1092        assert_eq!(event.content_text(), Some("Hello world".to_string()));
1093    }
1094
1095    #[cfg(feature = "json")]
1096    #[test]
1097    fn json_line_event_content_text_skips_non_text_blocks() {
1098        let event: JsonLineEvent = serde_json::from_str(
1099            r#"{"type":"message.delta","content":[{"type":"image","url":"x"},{"type":"text","text":"only this"}]}"#,
1100        )
1101        .unwrap();
1102        assert_eq!(event.content_text(), Some("only this".to_string()));
1103    }
1104
1105    #[cfg(feature = "json")]
1106    #[test]
1107    fn json_line_event_content_text_none_when_empty() {
1108        let event: JsonLineEvent =
1109            serde_json::from_str(r#"{"type":"message.delta","content":[]}"#).unwrap();
1110        assert_eq!(event.content_text(), None);
1111    }
1112
1113    #[cfg(feature = "json")]
1114    #[test]
1115    fn json_line_event_content_text_none_when_missing() {
1116        let event: JsonLineEvent = serde_json::from_str(r#"{"type":"message.delta"}"#).unwrap();
1117        assert_eq!(event.content_text(), None);
1118    }
1119
1120    #[cfg(feature = "json")]
1121    #[test]
1122    fn query_result_from_events() {
1123        let events: Vec<JsonLineEvent> = [
1124            r#"{"type":"thread.started","thread_id":"thread_1"}"#,
1125            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"the answer"}}"#,
1126            r#"{"type":"turn.completed","usage":{"input_tokens":7,"output_tokens":3,"total_tokens":10}}"#,
1127        ]
1128        .iter()
1129        .map(|l| serde_json::from_str(l).unwrap())
1130        .collect();
1131
1132        let result = QueryResult::from_events(events);
1133        assert_eq!(result.result, "the answer");
1134        assert_eq!(result.thread_id.as_deref(), Some("thread_1"));
1135        assert_eq!(result.usage.unwrap().total(), Some(10));
1136        assert_eq!(result.events.len(), 3);
1137    }
1138
1139    #[cfg(feature = "json")]
1140    #[test]
1141    fn query_result_concatenates_multiple_agent_messages() {
1142        let events: Vec<JsonLineEvent> = [
1143            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"one "}}"#,
1144            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"two"}}"#,
1145            r#"{"type":"turn.completed","usage":{"total_tokens":4}}"#,
1146        ]
1147        .iter()
1148        .map(|l| serde_json::from_str(l).unwrap())
1149        .collect();
1150
1151        assert_eq!(QueryResult::from_events(events).result, "one two");
1152    }
1153
1154    /// A failed turn has no agent message and no usage. Both must come back
1155    /// empty rather than fabricated.
1156    #[cfg(feature = "json")]
1157    #[test]
1158    fn query_result_from_a_failed_turn() {
1159        let events: Vec<JsonLineEvent> = [
1160            r#"{"type":"thread.started","thread_id":"thread_2"}"#,
1161            r#"{"type":"turn.failed","error":{"message":"usage limit"}}"#,
1162        ]
1163        .iter()
1164        .map(|l| serde_json::from_str(l).unwrap())
1165        .collect();
1166
1167        let result = QueryResult::from_events(events);
1168        assert_eq!(result.result, "");
1169        assert_eq!(result.usage, None);
1170        assert_eq!(result.thread_id.as_deref(), Some("thread_2"));
1171    }
1172
1173    /// Both values transcribed from captured runs.
1174    #[cfg(feature = "json")]
1175    #[test]
1176    fn item_type_reads_the_discriminator() {
1177        let message: JsonLineEvent = serde_json::from_str(
1178            r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"hi"}}"#,
1179        )
1180        .unwrap();
1181        assert_eq!(message.item_type(), Some("agent_message"));
1182
1183        let command: JsonLineEvent = serde_json::from_str(
1184            r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"git diff"}}"#,
1185        )
1186        .unwrap();
1187        assert_eq!(command.item_type(), Some("command_execution"));
1188
1189        let turn: JsonLineEvent = serde_json::from_str(r#"{"type":"turn.completed"}"#).unwrap();
1190        assert_eq!(turn.item_type(), None);
1191    }
1192
1193    /// Transcribed from a captured `codex exec review` run, where the reviewer
1194    /// reads the diff before commenting.
1195    #[cfg(feature = "json")]
1196    #[test]
1197    fn command_execution_reads_a_finished_command() {
1198        let event: JsonLineEvent = serde_json::from_str(
1199            r#"{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"git diff","aggregated_output":"","exit_code":0,"status":"completed"}}"#,
1200        )
1201        .unwrap();
1202
1203        let command = event.command_execution().unwrap();
1204        assert_eq!(command.command.as_deref(), Some("git diff"));
1205        assert_eq!(command.exit_code, Some(0));
1206        assert_eq!(command.status.as_deref(), Some("completed"));
1207    }
1208
1209    /// An `item.started` has no outcome yet, and must not invent one.
1210    #[cfg(feature = "json")]
1211    #[test]
1212    fn command_execution_tolerates_a_command_still_running() {
1213        let event: JsonLineEvent = serde_json::from_str(
1214            r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"git diff"}}"#,
1215        )
1216        .unwrap();
1217
1218        let command = event.command_execution().unwrap();
1219        assert_eq!(command.command.as_deref(), Some("git diff"));
1220        assert_eq!(command.exit_code, None);
1221        assert_eq!(command.status, None);
1222    }
1223
1224    #[cfg(feature = "json")]
1225    #[test]
1226    fn command_execution_is_none_for_other_items() {
1227        let event: JsonLineEvent = serde_json::from_str(
1228            r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"hi"}}"#,
1229        )
1230        .unwrap();
1231        assert!(event.command_execution().is_none());
1232    }
1233}