codex-cli-sdk 0.0.1

Rust SDK for the OpenAI Codex CLI
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use crate::hooks::HookMatcher;
use crate::mcp::McpServers;
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
use typed_builder::TypedBuilder;

// ── Crate-level config ─────────────────────────────────────────

/// Top-level configuration for the Codex SDK.
#[derive(Clone, TypedBuilder)]
pub struct CodexConfig {
    /// Path to the `codex` CLI binary. If None, auto-detected via discovery.
    #[builder(default, setter(strip_option, into))]
    pub cli_path: Option<PathBuf>,

    /// Environment variables to pass to the Codex CLI process.
    #[builder(default)]
    pub env: std::collections::HashMap<String, String>,

    /// TOML config overrides.
    #[builder(default)]
    pub config_overrides: ConfigOverrides,

    /// Config profile name (passed via `--profile`).
    #[builder(default, setter(strip_option, into))]
    pub profile: Option<String>,

    /// Timeout for CLI process spawn + session init.
    #[builder(default_code = "Some(Duration::from_secs(30))")]
    pub connect_timeout: Option<Duration>,

    /// Timeout for graceful shutdown.
    #[builder(default_code = "Some(Duration::from_secs(10))")]
    pub close_timeout: Option<Duration>,

    /// Timeout for `codex --version` check.
    #[builder(default_code = "Some(Duration::from_secs(5))")]
    pub version_check_timeout: Option<Duration>,

    /// Stderr callback — invoked with each line of stderr from the CLI.
    #[builder(default, setter(strip_option))]
    pub stderr_callback: Option<StderrCallback>,
}

pub type StderrCallback = std::sync::Arc<dyn Fn(&str) + Send + Sync>;

impl std::fmt::Debug for CodexConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CodexConfig")
            .field("cli_path", &self.cli_path)
            .field("env", &self.env)
            .field("config_overrides", &self.config_overrides)
            .field("profile", &self.profile)
            .field("connect_timeout", &self.connect_timeout)
            .field("close_timeout", &self.close_timeout)
            .field("version_check_timeout", &self.version_check_timeout)
            .field(
                "stderr_callback",
                &self.stderr_callback.as_ref().map(|_| "..."),
            )
            .finish()
    }
}

impl Default for CodexConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

// ── Per-thread options ─────────────────────────────────────────

/// Options for a single thread (conversation).
#[derive(Clone, TypedBuilder)]
pub struct ThreadOptions {
    /// Working directory for the thread.
    #[builder(default, setter(strip_option, into))]
    pub working_directory: Option<PathBuf>,

    /// Model to use (e.g., "gpt-5-codex", "o4-mini").
    #[builder(default, setter(strip_option, into))]
    pub model: Option<String>,

    /// Sandbox policy.
    #[builder(default)]
    pub sandbox: SandboxPolicy,

    /// Approval policy.
    #[builder(default)]
    pub approval: ApprovalPolicy,

    /// Additional writable directories (passed via `--add-dir`).
    #[builder(default)]
    pub additional_directories: Vec<PathBuf>,

    /// Skip git repository check.
    #[builder(default)]
    pub skip_git_repo_check: bool,

    /// Reasoning effort level.
    #[builder(default, setter(strip_option))]
    pub reasoning_effort: Option<ReasoningEffort>,

    /// Enable network access in sandbox.
    #[builder(default, setter(strip_option))]
    pub network_access: Option<bool>,

    /// Web search mode.
    #[builder(default, setter(strip_option))]
    pub web_search: Option<WebSearchMode>,

    /// JSON Schema for structured output.
    #[builder(default, setter(strip_option))]
    pub output_schema: Option<OutputSchema>,

    /// Ephemeral mode — don't persist session to disk.
    #[builder(default)]
    pub ephemeral: bool,

    /// Image file paths to include with the prompt.
    #[builder(default)]
    pub images: Vec<PathBuf>,

    /// Use local/OSS provider (lmstudio, ollama).
    #[builder(default, setter(strip_option, into))]
    pub local_provider: Option<String>,

    // ── Feature-parity fields (Gap 1, 2, 4, 5) ───────────────
    /// System prompt override — passed to CLI via `-c system_prompt="..."`.
    #[builder(default, setter(strip_option, into))]
    pub system_prompt: Option<String>,

