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