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    /// The text of the final agent message: the last completed
602    /// `agent_message` item after the last `turn.started`.
603    ///
604    /// Unlike [`result`](Self::result), which concatenates every agent
605    /// message, this is the one a `--output-schema` run answers with.
606    #[must_use]
607    pub fn final_message(&self) -> Option<String> {
608        crate::structured::final_message(&self.events)
609    }
610
611    /// Decode the final agent message of a `--output-schema` run into `T`.
612    ///
613    /// A failed turn is
614    /// [`StructuredOutputError::TurnFailed`](crate::structured::StructuredOutputError::TurnFailed)
615    /// even when it produced a message first. See [`crate::structured`] for
616    /// the full rules. This never runs the CLI.
617    pub fn decode_structured<T: serde::de::DeserializeOwned>(
618        &self,
619    ) -> std::result::Result<T, crate::structured::StructuredOutputError> {
620        crate::structured::decode(&self.events)
621    }
622}
623
624/// A shell command the model ran, from a `command_execution` item.
625///
626/// Every field is optional: an `item.started` carries the command with no
627/// outcome yet, and the CLI has added fields to this item before.
628#[cfg(feature = "json")]
629#[derive(Debug, Clone, Default, PartialEq, Eq)]
630#[non_exhaustive]
631pub struct CommandExecution {
632    /// The command line, as the CLI recorded it.
633    pub command: Option<String>,
634    /// Reported status, `completed` being the observed value.
635    pub status: Option<String>,
636    /// Exit code, once the command has finished.
637    pub exit_code: Option<i32>,
638    /// Combined stdout and stderr, when the CLI included it.
639    pub aggregated_output: Option<String>,
640}
641
642/// Token counts reported on a completed turn.
643///
644/// `codex-cli` 0.145.0 reports token usage and no monetary cost. Converting
645/// tokens to dollars needs a per-model price table the CLI does not provide,
646/// so this crate does not attempt it: a hardcoded table would go stale
647/// silently, which is the same class of bug as #73.
648///
649/// Every field is optional, and absence is normal rather than exceptional:
650/// observed runs carry five of the six and never `total_tokens`, which is why
651/// [`TokenUsage::total`] falls back to input plus output.
652#[cfg(feature = "json")]
653#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
654pub struct TokenUsage {
655    /// Input tokens for the turn.
656    pub input_tokens: Option<u64>,
657    /// Input tokens served from cache.
658    pub cached_input_tokens: Option<u64>,
659    /// Input tokens written to cache.
660    pub cache_write_input_tokens: Option<u64>,
661    /// Output tokens for the turn.
662    pub output_tokens: Option<u64>,
663    /// Output tokens spent on reasoning.
664    pub reasoning_output_tokens: Option<u64>,
665    /// Total tokens, if the CLI ever reports one. Observed runs do not.
666    pub total_tokens: Option<u64>,
667}
668
669#[cfg(feature = "json")]
670impl TokenUsage {
671    fn from_json(value: &serde_json::Value) -> Self {
672        let field = |name: &str| value.get(name).and_then(serde_json::Value::as_u64);
673        Self {
674            input_tokens: field("input_tokens"),
675            cached_input_tokens: field("cached_input_tokens"),
676            cache_write_input_tokens: field("cache_write_input_tokens"),
677            output_tokens: field("output_tokens"),
678            reasoning_output_tokens: field("reasoning_output_tokens"),
679            total_tokens: field("total_tokens"),
680        }
681    }
682
683    /// Best available total for the turn.
684    ///
685    /// Prefers the CLI's own `total_tokens`, falls back to input plus output
686    /// when it is absent, and returns `None` when neither is reported, so a
687    /// missing total is never silently counted as zero.
688    #[must_use]
689    pub fn total(&self) -> Option<u64> {
690        if let Some(total) = self.total_tokens {
691            return Some(total);
692        }
693        match (self.input_tokens, self.output_tokens) {
694            (None, None) => None,
695            (input, output) => Some(input.unwrap_or(0) + output.unwrap_or(0)),
696        }
697    }
698}
699
700/// Parsed semantic version of the Codex CLI (`major.minor.patch`).
701///
702/// Supports comparison and ordering for version-gating logic.
703#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
704pub struct CliVersion {
705    pub major: u32,
706    pub minor: u32,
707    pub patch: u32,
708}
709
710impl CliVersion {
711    #[must_use]
712    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
713        Self {
714            major,
715            minor,
716            patch,
717        }
718    }
719
720    pub fn parse_version_output(output: &str) -> Result<Self, VersionParseError> {
721        output
722            .split_whitespace()
723            .find_map(|token| token.parse().ok())
724            .ok_or_else(|| VersionParseError(output.trim().to_string()))
725    }
726
727    #[must_use]
728    pub fn satisfies_minimum(&self, minimum: &CliVersion) -> bool {
729        self >= minimum
730    }
731
732    /// Classify this version against a tested-against range.
733    ///
734    /// ```
735    /// use codex_wrapper::{CliVersion, CliVersionStatus};
736    ///
737    /// let min = CliVersion::new(0, 145, 0);
738    /// let max = CliVersion::new(0, 146, 0);
739    ///
740    /// assert!(CliVersion::new(0, 145, 3).status_within(&min, &max).is_tested());
741    /// assert!(!CliVersion::new(0, 200, 0).status_within(&min, &max).is_tested());
742    /// ```
743    #[must_use]
744    pub fn status_within(&self, min: &CliVersion, max: &CliVersion) -> CliVersionStatus {
745        if self < min {
746            CliVersionStatus::OlderThanMinimum {
747                found: *self,
748                minimum: *min,
749            }
750        } else if self > max {
751            CliVersionStatus::NewerUntested {
752                found: *self,
753                tested_max: *max,
754            }
755        } else {
756            CliVersionStatus::Tested
757        }
758    }
759}
760
761/// Classification of an installed CLI version against a tested range.
762///
763/// Returned by [`CliVersion::status_within`] and
764/// [`Codex::cli_version_status`](crate::Codex::cli_version_status). Mirrors
765/// `claude-wrapper`'s enum of the same name so a downstream abstraction can
766/// treat both wrappers uniformly.
767///
768/// There is deliberately no `Unparseable` variant: unparseable output is an
769/// error from [`Codex::cli_version`](crate::Codex::cli_version), not a status,
770/// and modeling it twice would fork this shape away from the sibling crate.
771#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
772#[serde(tag = "status", rename_all = "snake_case")]
773pub enum CliVersionStatus {
774    /// Within the tested-against range.
775    Tested,
776    /// Newer than the highest tested version.
777    ///
778    /// The wrapper should still generally work; semantics may have drifted.
779    NewerUntested {
780        /// The installed CLI version.
781        found: CliVersion,
782        /// Highest version this wrapper is tested against.
783        tested_max: CliVersion,
784    },
785    /// Older than the lowest tested version.
786    ///
787    /// Incorrect behavior is likely rather than merely possible: the arguments
788    /// this wrapper emits target the newer CLI, and older releases reject some
789    /// of them outright.
790    OlderThanMinimum {
791        /// The installed CLI version.
792        found: CliVersion,
793        /// Lowest version this wrapper is tested against.
794        minimum: CliVersion,
795    },
796}
797
798impl CliVersionStatus {
799    /// True only for [`Tested`](Self::Tested).
800    ///
801    /// For callers branching on "should I run?" without matching every
802    /// variant.
803    #[must_use]
804    pub fn is_tested(self) -> bool {
805        matches!(self, Self::Tested)
806    }
807}
808
809impl PartialOrd for CliVersion {
810    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
811        Some(self.cmp(other))
812    }
813}
814
815impl Ord for CliVersion {
816    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
817        self.major
818            .cmp(&other.major)
819            .then(self.minor.cmp(&other.minor))
820            .then(self.patch.cmp(&other.patch))
821    }
822}
823
824impl fmt::Display for CliVersion {
825    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
827    }
828}
829
830impl FromStr for CliVersion {
831    type Err = VersionParseError;
832
833    fn from_str(s: &str) -> Result<Self, Self::Err> {
834        let parts: Vec<&str> = s.split('.').collect();
835        if parts.len() != 3 {
836            return Err(VersionParseError(s.to_string()));
837        }
838
839        Ok(Self {
840            major: parts[0]
841                .parse()
842                .map_err(|_| VersionParseError(s.to_string()))?,
843            minor: parts[1]
844                .parse()
845                .map_err(|_| VersionParseError(s.to_string()))?,
846            patch: parts[2]
847                .parse()
848                .map_err(|_| VersionParseError(s.to_string()))?,
849        })
850    }
851}
852
853#[derive(Debug, Clone, thiserror::Error)]
854#[error("invalid version string: {0:?}")]
855pub struct VersionParseError(pub String);
856
857#[cfg(test)]
858mod tests {
859    use super::*;
860
861    #[test]
862    fn parses_codex_version_output() {
863        let version = CliVersion::parse_version_output("codex-cli 0.145.0").unwrap();
864        assert_eq!(version, CliVersion::new(0, 145, 0));
865    }
866
867    #[test]
868    fn parses_plain_version_output() {
869        let version = CliVersion::parse_version_output("0.145.0").unwrap();
870        assert_eq!(version, CliVersion::new(0, 145, 0));
871    }
872
873    #[cfg(feature = "json")]
874    #[test]
875    fn json_line_event_session_and_thread_id() {
876        let event: JsonLineEvent = serde_json::from_str(
877            r#"{"type":"message.created","session_id":"sess_abc","thread_id":"thread_123"}"#,
878        )
879        .unwrap();
880        assert_eq!(event.session_id(), Some("sess_abc"));
881        assert_eq!(event.thread_id(), Some("thread_123"));
882    }
883
884    #[cfg(feature = "json")]
885    #[test]
886    fn json_line_event_turn_terminal_types() {
887        let completed: JsonLineEvent =
888            serde_json::from_str(r#"{"type":"turn.completed"}"#).unwrap();
889        assert!(completed.is_turn_completed());
890        assert!(!completed.is_turn_failed());
891
892        let failed: JsonLineEvent = serde_json::from_str(r#"{"type":"turn.failed"}"#).unwrap();
893        assert!(failed.is_turn_failed());
894        assert!(!failed.is_turn_completed());
895
896        // The pre-#73 parser matched this. The CLI has never emitted it.
897        let bogus: JsonLineEvent = serde_json::from_str(r#"{"type":"completed"}"#).unwrap();
898        assert!(!bogus.is_turn_completed());
899    }
900
901    /// Transcribed from a paid `codex-cli` 0.145.0 run with a one-unit native
902    /// rollout budget. The CLI exposes the limit decision but no usage object.
903    #[cfg(feature = "json")]
904    #[test]
905    fn classifies_captured_rollout_budget_terminal_without_inventing_usage() {
906        let failed: JsonLineEvent = serde_json::from_str(
907            r#"{"type":"turn.failed","error":{"message":"shared rollout token budget exhausted"}}"#,
908        )
909        .unwrap();
910
911        assert_eq!(
912            failed.turn_failure_kind(),
913            Some(TurnFailureKind::RolloutBudgetExhausted)
914        );
915        assert_eq!(failed.usage(), None);
916
917        let other: JsonLineEvent = serde_json::from_str(
918            r#"{"type":"turn.failed","error":{"message":"tool policy rejected"}}"#,
919        )
920        .unwrap();
921        assert_eq!(other.turn_failure_kind(), Some(TurnFailureKind::Other));
922
923        let missing_message: JsonLineEvent =
924            serde_json::from_str(r#"{"type":"turn.failed"}"#).unwrap();
925        assert_eq!(
926            missing_message.turn_failure_kind(),
927            Some(TurnFailureKind::Other)
928        );
929
930        let nonterminal: JsonLineEvent =
931            serde_json::from_str(r#"{"type":"turn.started"}"#).unwrap();
932        assert_eq!(nonterminal.turn_failure_kind(), None);
933    }
934
935    /// Both lines are transcriptions of captured `codex-cli` 0.149.0 runs:
936    /// an output schema whose property omits `type`, and a root-level
937    /// `anyOf`. The human message differs between them; the code does not.
938    #[cfg(feature = "json")]
939    #[test]
940    fn classifies_an_api_request_rejection() {
941        let missing_type: JsonLineEvent = serde_json::from_str(
942            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}"}}"#,
943        )
944        .unwrap();
945        assert_eq!(
946            missing_type.turn_failure_kind(),
947            Some(TurnFailureKind::ApiRequestRejected)
948        );
949        let error = missing_type.turn_failure_api_error().unwrap();
950        assert_eq!(error.code.as_deref(), Some("invalid_json_schema"));
951        assert_eq!(error.error_type.as_deref(), Some("invalid_request_error"));
952        assert_eq!(error.status, Some(400));
953        assert!(error.rejected_request());
954
955        let root_any_of: JsonLineEvent = serde_json::from_str(
956            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}"}}"#,
957        )
958        .unwrap();
959        assert_eq!(
960            root_any_of.turn_failure_kind(),
961            Some(TurnFailureKind::ApiRequestRejected)
962        );
963        assert_eq!(
964            root_any_of
965                .turn_failure_api_error()
966                .and_then(|error| error.code),
967            Some("invalid_json_schema".to_string())
968        );
969    }
970
971    /// A local failure carries prose, not the API's JSON document, and must
972    /// not be mistaken for a request rejection.
973    #[cfg(feature = "json")]
974    #[test]
975    fn a_prose_failure_message_carries_no_api_error() {
976        let budget: JsonLineEvent = serde_json::from_str(
977            r#"{"type":"turn.failed","error":{"message":"shared rollout token budget exhausted"}}"#,
978        )
979        .unwrap();
980        assert_eq!(budget.turn_failure_api_error(), None);
981        assert_eq!(
982            budget.turn_failure_kind(),
983            Some(TurnFailureKind::RolloutBudgetExhausted)
984        );
985
986        let other: JsonLineEvent = serde_json::from_str(
987            r#"{"type":"turn.failed","error":{"message":"tool policy rejected"}}"#,
988        )
989        .unwrap();
990        assert_eq!(other.turn_failure_api_error(), None);
991        assert_eq!(other.turn_failure_kind(), Some(TurnFailureKind::Other));
992    }
993
994    /// A server-side or throttling failure is not a rejected request: the
995    /// turn may have done work, so a caller must not treat it as safe to
996    /// replay after editing the request.
997    #[cfg(feature = "json")]
998    #[test]
999    fn server_and_throttling_failures_are_not_request_rejections() {
1000        for (status, error_type) in [(500u64, "server_error"), (429, "rate_limit_error")] {
1001            let message = format!(
1002                r#"{{"type":"error","error":{{"type":"{error_type}","code":"x"}},"status":{status}}}"#
1003            );
1004            let event = JsonLineEvent {
1005                event_type: "turn.failed".to_string(),
1006                extra: HashMap::from([(
1007                    "error".to_string(),
1008                    serde_json::json!({ "message": message }),
1009                )]),
1010            };
1011            assert!(!event.turn_failure_api_error().unwrap().rejected_request());
1012            assert_eq!(event.turn_failure_kind(), Some(TurnFailureKind::Other));
1013        }
1014    }
1015
1016    #[cfg(feature = "json")]
1017    #[test]
1018    fn json_line_event_usage() {
1019        let event: JsonLineEvent = serde_json::from_str(
1020            r#"{"type":"turn.completed","usage":{"input_tokens":120,"output_tokens":45,"total_tokens":165}}"#,
1021        )
1022        .unwrap();
1023        let usage = event.usage().unwrap();
1024        assert_eq!(usage.input_tokens, Some(120));
1025        assert_eq!(usage.output_tokens, Some(45));
1026        assert_eq!(usage.total_tokens, Some(165));
1027        // Absent from the observed payload, so absent here rather than zero.
1028        assert_eq!(usage.cache_write_input_tokens, None);
1029        assert_eq!(usage.total(), Some(165));
1030    }
1031
1032    #[cfg(feature = "json")]
1033    #[test]
1034    fn token_usage_total_falls_back_to_input_plus_output() {
1035        let usage = TokenUsage {
1036            input_tokens: Some(10),
1037            output_tokens: Some(5),
1038            ..TokenUsage::default()
1039        };
1040        assert_eq!(usage.total(), Some(15));
1041    }
1042
1043    /// A missing total must not read as zero, which would silently understate
1044    /// a session's usage.
1045    #[cfg(feature = "json")]
1046    #[test]
1047    fn token_usage_total_is_none_when_nothing_reported() {
1048        assert_eq!(TokenUsage::default().total(), None);
1049    }
1050
1051    /// The shape a real run emits: `type` on the item, text in `text`.
1052    #[cfg(feature = "json")]
1053    #[test]
1054    fn agent_message_text_from_item_completed() {
1055        let event: JsonLineEvent = serde_json::from_str(
1056            r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"hello"}}"#,
1057        )
1058        .unwrap();
1059        assert_eq!(event.agent_message_text().as_deref(), Some("hello"));
1060    }
1061
1062    /// `item_type` and content blocks are not shapes the CLI has been seen to
1063    /// emit. The accessor still tolerates them, because the cost of being
1064    /// wrong here is a silently empty result rather than a loud failure, which
1065    /// is how #73 stayed hidden. These cases keep that tolerance covered.
1066    #[cfg(feature = "json")]
1067    #[test]
1068    fn agent_message_text_tolerates_layout_variants() {
1069        let item_type_key: JsonLineEvent = serde_json::from_str(
1070            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"a"}}"#,
1071        )
1072        .unwrap();
1073        assert_eq!(item_type_key.agent_message_text().as_deref(), Some("a"));
1074
1075        let content_blocks: JsonLineEvent = serde_json::from_str(
1076            r#"{"type":"item.completed","item":{"item_type":"agent_message","content":[{"text":"b"},{"text":"c"}]}}"#,
1077        )
1078        .unwrap();
1079        assert_eq!(content_blocks.agent_message_text().as_deref(), Some("bc"));
1080    }
1081
1082    #[cfg(feature = "json")]
1083    #[test]
1084    fn agent_message_text_ignores_other_items_and_events() {
1085        // The item type a review's diff-reading steps arrive as.
1086        let other_item: JsonLineEvent = serde_json::from_str(
1087            r#"{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"git diff","exit_code":0}}"#,
1088        )
1089        .unwrap();
1090        assert_eq!(other_item.agent_message_text(), None);
1091
1092        let other_event: JsonLineEvent = serde_json::from_str(
1093            r#"{"type":"item.started","item":{"id":"item_0","type":"agent_message","text":"x"}}"#,
1094        )
1095        .unwrap();
1096        assert_eq!(other_event.agent_message_text(), None);
1097    }
1098
1099    #[cfg(feature = "json")]
1100    #[test]
1101    fn json_line_event_role() {
1102        let event: JsonLineEvent =
1103            serde_json::from_str(r#"{"type":"message.created","role":"assistant"}"#).unwrap();
1104        assert_eq!(event.role(), Some("assistant"));
1105    }
1106
1107    #[cfg(feature = "json")]
1108    #[test]
1109    fn json_line_event_content_text() {
1110        let event: JsonLineEvent = serde_json::from_str(
1111            r#"{"type":"message.delta","content":[{"type":"text","text":"Hello "},{"type":"text","text":"world"}]}"#,
1112        )
1113        .unwrap();
1114        assert_eq!(event.content_text(), Some("Hello world".to_string()));
1115    }
1116
1117    #[cfg(feature = "json")]
1118    #[test]
1119    fn json_line_event_content_text_skips_non_text_blocks() {
1120        let event: JsonLineEvent = serde_json::from_str(
1121            r#"{"type":"message.delta","content":[{"type":"image","url":"x"},{"type":"text","text":"only this"}]}"#,
1122        )
1123        .unwrap();
1124        assert_eq!(event.content_text(), Some("only this".to_string()));
1125    }
1126
1127    #[cfg(feature = "json")]
1128    #[test]
1129    fn json_line_event_content_text_none_when_empty() {
1130        let event: JsonLineEvent =
1131            serde_json::from_str(r#"{"type":"message.delta","content":[]}"#).unwrap();
1132        assert_eq!(event.content_text(), None);
1133    }
1134
1135    #[cfg(feature = "json")]
1136    #[test]
1137    fn json_line_event_content_text_none_when_missing() {
1138        let event: JsonLineEvent = serde_json::from_str(r#"{"type":"message.delta"}"#).unwrap();
1139        assert_eq!(event.content_text(), None);
1140    }
1141
1142    #[cfg(feature = "json")]
1143    #[test]
1144    fn query_result_from_events() {
1145        let events: Vec<JsonLineEvent> = [
1146            r#"{"type":"thread.started","thread_id":"thread_1"}"#,
1147            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"the answer"}}"#,
1148            r#"{"type":"turn.completed","usage":{"input_tokens":7,"output_tokens":3,"total_tokens":10}}"#,
1149        ]
1150        .iter()
1151        .map(|l| serde_json::from_str(l).unwrap())
1152        .collect();
1153
1154        let result = QueryResult::from_events(events);
1155        assert_eq!(result.result, "the answer");
1156        assert_eq!(result.thread_id.as_deref(), Some("thread_1"));
1157        assert_eq!(result.usage.unwrap().total(), Some(10));
1158        assert_eq!(result.events.len(), 3);
1159    }
1160
1161    #[cfg(feature = "json")]
1162    #[test]
1163    fn query_result_concatenates_multiple_agent_messages() {
1164        let events: Vec<JsonLineEvent> = [
1165            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"one "}}"#,
1166            r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"two"}}"#,
1167            r#"{"type":"turn.completed","usage":{"total_tokens":4}}"#,
1168        ]
1169        .iter()
1170        .map(|l| serde_json::from_str(l).unwrap())
1171        .collect();
1172
1173        assert_eq!(QueryResult::from_events(events).result, "one two");
1174    }
1175
1176    /// A failed turn has no agent message and no usage. Both must come back
1177    /// empty rather than fabricated.
1178    #[cfg(feature = "json")]
1179    #[test]
1180    fn query_result_from_a_failed_turn() {
1181        let events: Vec<JsonLineEvent> = [
1182            r#"{"type":"thread.started","thread_id":"thread_2"}"#,
1183            r#"{"type":"turn.failed","error":{"message":"usage limit"}}"#,
1184        ]
1185        .iter()
1186        .map(|l| serde_json::from_str(l).unwrap())
1187        .collect();
1188
1189        let result = QueryResult::from_events(events);
1190        assert_eq!(result.result, "");
1191        assert_eq!(result.usage, None);
1192        assert_eq!(result.thread_id.as_deref(), Some("thread_2"));
1193    }
1194
1195    /// Both values transcribed from captured runs.
1196    #[cfg(feature = "json")]
1197    #[test]
1198    fn item_type_reads_the_discriminator() {
1199        let message: JsonLineEvent = serde_json::from_str(
1200            r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"hi"}}"#,
1201        )
1202        .unwrap();
1203        assert_eq!(message.item_type(), Some("agent_message"));
1204
1205        let command: JsonLineEvent = serde_json::from_str(
1206            r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"git diff"}}"#,
1207        )
1208        .unwrap();
1209        assert_eq!(command.item_type(), Some("command_execution"));
1210
1211        let turn: JsonLineEvent = serde_json::from_str(r#"{"type":"turn.completed"}"#).unwrap();
1212        assert_eq!(turn.item_type(), None);
1213    }
1214
1215    /// Transcribed from a captured `codex exec review` run, where the reviewer
1216    /// reads the diff before commenting.
1217    #[cfg(feature = "json")]
1218    #[test]
1219    fn command_execution_reads_a_finished_command() {
1220        let event: JsonLineEvent = serde_json::from_str(
1221            r#"{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"git diff","aggregated_output":"","exit_code":0,"status":"completed"}}"#,
1222        )
1223        .unwrap();
1224
1225        let command = event.command_execution().unwrap();
1226        assert_eq!(command.command.as_deref(), Some("git diff"));
1227        assert_eq!(command.exit_code, Some(0));
1228        assert_eq!(command.status.as_deref(), Some("completed"));
1229    }
1230
1231    /// An `item.started` has no outcome yet, and must not invent one.
1232    #[cfg(feature = "json")]
1233    #[test]
1234    fn command_execution_tolerates_a_command_still_running() {
1235        let event: JsonLineEvent = serde_json::from_str(
1236            r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"git diff"}}"#,
1237        )
1238        .unwrap();
1239
1240        let command = event.command_execution().unwrap();
1241        assert_eq!(command.command.as_deref(), Some("git diff"));
1242        assert_eq!(command.exit_code, None);
1243        assert_eq!(command.status, None);
1244    }
1245
1246    #[cfg(feature = "json")]
1247    #[test]
1248    fn command_execution_is_none_for_other_items() {
1249        let event: JsonLineEvent = serde_json::from_str(
1250            r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"hi"}}"#,
1251        )
1252        .unwrap();
1253        assert!(event.command_execution().is_none());
1254    }
1255}