fyi_core/framework/mod.rs
1//! Framework adapter system for multi-platform AI coding assistant support.
2//!
3//! This module provides a trait-based abstraction for different AI coding assistant
4//! platforms (Claude, Cursor, Gemini, OpenCode, Codex), allowing fyi to capture
5//! hook events from any supported platform.
6//!
7//! # Architecture
8//!
9//! Each platform has its own adapter implementing [`FrameworkAdapter`] that handles:
10//! - Hook configuration generation for `fyi activate`
11//! - Event parsing and normalization for `fyi log`
12//! - Framework detection from environment variables
13//!
14//! # Supported Frameworks
15//!
16//! - **claude**: The default, fully supported framework (Anthropic's Claude Code)
17//! - **gemini**: Google's Gemini CLI tool
18//! - **codex**: OpenAI's Codex CLI tool
19//!
20//! Future support planned for:
21//! - **cursor**: Cursor IDE with agent mode hooks
22//! - **opencode**: OpenCode AI assistant
23
24mod claude;
25mod codex;
26mod gemini;
27
28pub use claude::ClaudeAdapter;
29pub use codex::CodexAdapter;
30pub use gemini::GeminiAdapter;
31
32use crate::EventType;
33use std::collections::HashMap;
34use std::path::PathBuf;
35
36/// Configuration file format used by a framework.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum ConfigFormat {
39 /// JSON configuration (default for most frameworks)
40 #[default]
41 Json,
42 /// TOML configuration (used by Codex CLI)
43 Toml,
44}
45
46/// Framework adapter trait for AI coding assistant integrations.
47///
48/// Implementations of this trait handle the platform-specific details of:
49/// - Generating hook configuration files
50/// - Parsing hook input from stdin
51/// - Mapping platform events to canonical event types
52pub trait FrameworkAdapter: Send + Sync {
53 /// Framework identifier (e.g., "claude", "cursor", "gemini", "opencode").
54 fn name(&self) -> &'static str;
55
56 /// Human-readable display name for the framework.
57 fn display_name(&self) -> &'static str;
58
59 /// Config file path for project-level settings.
60 ///
61 /// Returns the path relative to the project root where hooks should be installed.
62 fn project_config_path(&self) -> PathBuf;
63
64 /// Config file path for user-level settings.
65 ///
66 /// Returns the absolute path to the user's global settings file.
67 fn user_config_path(&self) -> Option<PathBuf>;
68
69 /// Generate hook configuration JSON for this framework.
70 ///
71 /// # Arguments
72 /// * `enabled_events` - List of event types to enable hooks for
73 /// * `fyi_bin` - Path to the fyi binary (or "fyi" if in PATH)
74 /// * `otel_enabled` - Whether OpenTelemetry is enabled
75 /// * `otel_port` - Port for OTel server
76 ///
77 /// # Returns
78 /// JSON value representing the hooks configuration for this framework.
79 fn generate_hooks_config(
80 &self,
81 enabled_events: &[EventType],
82 fyi_bin: &str,
83 otel_enabled: bool,
84 otel_port: u16,
85 ) -> serde_json::Value;
86
87 /// Merge generated hooks into existing settings.
88 ///
89 /// # Arguments
90 /// * `generated` - The generated hooks configuration
91 /// * `existing` - The existing settings file content (if any)
92 ///
93 /// # Returns
94 /// The merged settings JSON.
95 fn merge_config(
96 &self,
97 generated: serde_json::Value,
98 existing: Option<serde_json::Value>,
99 ) -> serde_json::Value;
100
101 /// Parse hook input JSON from stdin into canonical fields.
102 ///
103 /// # Arguments
104 /// * `event_type` - The framework-specific event type string
105 /// * `stdin_json` - Raw JSON from stdin
106 ///
107 /// # Returns
108 /// Parsed hook data with normalized fields.
109 fn parse_hook_input(&self, event_type: &str, stdin_json: &serde_json::Value)
110 -> ParsedHookInput;
111
112 /// Map a framework-specific event type to a canonical EventType.
113 ///
114 /// # Arguments
115 /// * `framework_event` - The event type string from the framework
116 ///
117 /// # Returns
118 /// The corresponding canonical EventType.
119 fn map_event_type(&self, framework_event: &str) -> EventType;
120
121 /// List of hook event types supported by this framework.
122 fn supported_events(&self) -> Vec<&'static str>;
123
124 /// Framework-specific events that have no canonical equivalent.
125 ///
126 /// These events are unique to this framework and will be configured
127 /// alongside canonical events. They are stored as `Custom(name)` EventType.
128 ///
129 /// Override this method to add framework-specific events that don't map
130 /// to any canonical event type.
131 fn framework_specific_events(&self) -> Vec<&'static str> {
132 vec![]
133 }
134
135 /// Configuration file format used by this framework.
136 ///
137 /// Most frameworks use JSON, but some (like Codex) use TOML.
138 /// Override this method if the framework uses a non-JSON format.
139 fn config_format(&self) -> ConfigFormat {
140 ConfigFormat::Json
141 }
142
143 /// Environment variables that indicate this framework is the caller.
144 fn detection_env_vars(&self) -> &[&'static str];
145
146 /// Detect if this framework is currently calling fyi.
147 ///
148 /// Checks environment variables to determine if a hook from this
149 /// framework is invoking fyi.
150 fn detect(&self) -> bool {
151 self.detection_env_vars()
152 .iter()
153 .any(|var| std::env::var(var).is_ok())
154 }
155
156 /// Check if this framework is installed on the system.
157 ///
158 /// Returns true if the framework's config directory exists or
159 /// the framework's CLI tool is in PATH.
160 fn is_installed(&self) -> bool;
161
162 /// Remove fyi hooks from the framework's settings.
163 ///
164 /// Returns the modified settings with fyi hooks removed,
165 /// or None if there are no fyi hooks to remove.
166 ///
167 /// # Arguments
168 /// * `existing` - The existing settings file content
169 ///
170 /// # Returns
171 /// Some(modified settings) if hooks were removed, None if no fyi hooks found.
172 fn remove_hooks(&self, existing: serde_json::Value) -> Option<serde_json::Value>;
173}
174
175/// Parsed hook input with normalized fields.
176///
177/// This struct contains fields extracted from framework-specific hook JSON,
178/// normalized to a common format for storage.
179#[derive(Debug, Default, Clone)]
180pub struct ParsedHookInput {
181 /// Session identifier
182 pub session_id: Option<String>,
183 /// Tool use correlation ID
184 pub tool_use_id: Option<String>,
185 /// Tool name (Bash, Read, Write, etc.)
186 pub tool_name: Option<String>,
187 /// Subagent type for Task tool
188 pub subagent_type: Option<String>,
189 /// Spawned agent ID from PostToolUse
190 pub spawned_agent_id: Option<String>,
191 /// Permission mode
192 pub permission_mode: Option<String>,
193 /// Transcript file path
194 pub transcript_path: Option<String>,
195 /// Working directory
196 pub cwd: Option<String>,
197 /// Additional framework-specific fields
198 pub extra: HashMap<String, serde_json::Value>,
199}
200
201/// Get all available framework adapters.
202pub fn all_adapters() -> Vec<&'static dyn FrameworkAdapter> {
203 vec![&ClaudeAdapter, &GeminiAdapter, &CodexAdapter]
204}
205
206/// Get a framework adapter by name.
207pub fn get_adapter(name: &str) -> Option<&'static dyn FrameworkAdapter> {
208 match name.to_lowercase().as_str() {
209 "claude" => Some(&ClaudeAdapter),
210 "gemini" => Some(&GeminiAdapter),
211 "codex" => Some(&CodexAdapter),
212 _ => None,
213 }
214}
215
216/// Detect the current framework from environment variables.
217///
218/// Checks environment variables set by each framework to determine
219/// which one is currently invoking fyi. Returns the first matching
220/// framework if multiple are detected.
221pub fn detect_framework() -> Option<&'static dyn FrameworkAdapter> {
222 all_adapters().into_iter().find(|adapter| adapter.detect())
223}
224
225/// Detect all frameworks that match current environment variables.
226///
227/// Useful for diagnosing ambiguous detection scenarios.
228pub fn detect_all_frameworks() -> Vec<&'static dyn FrameworkAdapter> {
229 all_adapters()
230 .into_iter()
231 .filter(|adapter| adapter.detect())
232 .collect()
233}
234
235/// Get all frameworks that are installed on the system.
236///
237/// Uses the `is_installed()` method on each adapter to determine
238/// if the framework's config directory exists or CLI tool is available.
239pub fn installed_frameworks() -> Vec<&'static dyn FrameworkAdapter> {
240 all_adapters()
241 .into_iter()
242 .filter(|adapter| adapter.is_installed())
243 .collect()
244}
245
246/// Get the default framework (Claude Code).
247pub fn default_adapter() -> &'static dyn FrameworkAdapter {
248 &ClaudeAdapter
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
256 fn test_get_adapter_claude() {
257 assert!(get_adapter("claude").is_some());
258 assert!(get_adapter("CLAUDE").is_some());
259 }
260
261 #[test]
262 fn test_get_adapter_gemini() {
263 assert!(get_adapter("gemini").is_some());
264 assert!(get_adapter("GEMINI").is_some());
265 }
266
267 #[test]
268 fn test_get_adapter_unknown() {
269 assert!(get_adapter("unknown").is_none());
270 assert!(get_adapter("").is_none());
271 }
272
273 #[test]
274 fn test_get_adapter_codex() {
275 assert!(get_adapter("codex").is_some());
276 assert!(get_adapter("CODEX").is_some());
277 }
278
279 #[test]
280 fn test_all_adapters() {
281 let adapters = all_adapters();
282 assert!(!adapters.is_empty());
283 assert!(adapters.iter().any(|a| a.name() == "claude"));
284 assert!(adapters.iter().any(|a| a.name() == "gemini"));
285 assert!(adapters.iter().any(|a| a.name() == "codex"));
286 }
287
288 #[test]
289 fn test_default_adapter() {
290 let adapter = default_adapter();
291 assert_eq!(adapter.name(), "claude");
292 }
293}