    /// SDK-enforced maximum number of turns. The stream closes after this many
    /// `TurnCompleted` events.
    #[builder(default, setter(strip_option))]
    pub max_turns: Option<u32>,

    /// SDK-enforced token budget. The stream closes when cumulative
    /// `Usage.output_tokens` exceeds this value.
    #[builder(default, setter(strip_option))]
    pub max_budget_tokens: Option<u64>,

    /// MCP server configurations. Serialized to CLI config overrides.
    #[builder(default)]
    pub mcp_servers: McpServers,

    /// Hook matchers — evaluated in order on each stream event.
    #[builder(default)]
    pub hooks: Vec<HookMatcher>,

    /// Default timeout for hook callbacks (applied when `HookMatcher.timeout` is `None`).
    #[builder(default_code = "Duration::from_secs(30)")]
    pub default_hook_timeout: Duration,
}

impl std::fmt::Debug for ThreadOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ThreadOptions")
            .field("working_directory", &self.working_directory)
            .field("model", &self.model)
            .field("sandbox", &self.sandbox)
            .field("approval", &self.approval)
            .field("additional_directories", &self.additional_directories)
            .field("skip_git_repo_check", &self.skip_git_repo_check)
            .field("reasoning_effort", &self.reasoning_effort)
            .field("network_access", &self.network_access)
            .field("web_search", &self.web_search)
            .field("output_schema", &self.output_schema)
            .field("ephemeral", &self.ephemeral)
            .field("images", &self.images)
            .field("local_provider", &self.local_provider)
            .field("system_prompt", &self.system_prompt)
            .field("max_turns", &self.max_turns)
            .field("max_budget_tokens", &self.max_budget_tokens)
            .field("mcp_servers", &self.mcp_servers)
            .field("hooks", &self.hooks)
            .field("default_hook_timeout", &self.default_hook_timeout)
            .finish()
    }
}

impl Default for ThreadOptions {
    fn default() -> Self {
        Self::builder().build()
    }
}

// ── Enums ──────────────────────────────────────────────────────

/// Sandbox isolation level.
#[derive(Debug, Clone, Default)]
pub enum SandboxPolicy {
    /// Read-only access (most restrictive).
    Restricted,
    /// Workspace directory is writable (default).
    #[default]
    WorkspaceWrite,
    /// Full filesystem access (DANGEROUS).
    DangerFullAccess,
}

/// When to ask for user approval of tool calls.
#[derive(Debug, Clone, Default)]
pub enum ApprovalPolicy {
    /// Auto-approve everything (default for exec mode).
    #[default]
    Never,
    /// Model decides when to ask.
    OnRequest,
    /// Only auto-approve known-safe read-only commands.
    UnlessTrusted,
}

/// Reasoning effort level.
#[derive(Debug, Clone)]
pub enum ReasoningEffort {
    Minimal,
    Low,
    Medium,
    High,
    XHigh,
}

/// Web search configuration.
#[derive(Debug, Clone)]
pub enum WebSearchMode {
    Disabled,
    Cached,
    Live,
}

/// Output schema — either an inline JSON object or a file path.
#[derive(Debug, Clone)]
pub enum OutputSchema {
    /// Inline JSON schema (written to temp file automatically).
    Inline(Value),
    /// Path to an existing schema file.
    File(PathBuf),
}

/// Config overrides — either flat key-value pairs or nested JSON.
#[derive(Debug, Clone, Default)]
pub enum ConfigOverrides {
    #[default]
    None,
    /// Flat key-value pairs: `[("model", "o4-mini")]`
    Flat(Vec<(String, String)>),
    /// Nested JSON object — recursively flattened to dot-notation.
    Json(Value),
}

impl ConfigOverrides {
    /// Flatten to CLI `-c key=value` pairs.
    pub fn to_cli_pairs(&self) -> Vec<(String, String)> {
        match self {
            Self::None => vec![],
            Self::Flat(pairs) => pairs.clone(),
            Self::Json(value) => {
                let mut result = vec![];
                flatten_json("", value, &mut result);
                result
            }
        }
    }
}

