fyi-core 0.1.0

Core types and traits for fyi
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
//! OpenAI Codex CLI framework adapter.
//!
//! This adapter handles integration with OpenAI's Codex CLI tool.
//! Codex has a unique integration model compared to other frameworks:
//!
//! - **Limited notify hooks**: Only 2 events (`agent-turn-complete`, `approval-requested`)
//! - **TOML configuration**: Config is in TOML format, not JSON
//! - **CLI argument JSON**: JSON payload passed as command-line argument, not stdin
//! - **Rich OTEL telemetry**: Built-in OTLP support for detailed API request tracking
//!
//! # Integration Strategy
//!
//! Due to limited notify hook coverage (only 2 events), OTEL telemetry is the
//! primary data source for Codex. The notify hooks provide basic events, while
//! OTEL captures rich telemetry including token usage, cost, and model info.
//!
//! The recommended integration approach is dual:
//! 1. notify hooks for the 2 available events (turn completion, approval requests)
//! 2. OTEL ingestion for rich telemetry data (`codex.api_request`, etc.)
//!
//! Users cannot track session lifecycle, tool execution, or user prompts via
//! notify hooks - this data is only available through OTEL telemetry.

use super::{ConfigFormat, FrameworkAdapter, ParsedHookInput};
use crate::EventType;
use std::path::PathBuf;

/// OpenAI Codex CLI framework adapter.
///
/// Handles hook generation and event parsing for Codex CLI.
pub struct CodexAdapter;

