cli-agents 0.2.8

Build agentic apps over users' existing AI subscriptions (Claude, Codex, Gemini)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
mod parse;

use crate::adapters::CliAdapter;
use crate::discovery::discover_binary;
use crate::error::{Error, Result};
use crate::events::StreamEvent;
use crate::types::{CliName, RunOptions, RunResult};
use crate::DEFAULT_MAX_OUTPUT_BYTES;
use serde::Serialize;
use std::collections::HashMap;
use tokio_util::sync::CancellationToken;
use tracing::warn;

pub struct CodexAdapter;

impl CliAdapter for CodexAdapter {
    fn name(&self) -> CliName {
        CliName::Codex
    }

    async fn run(
        &self,
        opts: &RunOptions,
        emit: &(dyn Fn(StreamEvent) + Send + Sync),
        cancel: CancellationToken,
    ) -> Result<RunResult> {
        let binary = match &opts.executable_path {
            Some(p) => p.clone(),
            None => discover_binary(CliName::Codex).await.ok_or(Error::NoCli)?,
        };

        // Write temp config if MCP servers or system_prompt_file are set.
        // Hold the TempDir so it lives until the child process exits.
        let (config_env, _tmp_dir) = write_configs(opts).await?;

        let args = build_args(opts);
        let mut extra_env = opts.env.clone().unwrap_or_default();
        extra_env.extend(config_env);
        let max_bytes = opts.max_output_bytes.unwrap_or(DEFAULT_MAX_OUTPUT_BYTES);

        let mut state = parse::ParseState::default();
        let mut text_tracker: HashMap<String, String> = HashMap::new();

        let outcome = crate::adapters::spawn_and_stream(
            crate::adapters::SpawnParams {
                cli_label: "codex",
                binary: &binary,
                args: &args,
                extra_env: &extra_env,
                cwd: opts.cwd.as_deref().unwrap_or("."),
                max_bytes,
                cancel: &cancel,
            },
            |line| parse::parse_line(line, &mut state, &mut text_tracker, emit),
        )
        .await?;

        match outcome {
            crate::adapters::SpawnOutcome::Cancelled => Ok(RunResult {
                success: false,
                text: Some("Cancelled.".into()),
                ..Default::default()
            }),
            crate::adapters::SpawnOutcome::Done { exit_code, stderr } => {
                let success = !state.failed && exit_code == 0;
                let text = if !success && state.result_text.is_none() {
                    crate::adapters::extract_error_message(stderr.as_deref())
                } else {
                    state.result_text
                };
                Ok(RunResult {
                    success,
                    text,
                    exit_code: Some(exit_code),
                    stats: state.stats,
                    session_id: state.session_id,
                    stderr,
                    cost_usd: None,
                })
            }
        }
    }
}

fn build_args(opts: &RunOptions) -> Vec<String> {
    let mut args = vec!["exec".into()];

    // Resume a previous session if requested
    if let Some(session_id) = &opts.resume_session_id {
        args.push("resume".into());
        args.push(session_id.clone());
    }

    args.push(opts.task.clone());
    args.push("--json".into());

    if let Some(model) = &opts.model {
        args.push("--model".into());
        args.push(model.clone());
    }

    if let Some(cwd) = &opts.cwd {
        args.push("--cd".into());
        args.push(cwd.clone());
    }

    let codex_opts = opts.providers.as_ref().and_then(|p| p.codex.as_ref());

    if let Some(co) = codex_opts {
        if let Some(policy) = &co.approval_policy {
            match policy.as_str() {
                "full-auto" => args.push("--full-auto".into()),
                "suggest" | "auto-edit" => {
                    // Default Codex behavior — no flag needed
                }
                other => {
                    warn!(policy = other, "unknown Codex approval policy, ignoring");
                }
            }
        }
        if let Some(sandbox) = &co.sandbox_mode {
            args.push("--sandbox".into());
            args.push(sandbox.clone());
        }
        if let Some(dirs) = &co.additional_directories {
            for dir in dirs {
                args.push("--cd".into());
                args.push(dir.clone());
            }
        }
        if let Some(images) = &co.images {
            for img in images {
                args.push("--image".into());
                args.push(img.clone());
            }
        }
        if let Some(schema) = &co.output_schema {
            args.push("--output-schema".into());
            args.push(schema.clone());
        }
    }

    // Permission bypass for non-interactive use (opt-in).
    // Skip if an explicit approval_policy is set — the two flags conflict.
    let has_policy = codex_opts
        .and_then(|c| c.approval_policy.as_deref())
        .is_some_and(|p| !p.is_empty());
    if opts.skip_permissions && !has_policy {
        args.push("--dangerously-bypass-approvals-and-sandbox".into());
    }

    args
}

