1use super::usage::{self, count};
5use crate::streaming::parse_json_records;
6use crate::tools::launch_options::{
7 codex_gateway_overrides, codex_mcp_servers_override, json_schema_arg,
8 normalize_reasoning_effort, push_attachments, push_directories, resolve_gateway, 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 if let Some(ref gateway) = launch.gateway {
218 let (base_url, token_env) =
219 resolve_gateway(gateway, "codex").unwrap_or_else(|error| panic!("{error}"));
220 let search = gateway.serves_standalone_web_search();
221 for value in codex_gateway_overrides(&base_url, &token_env, search) {
222 args.push("-c".to_string());
223 args.push(value);
224 }
225 }
226
227 if let Some(ref model) = options.model {
228 let mapped_model = map_model_to_id(model);
229 args.push("--model".to_string());
230 args.push(mapped_model);
231 }
232
233 if options.json {
235 args.push("--json".to_string());
236 }
237
238 args.push("--skip-git-repo-check".to_string());
240
241 if !options.read_only
242 && options.sandbox_mode.is_none()
243 && options.approval_mode.is_none()
244 && !options.skip_default_safety_flags
245 {
246 args.push("--dangerously-bypass-approvals-and-sandbox".to_string());
247 }
248
249 args.extend(options.extra_args.clone());
250
251 args
252}
253
254pub fn build_command(options: &CodexBuildOptions) -> String {
266 let args = build_args(options);
267 let mut args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
268 if let Some(ref file) = options.launch.json_schema_file {
269 args_str.push(format!("--output-schema {}", escape_arg(file)));
270 } else if let Some(ref json_schema) = options.launch.json_schema {
271 args_str.push(format!(
272 "--output-schema <(printf '%s' {})",
273 escape_arg(&json_schema_arg(json_schema))
274 ));
275 }
276
277 let combined_prompt = match (&options.system_prompt, &options.prompt) {
279 (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
280 (Some(sys), None) => sys.clone(),
281 (None, Some(prompt)) => prompt.clone(),
282 (None, None) => String::new(),
283 };
284
285 let input_command = options.prompt_file.as_ref().map_or_else(
287 || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
288 |prompt_file| format!("cat {}", escape_arg(prompt_file)),
289 );
290 let executable = options.executable.as_deref().unwrap_or("codex");
291 let mut prefix_args = Vec::new();
292 if options.read_only {
293 prefix_args.push("--ask-for-approval".to_string());
294 prefix_args.push("never".to_string());
295 } else if let Some(ref approval_mode) = options.approval_mode {
296 prefix_args.push("--ask-for-approval".to_string());
297 prefix_args.push(approval_mode.clone());
298 }
299
300 format!(
301 "{} | {} {}",
302 input_command,
303 build_command_head(executable, &[], &[], &prefix_args),
304 args_str.join(" ")
305 )
306 .trim()
307 .to_string()
308}
309
310pub fn parse_output(output: &str) -> Vec<Value> {
319 parse_json_records(output)
320}
321
322pub fn extract_session_id(output: &str) -> Option<String> {
331 let messages = parse_output(output);
332
333 for msg in messages {
334 if let Some(thread_id) = msg.get("thread_id").and_then(|v| v.as_str()) {
335 return Some(thread_id.to_string());
336 }
337 if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
338 return Some(session_id.to_string());
339 }
340 }
341
342 None
343}
344
345#[derive(Debug, Clone, Default, serde::Serialize)]
347#[serde(rename_all = "camelCase")]
348pub struct CodexUsage {
349 pub input_tokens: u64,
350 pub output_tokens: u64,
351 pub cache_read_tokens: u64,
352 pub cache_creation_tokens: u64,
353 pub reasoning_tokens: u64,
354}
355
356pub fn extract_usage(output: &str) -> CodexUsage {
364 let messages = parse_output(output);
365 let mut result = CodexUsage::default();
366 for record in usage::records("codex", &messages) {
367 result.input_tokens += count(record, usage::INPUT);
368 result.output_tokens += count(record, usage::OUTPUT);
369 result.cache_read_tokens += count(record, usage::CACHE_READ);
370 result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
371 result.reasoning_tokens += count(record, usage::REASONING);
372 result.input_tokens -= count(record, usage::INPUT).min(count(record, usage::CACHE_READ));
373 }
374 result
375}
376
377#[derive(Debug, Clone)]
379pub struct CodexTool {
380 pub name: &'static str,
381 pub display_name: &'static str,
382 pub executable: &'static str,
383 pub supports_json_output: bool,
384 pub supports_json_input: bool,
385 pub supports_system_prompt: bool,
386 pub supports_resume: bool,
387 pub supports_read_only: bool,
388 pub supports_ask: bool,
389 pub default_model: &'static str,
390}
391
392impl Default for CodexTool {
393 fn default() -> Self {
394 Self {
395 name: "codex",
396 display_name: "Codex CLI",
397 executable: "codex",
398 supports_json_output: true,
399 supports_json_input: false, supports_system_prompt: false, supports_resume: true,
402 supports_read_only: true, supports_ask: false, default_model: "gpt-6-sol",
405 }
406 }
407}
408
409