impl FrameworkAdapter for CodexAdapter {
    fn name(&self) -> &'static str {
        "codex"
    }

    fn display_name(&self) -> &'static str {
        "Codex CLI"
    }

    fn project_config_path(&self) -> PathBuf {
        PathBuf::from(".codex/config.toml")
    }

    fn user_config_path(&self) -> Option<PathBuf> {
        dirs::home_dir().map(|h| h.join(".codex/config.toml"))
    }

    fn config_format(&self) -> ConfigFormat {
        ConfigFormat::Toml
    }

    fn generate_hooks_config(
        &self,
        _enabled_events: &[EventType],
        fyi_bin: &str,
        otel_enabled: bool,
        otel_port: u16,
    ) -> serde_json::Value {
        // Note: _enabled_events is intentionally ignored because Codex uses a single
        // notify command for all events, rather than per-event hooks like other frameworks.
        //
        // Codex uses TOML config, so we generate a JSON representation
        // that will be converted to TOML by the init command.
        //
        // Codex notify hook format: notify = ["command", "arg1", "arg2"]
        // The hook receives JSON as the last CLI argument, not via stdin.
        let notify_command = vec![
            fyi_bin.to_string(),
            "log".to_string(),
            "--framework".to_string(),
            "codex".to_string(),
        ];

        let mut config = serde_json::json!({
            "notify": notify_command
        });

        // Add OTEL configuration if enabled
        // Codex expects: exporter = { otlp-http = { endpoint = "...", protocol = "json" } }
        if otel_enabled {
            config["otel"] = serde_json::json!({
                "exporter": {
                    "otlp-http": {
                        "endpoint": format!("http://127.0.0.1:{}", otel_port),
                        "protocol": "json"
                    }
                }
            });
        }

        config
    }

    fn merge_config(
        &self,
        generated: serde_json::Value,
        existing: Option<serde_json::Value>,
    ) -> serde_json::Value {
        let mut settings = existing.unwrap_or_else(|| serde_json::json!({}));

        // Set notify command
        if let Some(notify) = generated.get("notify") {
            settings["notify"] = notify.clone();
        }

        // Merge otel settings
        if let Some(new_otel) = generated.get("otel") {
            if let Some(existing_otel) = settings.get_mut("otel") {
                if let (Some(existing_obj), Some(new_obj)) =
                    (existing_otel.as_object_mut(), new_otel.as_object())
                {
                    for (key, value) in new_obj {
                        existing_obj.insert(key.clone(), value.clone());
                    }
                }
            } else {
                settings["otel"] = new_otel.clone();
            }
        }

        settings
    }

    fn parse_hook_input(&self, _event_type: &str, json: &serde_json::Value) -> ParsedHookInput {
        // Codex JSON payload schema (from notify hook):
        // {
        //   "type": "agent-turn-complete" | "approval-requested",
        //   "thread-id": "abc123",
        //   "turn-id": "turn-1",
        //   "cwd": "/path/to/project",
        //   ...
        // }
        ParsedHookInput {
            // thread-id maps to session_id
            session_id: json
                .get("thread-id")
                .and_then(|v| v.as_str())
                .map(String::from),
            // turn-id can be used for correlation (similar to tool_use_id)
            tool_use_id: json
                .get("turn-id")
                .and_then(|v| v.as_str())
                .map(String::from),
            cwd: json.get("cwd").and_then(|v| v.as_str()).map(String::from),
            // Codex doesn't provide these fields
            tool_name: None,
            subagent_type: None,
            spawned_agent_id: None,
            permission_mode: None,
            transcript_path: None,
            ..Default::default()
        }
    }

    fn map_event_type(&self, framework_event: &str) -> EventType {
        match framework_event {
            // approval-requested maps to PermissionRequest
            "approval-requested" => EventType::PermissionRequest,
            // agent-turn-complete has no direct canonical equivalent
            // Store as Custom for now
            "agent-turn-complete" => EventType::Custom("TurnComplete".to_string()),
            // Try canonical parsing, fall back to custom
            other => other
                .parse()
                .unwrap_or_else(|_| EventType::Custom(other.to_string())),
        }
    }

    fn supported_events(&self) -> Vec<&'static str> {
        // Codex only supports 2 notify hook events
        vec!["agent-turn-complete", "approval-requested"]
    }

    fn framework_specific_events(&self) -> Vec<&'static str> {
        // agent-turn-complete has no canonical equivalent
        vec!["agent-turn-complete"]
    }

    fn detection_env_vars(&self) -> &[&'static str] {
        // Environment variables that Codex CLI may set.
        // Note: These are inferred from Codex documentation and need verification
        // with actual Codex CLI behavior. If detection fails, users can explicitly
        // specify --framework codex.
        &["CODEX_SESSION_ID", "CODEX_PROJECT_DIR", "CODEX_THREAD_ID"]
    }

    fn is_installed(&self) -> bool {
        // Check if ~/.codex exists or codex is in PATH
        if let Some(config_path) = self.user_config_path()
            && let Some(parent) = config_path.parent()
            && parent.exists()
        {
            return true;
        }
        // Check if codex CLI is in PATH
        which::which("codex").is_ok()
    }

    fn remove_hooks(&self, existing: serde_json::Value) -> Option<serde_json::Value> {
        let mut settings = existing;
        let mut modified = false;

        // Remove notify command if it contains "fyi"
        if let Some(notify) = settings.get("notify")
            && let Some(arr) = notify.as_array()
        {
            // Check if any element contains "fyi"
            let has_fyi = arr
                .iter()
                .any(|v| v.as_str().is_some_and(|s| s.contains("fyi")));
            if has_fyi && let Some(obj) = settings.as_object_mut() {
                obj.remove("notify");
                modified = true;
            }
        }

        // Remove otel section
        if let Some(obj) = settings.as_object_mut()
            && obj.remove("otel").is_some()
        {
            modified = true;
        }

        if modified { Some(settings) } else { None }
    }
}

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

    #[test]
    fn test_name() {
        let adapter = CodexAdapter;
        assert_eq!(adapter.name(), "codex");
        assert_eq!(adapter.display_name(), "Codex CLI");
    }

    #[test]
    fn test_config_format() {
        let adapter = CodexAdapter;
        assert_eq!(adapter.config_format(), ConfigFormat::Toml);
    }

    #[test]
    fn test_project_config_path() {
        let adapter = CodexAdapter;
        assert_eq!(
            adapter.project_config_path(),
            PathBuf::from(".codex/config.toml")
        );
    }

    #[test]
    fn test_map_event_type() {
        let adapter = CodexAdapter;

        // Codex-specific mappings
        assert_eq!(
            adapter.map_event_type("approval-requested"),
            EventType::PermissionRequest
        );
        assert_eq!(
            adapter.map_event_type("agent-turn-complete"),
            EventType::Custom("TurnComplete".to_string())
        );

        // Unknown events become Custom
        assert_eq!(
            adapter.map_event_type("unknown-event"),
            EventType::Custom("unknown-event".to_string())
        );
    }

    #[test]
    fn test_parse_hook_input() {
        let adapter = CodexAdapter;
        let input = serde_json::json!({
            "type": "agent-turn-complete",
            "thread-id": "codex-thread-123",
            "turn-id": "turn-456",
            "cwd": "/home/user/project"
        });

        let parsed = adapter.parse_hook_input("agent-turn-complete", &input);

        assert_eq!(parsed.session_id, Some("codex-thread-123".to_string()));
        assert_eq!(parsed.tool_use_id, Some("turn-456".to_string()));
        assert_eq!(parsed.cwd, Some("/home/user/project".to_string()));
        // Codex doesn't provide these
        assert_eq!(parsed.tool_name, None);
        assert_eq!(parsed.permission_mode, None);
        assert_eq!(parsed.transcript_path, None);
    }

    #[test]
    fn test_generate_hooks_config() -> Result<(), String> {
        let adapter = CodexAdapter;
        let events = vec![EventType::PermissionRequest];

        let config = adapter.generate_hooks_config(&events, "fyi", false, 4318);

        // Should have notify array
        let notify = config
            .get("notify")
            .ok_or("missing notify")?
            .as_array()
            .ok_or("notify not an array")?;
        assert_eq!(notify[0], "fyi");
        assert_eq!(notify[1], "log");
        assert_eq!(notify[2], "--framework");
        assert_eq!(notify[3], "codex");

        // No otel section when disabled
        assert!(config.get("otel").is_none());
        Ok(())
    }

    #[test]
    fn test_generate_hooks_config_with_otel() -> Result<(), String> {
        let adapter = CodexAdapter;
        let events = vec![];

        let config = adapter.generate_hooks_config(&events, "fyi", true, 4318);

        // Should have otel section with nested exporter format
        let otel = config.get("otel").ok_or("missing otel")?;
        assert_eq!(
            otel["exporter"]["otlp-http"]["endpoint"],
            "http://127.0.0.1:4318"
        );
        assert_eq!(otel["exporter"]["otlp-http"]["protocol"], "json");
        Ok(())
    }

    #[test]
    fn test_merge_config_new() -> Result<(), String> {
        let adapter = CodexAdapter;
        let generated = serde_json::json!({
            "notify": ["fyi", "log", "--framework", "codex"]
        });

        let merged = adapter.merge_config(generated, None);

        let notify = merged
            .get("notify")
            .ok_or("missing notify")?
            .as_array()
            .ok_or("notify not an array")?;
        assert_eq!(notify.len(), 4);
        Ok(())
    }

    #[test]
    fn test_merge_config_existing() {
        let adapter = CodexAdapter;
        let generated = serde_json::json!({
            "notify": ["fyi", "log", "--framework", "codex"],
            "otel": {
                "exporter": {
                    "otlp-http": {
                        "endpoint": "http://127.0.0.1:4318",
                        "protocol": "json"
                    }
                }
            }
        });
        let existing = serde_json::json!({
            "model": "gpt-4",
            "otel": {
                "headers": { "x-api-key": "secret" }
            }
        });

        let merged = adapter.merge_config(generated, Some(existing));

        // Should preserve existing settings
        assert_eq!(merged["model"], "gpt-4");
        // Should have notify
        assert!(merged.get("notify").is_some());
        // Should merge otel - nested exporter format
        assert_eq!(
            merged["otel"]["exporter"]["otlp-http"]["endpoint"],
            "http://127.0.0.1:4318"
        );
        // Existing otel keys are preserved
        assert_eq!(merged["otel"]["headers"]["x-api-key"], "secret");
    }

    #[test]
    fn test_supported_events() {
        let adapter = CodexAdapter;
        let events = adapter.supported_events();

        assert!(events.contains(&"agent-turn-complete"));
        assert!(events.contains(&"approval-requested"));
        assert_eq!(events.len(), 2);
    }

    #[test]
    fn test_framework_specific_events() {
        let adapter = CodexAdapter;
        let events = adapter.framework_specific_events();

        assert!(events.contains(&"agent-turn-complete"));
        assert_eq!(events.len(), 1);
    }

    #[test]
    fn test_detection_env_vars() {
        let adapter = CodexAdapter;
        let vars = adapter.detection_env_vars();

        assert!(vars.contains(&"CODEX_SESSION_ID"));
        assert!(vars.contains(&"CODEX_PROJECT_DIR"));
        assert!(vars.contains(&"CODEX_THREAD_ID"));
    }
}