// ── Codex TOML config types ──

#[derive(Serialize)]
struct CodexConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    instructions: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    mcp_servers: Option<HashMap<String, CodexMcpServer>>,
}

#[derive(Serialize)]
struct CodexMcpServer {
    #[serde(skip_serializing_if = "Option::is_none")]
    command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    args: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    env: Option<HashMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cwd: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_timeout_sec: Option<u64>,
}

/// Write temporary Codex config files for MCP servers and system prompts.
///
/// Codex reads MCP configuration from `config.toml` and system prompts from
/// an `instructions` field in the same file. We write a temporary config and
/// point Codex to it via `CODEX_HOME`.
///
/// Returns the env vars to set and the temp dir handle (must be kept alive
/// until the child process exits).
async fn write_configs(
    opts: &RunOptions,
) -> Result<(HashMap<String, String>, Option<tempfile::TempDir>)> {
    let has_mcp = opts.mcp_servers.as_ref().is_some_and(|s| !s.is_empty());
    let system_prompt = resolve_system_prompt(opts).await?;

    if !has_mcp && system_prompt.is_none() {
        return Ok((HashMap::new(), None));
    }

    let tmp_dir = tempfile::tempdir().map_err(Error::Io)?;
    let codex_dir = tmp_dir.path().join(".codex");
    tokio::fs::create_dir_all(&codex_dir)
        .await
        .map_err(Error::Io)?;

    let config = CodexConfig {
        instructions: system_prompt,
        mcp_servers: opts.mcp_servers.as_ref().map(|servers| {
            servers
                .iter()
                .map(|(name, s)| {
                    (
                        name.clone(),
                        CodexMcpServer {
                            command: s.command.clone(),
                            args: s.args.clone(),
                            env: s.env.clone(),
                            cwd: s.cwd.clone(),
                            tool_timeout_sec: s.timeout,
                        },
                    )
                })
                .collect()
        }),
    };

    let toml_str = toml::to_string_pretty(&config)
        .map_err(|e| Error::Other(format!("TOML serialization: {e}")))?;

    let config_path = codex_dir.join("config.toml");
    tokio::fs::write(&config_path, toml_str)
        .await
        .map_err(Error::Io)?;

    let mut env = HashMap::new();
    env.insert(
        "CODEX_HOME".into(),
        tmp_dir.path().to_string_lossy().into_owned(),
    );
    Ok((env, Some(tmp_dir)))
}

