Skip to main content

agent_commander/tools/
codex.rs

1//! Codex CLI tool configuration
2//! Based on hive-mind's codex.lib.mjs implementation
3
4use super::usage::{self, count};
5use crate::streaming::parse_ndjson;
6use crate::tools::shell::{build_command_head, escape_arg, escape_single_quotes};
7use serde_json::Value;
8use std::collections::HashMap;
9
10/// Get the Codex model map
11pub fn get_model_map() -> HashMap<&'static str, &'static str> {
12    let mut map = HashMap::new();
13    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
14    map.insert("gpt5-codex", "gpt-5-codex");
15    map.insert("o3", "o3");
16    map.insert("claude", "claude-3-5-sonnet");
17    map.insert("sonnet", "claude-3-5-sonnet");
18    map.insert("opus", "claude-3-opus");
19    map.insert("formal-ai", "formal-ai");
20    map.insert("formalai/formal-ai", "formal-ai");
21    map.insert("gpt-6.1-sol", "gpt-6.1-sol");
22    map.insert("gpt-6-sol", "gpt-6-sol");
23    map.insert("gpt-6-luna", "gpt-6-luna");
24    map.insert("gpt-reserve", "gpt-reserve");
25    map.insert("gpt-6-astra", "gpt-6-astra");
26    map.insert("gpt5", "gpt-5");
27    map.insert("gpt-5", "gpt-5");
28    map.insert("gpt-5.5", "gpt-5.5");
29    map.insert("gpt-5.5-mini", "gpt-5.5-mini");
30    map.insert("gpt-5.5-nano", "gpt-5.5-nano");
31    map.insert("gpt-5.6-sol", "gpt-5.6-sol");
32    map.insert("gpt-5.6-terra", "gpt-5.6-terra");
33    map.insert("gpt-5.6-luna", "gpt-5.6-luna");
34    map.insert("gpt-5.6-cyber", "gpt-5.6-cyber");
35    map.insert("gpt-5.4", "gpt-5.4");
36    map.insert("gpt-5.4-mini", "gpt-5.4-mini");
37    map.insert("gpt-5.4-nano", "gpt-5.4-nano");
38    map.insert("gpt-5.2", "gpt-5.2");
39    map.insert("gpt-5.2-codex", "gpt-5.2-codex");
40    map.insert("gpt-5.3-codex", "gpt-5.3-codex");
41    map.insert("gpt-5.3-codex-spark", "gpt-5.3-codex-spark");
42    map.insert("gpt-5.1-codex-max", "gpt-5.1-codex-max");
43    map.insert("gpt-daybreak-blue-latest", "gpt-daybreak-blue-latest");
44    map.insert("gpt-daybreak-red-latest", "gpt-daybreak-red-latest");
45    map.insert("openai.gpt-5.5", "openai.gpt-5.5");
46    map.insert("openai.gpt-5.4", "openai.gpt-5.4");
47    map.insert("openai.gpt-5.6-sol", "openai.gpt-5.6-sol");
48    map.insert("openai.gpt-5.6-terra", "openai.gpt-5.6-terra");
49    map.insert("openai.gpt-5.6-luna", "openai.gpt-5.6-luna");
50    map.insert("codex-auto-review", "codex-auto-review");
51    map.insert("o3-mini", "o3-mini");
52    map.insert("gpt4", "gpt-4");
53    map.insert("gpt-4", "gpt-4");
54    map.insert("gpt4o", "gpt-4o");
55    map.insert("gpt-4o", "gpt-4o");
56    map.insert("sol", "gpt-5.6-sol");
57    map.insert("terra", "gpt-5.6-terra");
58    map.insert("luna", "gpt-5.6-luna");
59    map.insert("openai/formal-ai", "openai/formal-ai");
60    map.insert("openai.formal-ai", "openai.formal-ai");
61    map.insert("openai/gpt-6.1-sol", "openai/gpt-6.1-sol");
62    map.insert("openai.gpt-6.1-sol", "openai.gpt-6.1-sol");
63    map.insert("openai/gpt-6-sol", "openai/gpt-6-sol");
64    map.insert("openai.gpt-6-sol", "openai.gpt-6-sol");
65    map.insert("openai/gpt-6-luna", "openai/gpt-6-luna");
66    map.insert("openai.gpt-6-luna", "openai.gpt-6-luna");
67    map.insert("openai/gpt-reserve", "openai/gpt-reserve");
68    map.insert("openai.gpt-reserve", "openai.gpt-reserve");
69    map.insert("openai/gpt-6-astra", "openai/gpt-6-astra");
70    map.insert("openai.gpt-6-astra", "openai.gpt-6-astra");
71    map.insert("openai/gpt-5", "openai/gpt-5");
72    map.insert("openai.gpt-5", "openai.gpt-5");
73    map.insert("openai/gpt-5.5", "openai/gpt-5.5");
74    map.insert("openai/gpt-5.5-mini", "openai/gpt-5.5-mini");
75    map.insert("openai.gpt-5.5-mini", "openai.gpt-5.5-mini");
76    map.insert("openai/gpt-5.5-nano", "openai/gpt-5.5-nano");
77    map.insert("openai.gpt-5.5-nano", "openai.gpt-5.5-nano");
78    map.insert("openai/gpt-5.6-sol", "openai/gpt-5.6-sol");
79    map.insert("openai/gpt-5.6-terra", "openai/gpt-5.6-terra");
80    map.insert("openai/gpt-5.6-luna", "openai/gpt-5.6-luna");
81    map.insert("openai/gpt-5.6-cyber", "openai/gpt-5.6-cyber");
82    map.insert("openai.gpt-5.6-cyber", "openai.gpt-5.6-cyber");
83    map.insert("openai/gpt-5.4", "openai/gpt-5.4");
84    map.insert("openai/gpt-5.4-mini", "openai/gpt-5.4-mini");
85    map.insert("openai.gpt-5.4-mini", "openai.gpt-5.4-mini");
86    map.insert("openai/gpt-5.4-nano", "openai/gpt-5.4-nano");
87    map.insert("openai.gpt-5.4-nano", "openai.gpt-5.4-nano");
88    map.insert("openai/gpt-5.2", "openai/gpt-5.2");
89    map.insert("openai.gpt-5.2", "openai.gpt-5.2");
90    map.insert("openai/gpt-5.2-codex", "openai/gpt-5.2-codex");
91    map.insert("openai.gpt-5.2-codex", "openai.gpt-5.2-codex");
92    map.insert("openai/gpt-5.3-codex", "openai/gpt-5.3-codex");
93    map.insert("openai.gpt-5.3-codex", "openai.gpt-5.3-codex");
94    map.insert("openai/gpt-5.3-codex-spark", "openai/gpt-5.3-codex-spark");
95    map.insert("openai.gpt-5.3-codex-spark", "openai.gpt-5.3-codex-spark");
96    map.insert("openai/gpt-5.1-codex-max", "openai/gpt-5.1-codex-max");
97    map.insert("openai.gpt-5.1-codex-max", "openai.gpt-5.1-codex-max");
98    map.insert(
99        "openai/gpt-daybreak-blue-latest",
100        "openai/gpt-daybreak-blue-latest",
101    );
102    map.insert(
103        "openai.gpt-daybreak-blue-latest",
104        "openai.gpt-daybreak-blue-latest",
105    );
106    map.insert(
107        "openai/gpt-daybreak-red-latest",
108        "openai/gpt-daybreak-red-latest",
109    );
110    map.insert(
111        "openai.gpt-daybreak-red-latest",
112        "openai.gpt-daybreak-red-latest",
113    );
114    map.insert("openai/codex-auto-review", "openai/codex-auto-review");
115    map.insert("openai.codex-auto-review", "openai.codex-auto-review");
116    map.insert("openai/o3-mini", "openai/o3-mini");
117    map.insert("openai.o3-mini", "openai.o3-mini");
118    map.insert("openai/gpt-4", "openai/gpt-4");
119    map.insert("openai.gpt-4", "openai.gpt-4");
120    map.insert("openai/gpt-4o", "openai/gpt-4o");
121    map.insert("openai.gpt-4o", "openai.gpt-4o");
122    map.insert("openai/sol", "openai/gpt-5.6-sol");
123    map.insert("openai.sol", "openai.gpt-5.6-sol");
124    map.insert("openai/terra", "openai/gpt-5.6-terra");
125    map.insert("openai.terra", "openai.gpt-5.6-terra");
126    map.insert("openai/luna", "openai/gpt-5.6-luna");
127    map.insert("openai.luna", "openai.gpt-5.6-luna");
128    map
129}
130
131/// Map model alias to full model ID
132///
133/// # Arguments
134/// * `model` - Model alias or full ID
135///
136/// # Returns
137/// Full model ID
138pub fn map_model_to_id(model: &str) -> String {
139    let model_map = get_model_map();
140    model_map
141        .get(model)
142        .map(|s| s.to_string())
143        .unwrap_or_else(|| model.to_string())
144}
145
146/// Codex command build options
147#[derive(Debug, Clone, Default)]
148pub struct CodexBuildOptions {
149    pub prompt: Option<String>,
150    pub prompt_file: Option<String>,
151    pub system_prompt: Option<String>,
152    pub model: Option<String>,
153    pub json: bool,
154    pub resume: Option<String>,
155    pub read_only: bool,
156    pub executable: Option<String>,
157    pub extra_env: Vec<(String, String)>,
158    pub extra_args: Vec<String>,
159    pub skip_default_safety_flags: bool,
160    pub sandbox_mode: Option<String>,
161    pub approval_mode: Option<String>,
162}
163
164/// Build command line arguments for Codex
165///
166/// # Arguments
167/// * `options` - Build options
168///
169/// # Returns
170/// Vector of CLI arguments
171pub fn build_args(options: &CodexBuildOptions) -> Vec<String> {
172    let mut args = vec!["exec".to_string()];
173
174    if let Some(ref resume) = options.resume {
175        args.push("resume".to_string());
176        args.push(resume.clone());
177    }
178
179    if let Some(ref model) = options.model {
180        let mapped_model = map_model_to_id(model);
181        args.push("--model".to_string());
182        args.push(mapped_model);
183    }
184
185    // Default to json=true like JavaScript version
186    if options.json {
187        args.push("--json".to_string());
188    }
189
190    // Codex-specific flags for autonomous execution
191    args.push("--skip-git-repo-check".to_string());
192    if options.read_only {
193        args.push("--sandbox".to_string());
194        args.push("read-only".to_string());
195    } else if let Some(ref sandbox_mode) = options.sandbox_mode {
196        args.push("--sandbox".to_string());
197        args.push(sandbox_mode.clone());
198    }
199
200    if !options.read_only
201        && options.sandbox_mode.is_none()
202        && options.approval_mode.is_none()
203        && !options.skip_default_safety_flags
204    {
205        args.push("--dangerously-bypass-approvals-and-sandbox".to_string());
206    }
207
208    args.extend(options.extra_args.clone());
209
210    args
211}
212
213/// Build complete command string for Codex
214/// Codex uses stdin for prompt input
215///
216/// # Arguments
217/// * `options` - Build options
218///
219/// # Returns
220/// Complete command string
221pub fn build_command(options: &CodexBuildOptions) -> String {
222    let args = build_args(options);
223    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
224
225    // Codex expects prompt via stdin, combine system and user prompts
226    let combined_prompt = match (&options.system_prompt, &options.prompt) {
227        (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
228        (Some(sys), None) => sys.clone(),
229        (None, Some(prompt)) => prompt.clone(),
230        (None, None) => String::new(),
231    };
232
233    // Build command with stdin piping
234    let input_command = options.prompt_file.as_ref().map_or_else(
235        || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
236        |prompt_file| format!("cat {}", escape_arg(prompt_file)),
237    );
238    let executable = options.executable.as_deref().unwrap_or("codex");
239    let mut prefix_args = Vec::new();
240    if options.read_only {
241        prefix_args.push("--ask-for-approval".to_string());
242        prefix_args.push("never".to_string());
243    } else if let Some(ref approval_mode) = options.approval_mode {
244        prefix_args.push("--ask-for-approval".to_string());
245        prefix_args.push(approval_mode.clone());
246    }
247
248    format!(
249        "{} | {} {}",
250        input_command,
251        build_command_head(executable, &options.extra_env, &prefix_args),
252        args_str.join(" ")
253    )
254    .trim()
255    .to_string()
256}
257
258/// Parse JSON messages from Codex output
259/// Codex outputs NDJSON format
260///
261/// # Arguments
262/// * `output` - Raw output string
263///
264/// # Returns
265/// Vector of parsed JSON messages
266pub fn parse_output(output: &str) -> Vec<Value> {
267    parse_ndjson(output)
268}
269
270/// Extract session/thread ID from Codex output
271/// Codex uses thread_id instead of session_id
272///
273/// # Arguments
274/// * `output` - Raw output string
275///
276/// # Returns
277/// Session ID or None
278pub fn extract_session_id(output: &str) -> Option<String> {
279    let messages = parse_output(output);
280
281    for msg in messages {
282        if let Some(thread_id) = msg.get("thread_id").and_then(|v| v.as_str()) {
283            return Some(thread_id.to_string());
284        }
285        if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
286            return Some(session_id.to_string());
287        }
288    }
289
290    None
291}
292
293/// Usage statistics
294#[derive(Debug, Clone, Default, serde::Serialize)]
295#[serde(rename_all = "camelCase")]
296pub struct CodexUsage {
297    pub input_tokens: u64,
298    pub output_tokens: u64,
299    pub cache_read_tokens: u64,
300    pub cache_creation_tokens: u64,
301    pub reasoning_tokens: u64,
302}
303
304/// Extract usage statistics from Codex output
305///
306/// # Arguments
307/// * `output` - Raw output string
308///
309/// # Returns
310/// Usage statistics
311pub fn extract_usage(output: &str) -> CodexUsage {
312    let messages = parse_output(output);
313    let mut result = CodexUsage::default();
314    for record in usage::records("codex", &messages) {
315        result.input_tokens += count(record, usage::INPUT);
316        result.output_tokens += count(record, usage::OUTPUT);
317        result.cache_read_tokens += count(record, usage::CACHE_READ);
318        result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
319        result.reasoning_tokens += count(record, usage::REASONING);
320        result.input_tokens -= count(record, usage::INPUT).min(count(record, usage::CACHE_READ));
321    }
322    result
323}
324
325/// Codex tool configuration
326#[derive(Debug, Clone)]
327pub struct CodexTool {
328    pub name: &'static str,
329    pub display_name: &'static str,
330    pub executable: &'static str,
331    pub supports_json_output: bool,
332    pub supports_json_input: bool,
333    pub supports_system_prompt: bool,
334    pub supports_resume: bool,
335    pub supports_read_only: bool,
336    pub supports_ask: bool,
337    pub default_model: &'static str,
338}
339
340impl Default for CodexTool {
341    fn default() -> Self {
342        Self {
343            name: "codex",
344            display_name: "Codex CLI",
345            executable: "codex",
346            supports_json_output: true,
347            supports_json_input: false, // stdin carries plain prompt text
348            supports_system_prompt: false, // System prompt is combined with user prompt
349            supports_resume: true,
350            supports_read_only: true, // Supports --sandbox read-only
351            supports_ask: false, // Approval is coupled with the sandbox, not a relayable JSON stream
352            default_model: "gpt-6-sol",
353        }
354    }
355}
356
357// Tests are in rust/tests/codex_tests.rs