/// Recursively flatten nested JSON to dot-notation key-value pairs.
fn flatten_json(prefix: &str, value: &Value, out: &mut Vec<(String, String)>) {
    match value {
        Value::Object(map) => {
            for (key, val) in map {
                let full_key = if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{prefix}.{key}")
                };
                flatten_json(&full_key, val, out);
            }
        }
        Value::Array(arr) => {
            let formatted: Vec<String> = arr
                .iter()
                .map(|v| match v {
                    // serde_json::to_string produces a properly escaped JSON string.
                    Value::String(s) => {
                        serde_json::to_string(s).expect("infallible: String serialization")
                    }
                    other => other.to_string(),
                })
                .collect();
            out.push((prefix.to_string(), format!("[{}]", formatted.join(", "))));
        }
        // The Codex CLI `-c` flag expects strings wrapped in double quotes
        // (e.g. `key="value"`), but bare booleans and numbers (e.g. `key=true`).
        // Use serde_json to produce a properly escaped JSON string literal.
        Value::String(s) => out.push((
            prefix.to_string(),
            serde_json::to_string(s).expect("infallible: String serialization"),
        )),
        Value::Number(n) => out.push((prefix.to_string(), n.to_string())),
        Value::Bool(b) => out.push((prefix.to_string(), b.to_string())),
        Value::Null => {}
    }
}

// ── Per-turn options ───────────────────────────────────────────

/// Options for a single turn (run/run_streamed call).
#[derive(Debug, Default)]
pub struct TurnOptions {
    /// JSON Schema for structured output (overrides `ThreadOptions.output_schema`).
    pub output_schema: Option<Value>,
    /// Cancellation token — abort the turn mid-stream.
    pub cancel: Option<tokio_util::sync::CancellationToken>,
}

// ── Output schema temp file (RAII guard) ───────────────────────

/// Manages a temp file for inline JSON schemas.
pub(crate) struct OutputSchemaFile {
    _temp_dir: Option<tempfile::TempDir>,
    schema_path: Option<PathBuf>,
}

impl OutputSchemaFile {
    pub fn new(schema: Option<&Value>) -> crate::Result<Self> {
        match schema {
            None => Ok(Self {
                _temp_dir: None,
                schema_path: None,
            }),
            Some(value) => {
                if !value.is_object() {
                    return Err(crate::Error::Config(
                        "output schema must be a JSON object".into(),
                    ));
                }
                let temp_dir = tempfile::Builder::new()
                    .prefix("codex-output-schema-")
                    .tempdir()
                    .map_err(|e| crate::Error::Config(format!("failed to create temp dir: {e}")))?;
                let schema_path = temp_dir.path().join("schema.json");
                let bytes = serde_json::to_vec(value).map_err(|e| {
                    crate::Error::Config(format!("failed to serialize schema: {e}"))
                })?;
                std::fs::write(&schema_path, bytes)
                    .map_err(|e| crate::Error::Config(format!("failed to write schema: {e}")))?;
                Ok(Self {
                    schema_path: Some(schema_path),
                    _temp_dir: Some(temp_dir),
                })
            }
        }
    }

    pub fn path(&self) -> Option<&std::path::Path> {
        self.schema_path.as_deref()
    }
}

// ── CLI argument generation ────────────────────────────────────

