Skip to main content

cli_agents/adapters/codex/
mod.rs

1mod parse;
2
3use crate::DEFAULT_MAX_OUTPUT_BYTES;
4use crate::adapters::CliAdapter;
5use crate::discovery::discover_binary;
6use crate::error::{Error, Result};
7use crate::events::StreamEvent;
8use crate::types::{CliName, RunOptions, RunResult};
9use serde::Serialize;
10use std::collections::HashMap;
11use tokio_util::sync::CancellationToken;
12use tracing::warn;
13
14pub struct CodexAdapter;
15
16impl CliAdapter for CodexAdapter {
17    fn name(&self) -> CliName {
18        CliName::Codex
19    }
20
21    async fn run(
22        &self,
23        opts: &RunOptions,
24        emit: &(dyn Fn(StreamEvent) + Send + Sync),
25        cancel: CancellationToken,
26    ) -> Result<RunResult> {
27        let binary = match &opts.executable_path {
28            Some(p) => p.clone(),
29            None => discover_binary(CliName::Codex).await.ok_or(Error::NoCli)?,
30        };
31
32        // Write temp config if MCP servers or system_prompt_file are set.
33        // Hold the TempDir so it lives until the child process exits.
34        let (config_env, _tmp_dir) = write_configs(opts).await?;
35
36        let args = build_args(opts);
37        let mut extra_env = opts.env.clone().unwrap_or_default();
38        extra_env.extend(config_env);
39        let max_bytes = opts.max_output_bytes.unwrap_or(DEFAULT_MAX_OUTPUT_BYTES);
40
41        let mut state = parse::ParseState::default();
42        let mut text_tracker: HashMap<String, String> = HashMap::new();
43
44        let outcome = crate::adapters::spawn_and_stream(
45            crate::adapters::SpawnParams {
46                cli_label: "codex",
47                binary: &binary,
48                args: &args,
49                extra_env: &extra_env,
50                cwd: opts.cwd.as_deref().unwrap_or("."),
51                max_bytes,
52                cancel: &cancel,
53            },
54            |line| parse::parse_line(line, &mut state, &mut text_tracker, emit),
55        )
56        .await?;
57
58        match outcome {
59            crate::adapters::SpawnOutcome::Cancelled => Ok(RunResult {
60                success: false,
61                text: Some("Cancelled.".into()),
62                ..Default::default()
63            }),
64            crate::adapters::SpawnOutcome::Done { exit_code, stderr } => {
65                let success = !state.failed && exit_code == 0;
66                let text = if !success && state.result_text.is_none() {
67                    crate::adapters::extract_error_message(stderr.as_deref())
68                } else {
69                    state.result_text
70                };
71                Ok(RunResult {
72                    success,
73                    text,
74                    exit_code: Some(exit_code),
75                    stats: state.stats,
76                    session_id: state.session_id,
77                    stderr,
78                    cost_usd: None,
79                })
80            }
81        }
82    }
83}
84
85fn build_args(opts: &RunOptions) -> Vec<String> {
86    let mut args = vec!["exec".into()];
87
88    // Resume a previous session if requested
89    if let Some(session_id) = &opts.resume_session_id {
90        args.push("resume".into());
91        args.push(session_id.clone());
92    }
93
94    args.push(opts.task.clone());
95    args.push("--json".into());
96
97    if let Some(model) = &opts.model {
98        args.push("--model".into());
99        args.push(model.clone());
100    }
101
102    if let Some(cwd) = &opts.cwd {
103        args.push("--cd".into());
104        args.push(cwd.clone());
105    }
106
107    let codex_opts = opts.providers.as_ref().and_then(|p| p.codex.as_ref());
108
109    if let Some(co) = codex_opts {
110        if let Some(policy) = &co.approval_policy {
111            match policy.as_str() {
112                "full-auto" => args.push("--full-auto".into()),
113                "suggest" | "auto-edit" => {
114                    // Default Codex behavior — no flag needed
115                }
116                other => {
117                    warn!(policy = other, "unknown Codex approval policy, ignoring");
118                }
119            }
120        }
121        if let Some(sandbox) = &co.sandbox_mode {
122            args.push("--sandbox".into());
123            args.push(sandbox.clone());
124        }
125        if let Some(dirs) = &co.additional_directories {
126            for dir in dirs {
127                args.push("--cd".into());
128                args.push(dir.clone());
129            }
130        }
131        if let Some(images) = &co.images {
132            for img in images {
133                args.push("--image".into());
134                args.push(img.clone());
135            }
136        }
137        if let Some(schema) = &co.output_schema {
138            args.push("--output-schema".into());
139            args.push(schema.clone());
140        }
141    }
142
143    // Permission bypass for non-interactive use (opt-in)
144    if opts.skip_permissions {
145        args.push("--dangerously-bypass-approvals-and-sandbox".into());
146    }
147
148    args
149}
150
151// ── Codex TOML config types ──
152
153#[derive(Serialize)]
154struct CodexConfig {
155    #[serde(skip_serializing_if = "Option::is_none")]
156    instructions: Option<String>,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    mcp_servers: Option<HashMap<String, CodexMcpServer>>,
159}
160
161#[derive(Serialize)]
162struct CodexMcpServer {
163    #[serde(skip_serializing_if = "Option::is_none")]
164    command: Option<String>,
165    #[serde(skip_serializing_if = "Option::is_none")]
166    args: Option<Vec<String>>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    env: Option<HashMap<String, String>>,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    cwd: Option<String>,
171    #[serde(skip_serializing_if = "Option::is_none")]
172    tool_timeout_sec: Option<u64>,
173}
174
175/// Write temporary Codex config files for MCP servers and system prompts.
176///
177/// Codex reads MCP configuration from `config.toml` and system prompts from
178/// an `instructions` field in the same file. We write a temporary config and
179/// point Codex to it via `CODEX_HOME`.
180///
181/// Returns the env vars to set and the temp dir handle (must be kept alive
182/// until the child process exits).
183async fn write_configs(
184    opts: &RunOptions,
185) -> Result<(HashMap<String, String>, Option<tempfile::TempDir>)> {
186    let has_mcp = opts.mcp_servers.as_ref().is_some_and(|s| !s.is_empty());
187    let system_prompt = resolve_system_prompt(opts).await?;
188
189    if !has_mcp && system_prompt.is_none() {
190        return Ok((HashMap::new(), None));
191    }
192
193    let tmp_dir = tempfile::tempdir().map_err(Error::Io)?;
194    let codex_dir = tmp_dir.path().join(".codex");
195    tokio::fs::create_dir_all(&codex_dir)
196        .await
197        .map_err(Error::Io)?;
198
199    let config = CodexConfig {
200        instructions: system_prompt,
201        mcp_servers: opts.mcp_servers.as_ref().map(|servers| {
202            servers
203                .iter()
204                .map(|(name, s)| {
205                    (
206                        name.clone(),
207                        CodexMcpServer {
208                            command: s.command.clone(),
209                            args: s.args.clone(),
210                            env: s.env.clone(),
211                            cwd: s.cwd.clone(),
212                            tool_timeout_sec: s.timeout,
213                        },
214                    )
215                })
216                .collect()
217        }),
218    };
219
220    let toml_str = toml::to_string_pretty(&config)
221        .map_err(|e| Error::Other(format!("TOML serialization: {e}")))?;
222
223    let config_path = codex_dir.join("config.toml");
224    tokio::fs::write(&config_path, toml_str)
225        .await
226        .map_err(Error::Io)?;
227
228    let mut env = HashMap::new();
229    env.insert(
230        "CODEX_HOME".into(),
231        tmp_dir.path().to_string_lossy().into_owned(),
232    );
233    Ok((env, Some(tmp_dir)))
234}
235
236/// Resolve the effective system prompt: `system_prompt_file` takes precedence
237/// over `system_prompt`.
238async fn resolve_system_prompt(opts: &RunOptions) -> Result<Option<String>> {
239    if let Some(path) = &opts.system_prompt_file {
240        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
241            Error::Process(format!("failed to read system prompt file {path}: {e}"))
242        })?;
243        Ok(Some(content))
244    } else {
245        Ok(opts.system_prompt.clone())
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn build_args_minimal() {
255        let opts = RunOptions {
256            task: "hello".into(),
257            ..Default::default()
258        };
259        let args = build_args(&opts);
260        assert!(args.contains(&"exec".to_string()));
261        assert!(args.contains(&"hello".to_string()));
262        assert!(args.contains(&"--json".to_string()));
263    }
264
265    #[test]
266    fn build_args_no_permission_bypass_by_default() {
267        let opts = RunOptions {
268            task: "hello".into(),
269            ..Default::default()
270        };
271        let args = build_args(&opts);
272        assert!(!args.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
273    }
274
275    #[test]
276    fn build_args_permission_bypass_when_opted_in() {
277        let opts = RunOptions {
278            task: "hello".into(),
279            skip_permissions: true,
280            ..Default::default()
281        };
282        let args = build_args(&opts);
283        assert!(args.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
284    }
285
286    #[test]
287    fn build_args_resume_session() {
288        let opts = RunOptions {
289            task: "continue working".into(),
290            resume_session_id: Some("tid-abc123".into()),
291            ..Default::default()
292        };
293        let args = build_args(&opts);
294        // Should be: exec resume <session_id> <task> --json
295        let resume_idx = args.iter().position(|a| a == "resume").unwrap();
296        assert_eq!(args[resume_idx + 1], "tid-abc123");
297    }
298
299    #[test]
300    fn build_args_full_auto() {
301        let opts = RunOptions {
302            task: "fix bug".into(),
303            model: Some("o3".into()),
304            providers: Some(crate::types::ProviderOptions {
305                codex: Some(crate::types::CodexOptions {
306                    approval_policy: Some("full-auto".into()),
307                    sandbox_mode: Some("workspace-write".into()),
308                    ..Default::default()
309                }),
310                ..Default::default()
311            }),
312            ..Default::default()
313        };
314        let args = build_args(&opts);
315        assert!(args.contains(&"--full-auto".to_string()));
316        assert!(args.contains(&"--sandbox".to_string()));
317        assert!(args.contains(&"--model".to_string()));
318        assert!(args.contains(&"o3".to_string()));
319    }
320
321    #[tokio::test]
322    async fn write_configs_creates_mcp_config() {
323        let mut servers = HashMap::new();
324        servers.insert(
325            "test".into(),
326            crate::types::McpServer {
327                command: Some("test-server".into()),
328                args: Some(vec!["--flag".into()]),
329                ..Default::default()
330            },
331        );
332
333        let opts = RunOptions {
334            task: "hello".into(),
335            mcp_servers: Some(servers),
336            ..Default::default()
337        };
338
339        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
340        assert!(env.contains_key("CODEX_HOME"));
341        let tmp = tmp_dir.unwrap();
342
343        let config_path = tmp.path().join(".codex/config.toml");
344        let content = std::fs::read_to_string(&config_path).unwrap();
345        assert!(content.contains("[mcp_servers.test]"));
346        assert!(content.contains("test-server"));
347    }
348
349    #[tokio::test]
350    async fn write_configs_with_system_prompt() {
351        let opts = RunOptions {
352            task: "hello".into(),
353            system_prompt: Some("You are helpful.".into()),
354            ..Default::default()
355        };
356
357        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
358        assert!(env.contains_key("CODEX_HOME"));
359        let tmp = tmp_dir.unwrap();
360
361        let config_path = tmp.path().join(".codex/config.toml");
362        let content = std::fs::read_to_string(&config_path).unwrap();
363        assert!(content.contains("instructions"));
364        assert!(content.contains("You are helpful."));
365    }
366
367    #[tokio::test]
368    async fn write_configs_noop_when_empty() {
369        let opts = RunOptions {
370            task: "hello".into(),
371            ..Default::default()
372        };
373
374        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
375        assert!(env.is_empty());
376        assert!(tmp_dir.is_none());
377    }
378
379    #[tokio::test]
380    async fn write_configs_system_prompt_file_takes_precedence() {
381        let fixture = tempfile::tempdir().unwrap();
382
383        // Write a prompt file
384        let prompt_file = fixture.path().join("prompt.md");
385        std::fs::write(&prompt_file, "File prompt content").unwrap();
386
387        let opts = RunOptions {
388            task: "hello".into(),
389            system_prompt: Some("Inline prompt".into()),
390            system_prompt_file: Some(prompt_file.to_string_lossy().into_owned()),
391            ..Default::default()
392        };
393
394        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
395        assert!(env.contains_key("CODEX_HOME"));
396        let tmp = tmp_dir.unwrap();
397
398        let config_path = tmp.path().join(".codex/config.toml");
399        let content = std::fs::read_to_string(&config_path).unwrap();
400        assert!(content.contains("File prompt content"));
401        assert!(!content.contains("Inline prompt"));
402    }
403}