Skip to main content

fyi_core/framework/
codex.rs

1//! OpenAI Codex CLI framework adapter.
2//!
3//! This adapter handles integration with OpenAI's Codex CLI tool.
4//! Codex has a unique integration model compared to other frameworks:
5//!
6//! - **Limited notify hooks**: Only 2 events (`agent-turn-complete`, `approval-requested`)
7//! - **TOML configuration**: Config is in TOML format, not JSON
8//! - **CLI argument JSON**: JSON payload passed as command-line argument, not stdin
9//! - **Rich OTEL telemetry**: Built-in OTLP support for detailed API request tracking
10//!
11//! # Integration Strategy
12//!
13//! Due to limited notify hook coverage (only 2 events), OTEL telemetry is the
14//! primary data source for Codex. The notify hooks provide basic events, while
15//! OTEL captures rich telemetry including token usage, cost, and model info.
16//!
17//! The recommended integration approach is dual:
18//! 1. notify hooks for the 2 available events (turn completion, approval requests)
19//! 2. OTEL ingestion for rich telemetry data (`codex.api_request`, etc.)
20//!
21//! Users cannot track session lifecycle, tool execution, or user prompts via
22//! notify hooks - this data is only available through OTEL telemetry.
23
24use super::{ConfigFormat, FrameworkAdapter, ParsedHookInput};
25use crate::EventType;
26use std::path::PathBuf;
27
28/// OpenAI Codex CLI framework adapter.
29///
30/// Handles hook generation and event parsing for Codex CLI.
31pub struct CodexAdapter;
32
33impl FrameworkAdapter for CodexAdapter {
34    fn name(&self) -> &'static str {
35        "codex"
36    }
37
38    fn display_name(&self) -> &'static str {
39        "Codex CLI"
40    }
41
42    fn project_config_path(&self) -> PathBuf {
43        PathBuf::from(".codex/config.toml")
44    }
45
46    fn user_config_path(&self) -> Option<PathBuf> {
47        dirs::home_dir().map(|h| h.join(".codex/config.toml"))
48    }
49
50    fn config_format(&self) -> ConfigFormat {
51        ConfigFormat::Toml
52    }
53
54    fn generate_hooks_config(
55        &self,
56        _enabled_events: &[EventType],
57        fyi_bin: &str,
58        otel_enabled: bool,
59        otel_port: u16,
60    ) -> serde_json::Value {
61        // Note: _enabled_events is intentionally ignored because Codex uses a single
62        // notify command for all events, rather than per-event hooks like other frameworks.
63        //
64        // Codex uses TOML config, so we generate a JSON representation
65        // that will be converted to TOML by the init command.
66        //
67        // Codex notify hook format: notify = ["command", "arg1", "arg2"]
68        // The hook receives JSON as the last CLI argument, not via stdin.
69        let notify_command = vec![
70            fyi_bin.to_string(),
71            "log".to_string(),
72            "--framework".to_string(),
73            "codex".to_string(),
74        ];
75
76        let mut config = serde_json::json!({
77            "notify": notify_command
78        });
79
80        // Add OTEL configuration if enabled
81        // Codex expects: exporter = { otlp-http = { endpoint = "...", protocol = "json" } }
82        if otel_enabled {
83            config["otel"] = serde_json::json!({
84                "exporter": {
85                    "otlp-http": {
86                        "endpoint": format!("http://127.0.0.1:{}", otel_port),
87                        "protocol": "json"
88                    }
89                }
90            });
91        }
92
93        config
94    }
95
96    fn merge_config(
97        &self,
98        generated: serde_json::Value,
99        existing: Option<serde_json::Value>,
100    ) -> serde_json::Value {
101        let mut settings = existing.unwrap_or_else(|| serde_json::json!({}));
102
103        // Set notify command
104        if let Some(notify) = generated.get("notify") {
105            settings["notify"] = notify.clone();
106        }
107
108        // Merge otel settings
109        if let Some(new_otel) = generated.get("otel") {
110            if let Some(existing_otel) = settings.get_mut("otel") {
111                if let (Some(existing_obj), Some(new_obj)) =
112                    (existing_otel.as_object_mut(), new_otel.as_object())
113                {
114                    for (key, value) in new_obj {
115                        existing_obj.insert(key.clone(), value.clone());
116                    }
117                }
118            } else {
119                settings["otel"] = new_otel.clone();
120            }
121        }
122
123        settings
124    }
125
126    fn parse_hook_input(&self, _event_type: &str, json: &serde_json::Value) -> ParsedHookInput {
127        // Codex JSON payload schema (from notify hook):
128        // {
129        //   "type": "agent-turn-complete" | "approval-requested",
130        //   "thread-id": "abc123",
131        //   "turn-id": "turn-1",
132        //   "cwd": "/path/to/project",
133        //   ...
134        // }
135        ParsedHookInput {
136            // thread-id maps to session_id
137            session_id: json
138                .get("thread-id")
139                .and_then(|v| v.as_str())
140                .map(String::from),
141            // turn-id can be used for correlation (similar to tool_use_id)
142            tool_use_id: json
143                .get("turn-id")
144                .and_then(|v| v.as_str())
145                .map(String::from),
146            cwd: json.get("cwd").and_then(|v| v.as_str()).map(String::from),
147            // Codex doesn't provide these fields
148            tool_name: None,
149            subagent_type: None,
150            spawned_agent_id: None,
151            permission_mode: None,
152            transcript_path: None,
153            ..Default::default()
154        }
155    }
156
157    fn map_event_type(&self, framework_event: &str) -> EventType {
158        match framework_event {
159            // approval-requested maps to PermissionRequest
160            "approval-requested" => EventType::PermissionRequest,
161            // agent-turn-complete has no direct canonical equivalent
162            // Store as Custom for now
163            "agent-turn-complete" => EventType::Custom("TurnComplete".to_string()),
164            // Try canonical parsing, fall back to custom
165            other => other
166                .parse()
167                .unwrap_or_else(|_| EventType::Custom(other.to_string())),
168        }
169    }
170
171    fn supported_events(&self) -> Vec<&'static str> {
172        // Codex only supports 2 notify hook events
173        vec!["agent-turn-complete", "approval-requested"]
174    }
175
176    fn framework_specific_events(&self) -> Vec<&'static str> {
177        // agent-turn-complete has no canonical equivalent
178        vec!["agent-turn-complete"]
179    }
180
181    fn detection_env_vars(&self) -> &[&'static str] {
182        // Environment variables that Codex CLI may set.
183        // Note: These are inferred from Codex documentation and need verification
184        // with actual Codex CLI behavior. If detection fails, users can explicitly
185        // specify --framework codex.
186        &["CODEX_SESSION_ID", "CODEX_PROJECT_DIR", "CODEX_THREAD_ID"]
187    }
188
189    fn is_installed(&self) -> bool {
190        // Check if ~/.codex exists or codex is in PATH
191        if let Some(config_path) = self.user_config_path()
192            && let Some(parent) = config_path.parent()
193            && parent.exists()
194        {
195            return true;
196        }
197        // Check if codex CLI is in PATH
198        which::which("codex").is_ok()
199    }
200
201    fn remove_hooks(&self, existing: serde_json::Value) -> Option<serde_json::Value> {
202        let mut settings = existing;
203        let mut modified = false;
204
205        // Remove notify command if it contains "fyi"
206        if let Some(notify) = settings.get("notify")
207            && let Some(arr) = notify.as_array()
208        {
209            // Check if any element contains "fyi"
210            let has_fyi = arr
211                .iter()
212                .any(|v| v.as_str().is_some_and(|s| s.contains("fyi")));
213            if has_fyi && let Some(obj) = settings.as_object_mut() {
214                obj.remove("notify");
215                modified = true;
216            }
217        }
218
219        // Remove otel section
220        if let Some(obj) = settings.as_object_mut()
221            && obj.remove("otel").is_some()
222        {
223            modified = true;
224        }
225
226        if modified { Some(settings) } else { None }
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn test_name() {
236        let adapter = CodexAdapter;
237        assert_eq!(adapter.name(), "codex");
238        assert_eq!(adapter.display_name(), "Codex CLI");
239    }
240
241    #[test]
242    fn test_config_format() {
243        let adapter = CodexAdapter;
244        assert_eq!(adapter.config_format(), ConfigFormat::Toml);
245    }
246
247    #[test]
248    fn test_project_config_path() {
249        let adapter = CodexAdapter;
250        assert_eq!(
251            adapter.project_config_path(),
252            PathBuf::from(".codex/config.toml")
253        );
254    }
255
256    #[test]
257    fn test_map_event_type() {
258        let adapter = CodexAdapter;
259
260        // Codex-specific mappings
261        assert_eq!(
262            adapter.map_event_type("approval-requested"),
263            EventType::PermissionRequest
264        );
265        assert_eq!(
266            adapter.map_event_type("agent-turn-complete"),
267            EventType::Custom("TurnComplete".to_string())
268        );
269
270        // Unknown events become Custom
271        assert_eq!(
272            adapter.map_event_type("unknown-event"),
273            EventType::Custom("unknown-event".to_string())
274        );
275    }
276
277    #[test]
278    fn test_parse_hook_input() {
279        let adapter = CodexAdapter;
280        let input = serde_json::json!({
281            "type": "agent-turn-complete",
282            "thread-id": "codex-thread-123",
283            "turn-id": "turn-456",
284            "cwd": "/home/user/project"
285        });
286
287        let parsed = adapter.parse_hook_input("agent-turn-complete", &input);
288
289        assert_eq!(parsed.session_id, Some("codex-thread-123".to_string()));
290        assert_eq!(parsed.tool_use_id, Some("turn-456".to_string()));
291        assert_eq!(parsed.cwd, Some("/home/user/project".to_string()));
292        // Codex doesn't provide these
293        assert_eq!(parsed.tool_name, None);
294        assert_eq!(parsed.permission_mode, None);
295        assert_eq!(parsed.transcript_path, None);
296    }
297
298    #[test]
299    fn test_generate_hooks_config() -> Result<(), String> {
300        let adapter = CodexAdapter;
301        let events = vec![EventType::PermissionRequest];
302
303        let config = adapter.generate_hooks_config(&events, "fyi", false, 4318);
304
305        // Should have notify array
306        let notify = config
307            .get("notify")
308            .ok_or("missing notify")?
309            .as_array()
310            .ok_or("notify not an array")?;
311        assert_eq!(notify[0], "fyi");
312        assert_eq!(notify[1], "log");
313        assert_eq!(notify[2], "--framework");
314        assert_eq!(notify[3], "codex");
315
316        // No otel section when disabled
317        assert!(config.get("otel").is_none());
318        Ok(())
319    }
320
321    #[test]
322    fn test_generate_hooks_config_with_otel() -> Result<(), String> {
323        let adapter = CodexAdapter;
324        let events = vec![];
325
326        let config = adapter.generate_hooks_config(&events, "fyi", true, 4318);
327
328        // Should have otel section with nested exporter format
329        let otel = config.get("otel").ok_or("missing otel")?;
330        assert_eq!(
331            otel["exporter"]["otlp-http"]["endpoint"],
332            "http://127.0.0.1:4318"
333        );
334        assert_eq!(otel["exporter"]["otlp-http"]["protocol"], "json");
335        Ok(())
336    }
337
338    #[test]
339    fn test_merge_config_new() -> Result<(), String> {
340        let adapter = CodexAdapter;
341        let generated = serde_json::json!({
342            "notify": ["fyi", "log", "--framework", "codex"]
343        });
344
345        let merged = adapter.merge_config(generated, None);
346
347        let notify = merged
348            .get("notify")
349            .ok_or("missing notify")?
350            .as_array()
351            .ok_or("notify not an array")?;
352        assert_eq!(notify.len(), 4);
353        Ok(())
354    }
355
356    #[test]
357    fn test_merge_config_existing() {
358        let adapter = CodexAdapter;
359        let generated = serde_json::json!({
360            "notify": ["fyi", "log", "--framework", "codex"],
361            "otel": {
362                "exporter": {
363                    "otlp-http": {
364                        "endpoint": "http://127.0.0.1:4318",
365                        "protocol": "json"
366                    }
367                }
368            }
369        });
370        let existing = serde_json::json!({
371            "model": "gpt-4",
372            "otel": {
373                "headers": { "x-api-key": "secret" }
374            }
375        });
376
377        let merged = adapter.merge_config(generated, Some(existing));
378
379        // Should preserve existing settings
380        assert_eq!(merged["model"], "gpt-4");
381        // Should have notify
382        assert!(merged.get("notify").is_some());
383        // Should merge otel - nested exporter format
384        assert_eq!(
385            merged["otel"]["exporter"]["otlp-http"]["endpoint"],
386            "http://127.0.0.1:4318"
387        );
388        // Existing otel keys are preserved
389        assert_eq!(merged["otel"]["headers"]["x-api-key"], "secret");
390    }
391
392    #[test]
393    fn test_supported_events() {
394        let adapter = CodexAdapter;
395        let events = adapter.supported_events();
396
397        assert!(events.contains(&"agent-turn-complete"));
398        assert!(events.contains(&"approval-requested"));
399        assert_eq!(events.len(), 2);
400    }
401
402    #[test]
403    fn test_framework_specific_events() {
404        let adapter = CodexAdapter;
405        let events = adapter.framework_specific_events();
406
407        assert!(events.contains(&"agent-turn-complete"));
408        assert_eq!(events.len(), 1);
409    }
410
411    #[test]
412    fn test_detection_env_vars() {
413        let adapter = CodexAdapter;
414        let vars = adapter.detection_env_vars();
415
416        assert!(vars.contains(&"CODEX_SESSION_ID"));
417        assert!(vars.contains(&"CODEX_PROJECT_DIR"));
418        assert!(vars.contains(&"CODEX_THREAD_ID"));
419    }
420}