impl ThreadOptions {
    /// Convert thread options to CLI arguments for `codex exec`.
    pub fn to_cli_args(&self) -> Vec<String> {
        let mut args = vec!["exec".to_string(), "--json".to_string()];

        if let Some(ref model) = self.model {
            args.extend(["--model".into(), model.clone()]);
        }

        match &self.sandbox {
            SandboxPolicy::Restricted => {
                args.extend(["--sandbox".into(), "restricted".into()]);
            }
            SandboxPolicy::WorkspaceWrite => {
                args.extend(["--sandbox".into(), "workspace-write".into()]);
            }
            SandboxPolicy::DangerFullAccess => {
                args.extend(["--sandbox".into(), "danger-full-access".into()]);
            }
        }

        if let Some(ref cwd) = self.working_directory {
            args.extend(["--cd".into(), cwd.display().to_string()]);
        }

        for dir in &self.additional_directories {
            args.extend(["--add-dir".into(), dir.display().to_string()]);
        }

        if self.skip_git_repo_check {
            args.push("--skip-git-repo-check".into());
        }

        if self.ephemeral {
            args.push("--ephemeral".into());
        }

        for img in &self.images {
            args.extend(["--image".into(), img.display().to_string()]);
        }

        if let Some(ref provider) = self.local_provider {
            args.extend(["--local-provider".into(), provider.clone()]);
        }

        match &self.approval {
            ApprovalPolicy::Never => {}
            ApprovalPolicy::OnRequest => {
                args.extend(["-c".into(), "approval_policy=on-request".into()]);
            }
            ApprovalPolicy::UnlessTrusted => {
                args.extend(["-c".into(), "approval_policy=untrusted".into()]);
            }
        }

        if let Some(ref effort) = self.reasoning_effort {
            let val = match effort {
                ReasoningEffort::Minimal => "minimal",
                ReasoningEffort::Low => "low",
                ReasoningEffort::Medium => "medium",
                ReasoningEffort::High => "high",
                ReasoningEffort::XHigh => "xhigh",
            };
            args.extend(["-c".into(), format!("model_reasoning_effort={val}")]);
        }

        if let Some(network) = self.network_access {
            args.extend([
                "-c".into(),
                format!("sandbox_workspace_write.network_access={network}"),
            ]);
        }

        if let Some(ref ws) = self.web_search {
            let val = match ws {
                WebSearchMode::Disabled => "disabled",
                WebSearchMode::Cached => "cached",
                WebSearchMode::Live => "live",
            };
            args.extend(["-c".into(), format!("web_search={val}")]);
        }

        // System prompt → -c system_prompt="..."
        // serde_json::to_string produces a properly escaped JSON string literal,
        // handling embedded quotes, backslashes, newlines, etc.
        if let Some(ref prompt) = self.system_prompt {
            let escaped = serde_json::to_string(prompt).expect("infallible: String serialization");
            args.extend(["-c".into(), format!("system_prompt={escaped}")]);
        }

        // MCP servers → -c mcp_servers=<json>
        // Note: max_turns and max_budget_tokens are SDK-enforced, not CLI args.
        if !self.mcp_servers.is_empty() {
            if let Ok(json) = serde_json::to_string(&self.mcp_servers) {
                args.extend(["-c".into(), format!("mcp_servers={json}")]);
            }
        }

        args
    }
}

impl CodexConfig {
    /// Merge crate-level config overrides into CLI args.
    pub fn apply_overrides(&self, args: &mut Vec<String>) {
        if let Some(ref profile) = self.profile {
            args.extend(["--profile".into(), profile.clone()]);
        }
        for (key, val) in self.config_overrides.to_cli_pairs() {
            args.extend(["-c".into(), format!("{key}={val}")]);
        }
    }