/// Resolve the effective system prompt: `system_prompt_file` takes precedence
/// over `system_prompt`.
async fn resolve_system_prompt(opts: &RunOptions) -> Result<Option<String>> {
    if let Some(path) = &opts.system_prompt_file {
        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
            Error::Process(format!("failed to read system prompt file {path}: {e}"))
        })?;
        Ok(Some(content))
    } else {
        Ok(opts.system_prompt.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn build_args_minimal() {
        let opts = RunOptions {
            task: "hello".into(),
            ..Default::default()
        };
        let args = build_args(&opts);
        assert!(args.contains(&"exec".to_string()));
        assert!(args.contains(&"hello".to_string()));
        assert!(args.contains(&"--json".to_string()));
    }

    #[test]
    fn build_args_no_permission_bypass_by_default() {
        let opts = RunOptions {
            task: "hello".into(),
            ..Default::default()
        };
        let args = build_args(&opts);
        assert!(!args.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
    }

    #[test]
    fn build_args_permission_bypass_when_opted_in() {
        let opts = RunOptions {
            task: "hello".into(),
            skip_permissions: true,
            ..Default::default()
        };
        let args = build_args(&opts);
        assert!(args.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()));
    }

    #[test]
    fn build_args_resume_session() {
        let opts = RunOptions {
            task: "continue working".into(),
            resume_session_id: Some("tid-abc123".into()),
            ..Default::default()
        };
        let args = build_args(&opts);
        // Should be: exec resume <session_id> <task> --json
        let resume_idx = args.iter().position(|a| a == "resume").unwrap();
        assert_eq!(args[resume_idx + 1], "tid-abc123");
    }

    #[test]
    fn build_args_full_auto() {
        let opts = RunOptions {
            task: "fix bug".into(),
            model: Some("o3".into()),
            providers: Some(crate::types::ProviderOptions {
                codex: Some(crate::types::CodexOptions {
                    approval_policy: Some("full-auto".into()),
                    sandbox_mode: Some("workspace-write".into()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        let args = build_args(&opts);
        assert!(args.contains(&"--full-auto".to_string()));
        assert!(args.contains(&"--sandbox".to_string()));
        assert!(args.contains(&"--model".to_string()));
        assert!(args.contains(&"o3".to_string()));
    }

    #[test]
    fn build_args_full_auto_with_skip_permissions_no_conflict() {
        let opts = RunOptions {
            task: "fix bug".into(),
            skip_permissions: true,
            providers: Some(crate::types::ProviderOptions {
                codex: Some(crate::types::CodexOptions {
                    approval_policy: Some("full-auto".into()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        let args = build_args(&opts);
        assert!(args.contains(&"--full-auto".to_string()));
        assert!(
            !args.contains(&"--dangerously-bypass-approvals-and-sandbox".to_string()),
            "should not pass both --full-auto and --dangerously-bypass-approvals-and-sandbox"
        );
    }

    #[tokio::test]
    async fn write_configs_creates_mcp_config() {
        let mut servers = HashMap::new();
        servers.insert(
            "test".into(),
            crate::types::McpServer {
                command: Some("test-server".into()),
                args: Some(vec!["--flag".into()]),
                ..Default::default()
            },
        );

        let opts = RunOptions {
            task: "hello".into(),
            mcp_servers: Some(servers),
            ..Default::default()
        };

        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
        assert!(env.contains_key("CODEX_HOME"));
        let tmp = tmp_dir.unwrap();

        let config_path = tmp.path().join(".codex/config.toml");
        let content = std::fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("[mcp_servers.test]"));
        assert!(content.contains("test-server"));
    }

    #[tokio::test]
    async fn write_configs_with_system_prompt() {
        let opts = RunOptions {
            task: "hello".into(),
            system_prompt: Some("You are helpful.".into()),
            ..Default::default()
        };

        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
        assert!(env.contains_key("CODEX_HOME"));
        let tmp = tmp_dir.unwrap();

        let config_path = tmp.path().join(".codex/config.toml");
        let content = std::fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("instructions"));
        assert!(content.contains("You are helpful."));
    }

    #[tokio::test]
    async fn write_configs_noop_when_empty() {
        let opts = RunOptions {
            task: "hello".into(),
            ..Default::default()
        };

        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
        assert!(env.is_empty());
        assert!(tmp_dir.is_none());
    }

    #[tokio::test]
    async fn write_configs_system_prompt_file_takes_precedence() {
        let fixture = tempfile::tempdir().unwrap();

        // Write a prompt file
        let prompt_file = fixture.path().join("prompt.md");
        std::fs::write(&prompt_file, "File prompt content").unwrap();

        let opts = RunOptions {
            task: "hello".into(),
            system_prompt: Some("Inline prompt".into()),
            system_prompt_file: Some(prompt_file.to_string_lossy().into_owned()),
            ..Default::default()
        };

        let (env, tmp_dir) = write_configs(&opts).await.unwrap();
        assert!(env.contains_key("CODEX_HOME"));
        let tmp = tmp_dir.unwrap();

        let config_path = tmp.path().join(".codex/config.toml");
        let content = std::fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("File prompt content"));
        assert!(!content.contains("Inline prompt"));
    }
}