Skip to main content

mockql_core/llm_provider/cli/
codex.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::graphql::GraphQLResponse;
16use crate::graphql::mock_response_prompt::MockResponsePrompt;
17use crate::llm_provider::ProviderError;
18use std::path::Path;
19use std::process::Stdio;
20use std::time::Duration;
21use tempfile::TempDir;
22use tokio::fs;
23use tokio::io::AsyncWriteExt;
24use tokio::process::Command;
25
26/// OpenAI Codex CLI provider.
27#[derive(Debug, Clone)]
28pub struct CodexCliProvider {
29  /// Model identifier forwarded to the CLI.
30  pub model: String,
31}
32
33impl CodexCliProvider {
34  const BINARY: &str = "codex";
35
36  pub(crate) async fn run(
37    &self,
38    prompt: &MockResponsePrompt,
39    timeout_duration: Duration,
40  ) -> Result<GraphQLResponse, ProviderError> {
41    let prompt_markdown = prompt.to_markdown()?;
42    let temp_dir = TempDir::new().map_err(|error| ProviderError::Request(error.to_string()))?;
43    let output_path = temp_dir.path().join("last-message.json");
44
45    let mut command = Command::new(Self::BINARY);
46    command.args(self.get_args(&output_path));
47    command
48      .stdin(Stdio::piped())
49      .stdout(Stdio::piped())
50      .stderr(Stdio::piped())
51      .kill_on_drop(true);
52
53    let mut child = command
54      .spawn()
55      .map_err(|error| ProviderError::Request(format!("failed to execute Codex CLI: {error}")))?;
56
57    {
58      let mut stdin = child
59        .stdin
60        .take()
61        .ok_or_else(|| ProviderError::Request("Codex CLI stdin was not piped".to_string()))?;
62
63      stdin
64        .write_all(prompt_markdown.as_bytes())
65        .await
66        .map_err(|error| ProviderError::Request(format!("Codex CLI failed while writing prompt: {error}")))?;
67
68      stdin
69        .shutdown()
70        .await
71        .map_err(|error| ProviderError::Request(format!("Codex CLI failed while closing stdin: {error}")))?;
72    }
73
74    let output = super::exec_cli(timeout_duration, child).await?;
75    let stderr = String::from_utf8_lossy(&output.stderr);
76
77    let output_string = fs::read_to_string(&output_path).await.map_err(|error| {
78      ProviderError::Request(if stderr.trim().is_empty() {
79        format!("Codex CLI did not write last-message output: {error}")
80      } else {
81        format!(
82          "Codex CLI did not write last-message output: {error}. stderr: {}",
83          stderr.trim()
84        )
85      })
86    })?;
87
88    Self::parse_response(&output_string)
89  }
90
91  fn get_args(&self, output_path: &Path) -> Vec<String> {
92    let output_path = output_path.display().to_string();
93    let args = vec![
94      "exec",
95      "--skip-git-repo-check",
96      "--yolo",
97      "-m",
98      &self.model,
99      "--config",
100      r##"model_reasoning_effort="low""##,
101      "--json",
102      "--output-last-message",
103      &output_path,
104      "-",
105    ];
106    args.into_iter().map(String::from).collect()
107  }
108
109  fn parse_response(file_text: &str) -> Result<GraphQLResponse, ProviderError> {
110    let trimmed = file_text.trim();
111    if trimmed.is_empty() {
112      return Err(ProviderError::Request(
113        "Codex CLI returned an empty last-message output".to_string(),
114      ));
115    }
116    crate::llm_provider::parse_llm_json(trimmed)
117  }
118}
119
120#[cfg(test)]
121mod tests {
122  use super::*;
123
124  #[test]
125  fn builds_script_mode_args() {
126    let provider = CodexCliProvider {
127      model: "gpt-5.4-mini".into(),
128    };
129    let args = provider.get_args(Path::new("mock-response.codex.json"));
130    assert_eq!(
131      args,
132      vec![
133        "exec",
134        "--skip-git-repo-check",
135        "--yolo",
136        "-m",
137        "gpt-5.4-mini",
138        "--config",
139        r##"model_reasoning_effort="low""##,
140        "--json",
141        "--output-last-message",
142        "mock-response.codex.json",
143        "-",
144      ]
145    );
146  }
147
148  #[test]
149  fn parses_fixture_last_message() {
150    let response =
151      CodexCliProvider::parse_response(include_str!("mock-response.codex.json")).expect("fixture should parse");
152
153    let data = response.data.expect("response should contain data");
154    assert_eq!(
155      data["loyaltyRewards"]["additionalInformation"][0]["title"],
156      "Platinum member benefits"
157    );
158  }
159}