    /// Build environment variables for the subprocess.
    pub fn to_env(&self) -> std::collections::HashMap<String, String> {
        let mut env = self.env.clone();
        env.entry("CODEX_INTERNAL_ORIGINATOR_OVERRIDE".into())
            .or_insert_with(|| "codex_cli_sdk_rs".into());
        env.entry("CI".into()).or_insert_with(|| "true".into());
        env.entry("TERM".into()).or_insert_with(|| "xterm".into());
        env
    }
}

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

    #[test]
    fn default_thread_options_cli_args() {
        let args = ThreadOptions::default().to_cli_args();
        assert_eq!(args[0], "exec");
        assert_eq!(args[1], "--json");
        assert!(args.contains(&"--sandbox".to_string()));
        assert!(args.contains(&"workspace-write".to_string()));
    }

    #[test]
    fn full_thread_options_cli_args() {
        let opts = ThreadOptions::builder()
            .model("o4-mini")
            .sandbox(SandboxPolicy::DangerFullAccess)
            .ephemeral(true)
            .skip_git_repo_check(true)
            .reasoning_effort(ReasoningEffort::High)
            .network_access(true)
            .web_search(WebSearchMode::Live)
            .build();

        let args = opts.to_cli_args();
        assert!(args.contains(&"--model".to_string()));
        assert!(args.contains(&"o4-mini".to_string()));
        assert!(args.contains(&"danger-full-access".to_string()));
        assert!(args.contains(&"--ephemeral".to_string()));
        assert!(args.contains(&"--skip-git-repo-check".to_string()));
    }

    #[test]
    fn flatten_json_nested() {
        let value = serde_json::json!({
            "sandbox_workspace_write": {
                "network_access": true
            }
        });
        let overrides = ConfigOverrides::Json(value);
        let pairs = overrides.to_cli_pairs();
        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0].0, "sandbox_workspace_write.network_access");
        assert_eq!(pairs[0].1, "true");
    }

    #[test]
    fn config_to_env_sets_defaults() {
        let config = CodexConfig::default();
        let env = config.to_env();
        assert_eq!(env.get("CI").unwrap(), "true");
        assert_eq!(env.get("TERM").unwrap(), "xterm");
        assert!(env.contains_key("CODEX_INTERNAL_ORIGINATOR_OVERRIDE"));
    }

    #[test]
    fn output_schema_file_creates_temp() {
        let schema = serde_json::json!({"type": "object", "properties": {}});
        let guard = OutputSchemaFile::new(Some(&schema)).unwrap();
        assert!(guard.path().is_some());
        assert!(guard.path().unwrap().exists());
    }

    #[test]
    fn output_schema_file_rejects_non_object() {
        let schema = serde_json::json!("not an object");
        let result = OutputSchemaFile::new(Some(&schema));
        assert!(result.is_err());
    }

    #[test]
    fn system_prompt_cli_arg() {
        let opts = ThreadOptions::builder()
            .system_prompt("You are a helpful assistant")
            .build();
        let args = opts.to_cli_args();
        assert!(args.contains(&"-c".to_string()));
        assert!(
            args.iter()
                .any(|a| a.contains("system_prompt=") && a.contains("You are a helpful assistant"))
        );
    }

    #[test]
    fn system_prompt_with_special_chars_is_escaped() {
        let opts = ThreadOptions::builder()
            .system_prompt(r#"Say "hello" and use \n newlines"#)
            .build();
        let args = opts.to_cli_args();
        let arg = args
            .iter()
            .find(|a| a.starts_with("system_prompt="))
            .expect("system_prompt arg missing");
        // Value must be a valid JSON string (parseable, no raw unescaped quotes).
        let json_value = arg.strip_prefix("system_prompt=").unwrap();
        let parsed: String = serde_json::from_str(json_value)
            .expect("system_prompt value should be valid JSON string");
        assert!(parsed.contains('"'));
        assert!(parsed.contains('\\'));
    }

    #[test]
    fn flatten_json_escapes_string_values() {
        let value = serde_json::json!({ "key": "val\"ue with \"quotes\" and \\backslash" });
        let overrides = ConfigOverrides::Json(value);
        let pairs = overrides.to_cli_pairs();
        assert_eq!(pairs.len(), 1);
        // The value must be a valid JSON string literal.
        let parsed: String = serde_json::from_str(&pairs[0].1)
            .expect("flattened string value should be valid JSON string");
        assert!(parsed.contains('"'));
    }

    #[test]
    fn mcp_servers_cli_arg() {
        use crate::mcp::McpServerConfig;

        let mut servers = crate::mcp::McpServers::new();
        servers.insert(
            "fs".into(),
            McpServerConfig::new("npx").with_args(["-y", "fs-server"]),
        );

        let opts = ThreadOptions::builder().mcp_servers(servers).build();
        let args = opts.to_cli_args();
        assert!(args.iter().any(|a| a.starts_with("mcp_servers=")));
    }

    #[test]
    fn max_turns_not_in_cli_args() {
        let opts = ThreadOptions::builder().max_turns(5).build();
        let args = opts.to_cli_args();
        // max_turns is SDK-enforced, not a CLI arg
        assert!(!args.iter().any(|a| a.contains("max_turns")));
    }

    #[test]
    fn max_budget_tokens_not_in_cli_args() {
        let opts = ThreadOptions::builder().max_budget_tokens(10000).build();
        let args = opts.to_cli_args();
        assert!(!args.iter().any(|a| a.contains("max_budget")));
    }

    #[test]
    fn default_hook_timeout_is_30s() {
        let opts = ThreadOptions::default();
        assert_eq!(
            opts.default_hook_timeout,
            std::time::Duration::from_secs(30)
        );
    }
}