1use 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
16pub fn get_model_map() -> HashMap<&'static str, &'static str> {
18 let mut map = HashMap::new();
19 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
144pub 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#[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 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 pub launch: LaunchOptions,
175}
176
177pub fn build_args(options: &CodexBuildOptions) -> Vec<String> {
185 let mut args = vec!["exec".to_string()];
186
187 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 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 if options.json {
226 args.push("--json".to_string());
227 }
228
229 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
245pub 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 json_schema) = options.launch.json_schema {
260 args_str.push(format!(
261 "--output-schema <(printf '%s' {})",
262 escape_arg(&json_schema_arg(json_schema))
263 ));
264 }
265
266 let combined_prompt = match (&options.system_prompt, &options.prompt) {
268 (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
269 (Some(sys), None) => sys.clone(),
270 (None, Some(prompt)) => prompt.clone(),
271 (None, None) => String::new(),
272 };
273
274 let input_command = options.prompt_file.as_ref().map_or_else(
276 || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
277 |prompt_file| format!("cat {}", escape_arg(prompt_file)),
278 );
279 let executable = options.executable.as_deref().unwrap_or("codex");
280 let mut prefix_args = Vec::new();
281 if options.read_only {
282 prefix_args.push("--ask-for-approval".to_string());
283 prefix_args.push("never".to_string());
284 } else if let Some(ref approval_mode) = options.approval_mode {
285 prefix_args.push("--ask-for-approval".to_string());
286 prefix_args.push(approval_mode.clone());
287 }
288
289 format!(
290 "{} | {} {}",
291 input_command,
292 build_command_head(
293 executable,
294 &options.unset_env,
295 &options.extra_env,
296 &prefix_args
297 ),
298 args_str.join(" ")
299 )
300 .trim()
301 .to_string()
302}
303
304pub fn parse_output(output: &str) -> Vec<Value> {
313 parse_json_records(output)
314}
315
316pub fn extract_session_id(output: &str) -> Option<String> {
325 let messages = parse_output(output);
326
327 for msg in messages {
328 if let Some(thread_id) = msg.get("thread_id").and_then(|v| v.as_str()) {
329 return Some(thread_id.to_string());
330 }
331 if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
332 return Some(session_id.to_string());
333 }
334 }
335
336 None
337}
338
339#[derive(Debug, Clone, Default, serde::Serialize)]
341#[serde(rename_all = "camelCase")]
342pub struct CodexUsage {
343 pub input_tokens: u64,
344 pub output_tokens: u64,
345 pub cache_read_tokens: u64,
346 pub cache_creation_tokens: u64,
347 pub reasoning_tokens: u64,
348}
349
350pub fn extract_usage(output: &str) -> CodexUsage {
358 let messages = parse_output(output);
359 let mut result = CodexUsage::default();
360 for record in usage::records("codex", &messages) {
361 result.input_tokens += count(record, usage::INPUT);
362 result.output_tokens += count(record, usage::OUTPUT);
363 result.cache_read_tokens += count(record, usage::CACHE_READ);
364 result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
365 result.reasoning_tokens += count(record, usage::REASONING);
366 result.input_tokens -= count(record, usage::INPUT).min(count(record, usage::CACHE_READ));
367 }
368 result
369}
370
371#[derive(Debug, Clone)]
373pub struct CodexTool {
374 pub name: &'static str,
375 pub display_name: &'static str,
376 pub executable: &'static str,
377 pub supports_json_output: bool,
378 pub supports_json_input: bool,
379 pub supports_system_prompt: bool,
380 pub supports_resume: bool,
381 pub supports_read_only: bool,
382 pub supports_ask: bool,
383 pub default_model: &'static str,
384}
385
386impl Default for CodexTool {
387 fn default() -> Self {
388 Self {
389 name: "codex",
390 display_name: "Codex CLI",
391 executable: "codex",
392 supports_json_output: true,
393 supports_json_input: false, supports_system_prompt: false, supports_resume: true,
396 supports_read_only: true, supports_ask: false, default_model: "gpt-6-sol",
399 }
400 }
401}
402
403