fyi-core 0.1.0

Core types and traits for fyi
Documentation
//! Framework adapter system for multi-platform AI coding assistant support.
//!
//! This module provides a trait-based abstraction for different AI coding assistant
//! platforms (Claude, Cursor, Gemini, OpenCode, Codex), allowing fyi to capture
//! hook events from any supported platform.
//!
//! # Architecture
//!
//! Each platform has its own adapter implementing [`FrameworkAdapter`] that handles:
//! - Hook configuration generation for `fyi activate`
//! - Event parsing and normalization for `fyi log`
//! - Framework detection from environment variables
//!
//! # Supported Frameworks
//!
//! - **claude**: The default, fully supported framework (Anthropic's Claude Code)
//! - **gemini**: Google's Gemini CLI tool
//! - **codex**: OpenAI's Codex CLI tool
//!
//! Future support planned for:
//! - **cursor**: Cursor IDE with agent mode hooks
//! - **opencode**: OpenCode AI assistant

mod claude;
mod codex;
mod gemini;

pub use claude::ClaudeAdapter;
pub use codex::CodexAdapter;
pub use gemini::GeminiAdapter;

use crate::EventType;
use std::collections::HashMap;
use std::path::PathBuf;

/// Configuration file format used by a framework.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfigFormat {
    /// JSON configuration (default for most frameworks)
    #[default]
    Json,
    /// TOML configuration (used by Codex CLI)
    Toml,
}

/// Framework adapter trait for AI coding assistant integrations.
///
/// Implementations of this trait handle the platform-specific details of:
/// - Generating hook configuration files
/// - Parsing hook input from stdin
/// - Mapping platform events to canonical event types
pub trait FrameworkAdapter: Send + Sync {
    /// Framework identifier (e.g., "claude", "cursor", "gemini", "opencode").
    fn name(&self) -> &'static str;

    /// Human-readable display name for the framework.
    fn display_name(&self) -> &'static str;

    /// Config file path for project-level settings.
    ///
    /// Returns the path relative to the project root where hooks should be installed.
    fn project_config_path(&self) -> PathBuf;

    /// Config file path for user-level settings.
    ///
    /// Returns the absolute path to the user's global settings file.
    fn user_config_path(&self) -> Option<PathBuf>;

    /// Generate hook configuration JSON for this framework.
    ///
    /// # Arguments
    /// * `enabled_events` - List of event types to enable hooks for
    /// * `fyi_bin` - Path to the fyi binary (or "fyi" if in PATH)
    /// * `otel_enabled` - Whether OpenTelemetry is enabled
    /// * `otel_port` - Port for OTel server
    ///
    /// # Returns
    /// JSON value representing the hooks configuration for this framework.
    fn generate_hooks_config(
        &self,
        enabled_events: &[EventType],
        fyi_bin: &str,
        otel_enabled: bool,
        otel_port: u16,
    ) -> serde_json::Value;

    /// Merge generated hooks into existing settings.
    ///
    /// # Arguments
    /// * `generated` - The generated hooks configuration
    /// * `existing` - The existing settings file content (if any)
    ///
    /// # Returns
    /// The merged settings JSON.
    fn merge_config(
        &self,
        generated: serde_json::Value,
        existing: Option<serde_json::Value>,
    ) -> serde_json::Value;

    /// Parse hook input JSON from stdin into canonical fields.
    ///
    /// # Arguments
    /// * `event_type` - The framework-specific event type string
    /// * `stdin_json` - Raw JSON from stdin
    ///
    /// # Returns
    /// Parsed hook data with normalized fields.
    fn parse_hook_input(&self, event_type: &str, stdin_json: &serde_json::Value)
    -> ParsedHookInput;

    /// Map a framework-specific event type to a canonical EventType.
    ///
    /// # Arguments
    /// * `framework_event` - The event type string from the framework
    ///
    /// # Returns
    /// The corresponding canonical EventType.
    fn map_event_type(&self, framework_event: &str) -> EventType;

    /// List of hook event types supported by this framework.
    fn supported_events(&self) -> Vec<&'static str>;

    /// Framework-specific events that have no canonical equivalent.
    ///
    /// These events are unique to this framework and will be configured
    /// alongside canonical events. They are stored as `Custom(name)` EventType.
    ///
    /// Override this method to add framework-specific events that don't map
    /// to any canonical event type.
    fn framework_specific_events(&self) -> Vec<&'static str> {
        vec![]
    }

    /// Configuration file format used by this framework.
    ///
    /// Most frameworks use JSON, but some (like Codex) use TOML.
    /// Override this method if the framework uses a non-JSON format.
    fn config_format(&self) -> ConfigFormat {
        ConfigFormat::Json
    }

    /// Environment variables that indicate this framework is the caller.
    fn detection_env_vars(&self) -> &[&'static str];

    /// Detect if this framework is currently calling fyi.
    ///
    /// Checks environment variables to determine if a hook from this
    /// framework is invoking fyi.
    fn detect(&self) -> bool {
        self.detection_env_vars()
            .iter()
            .any(|var| std::env::var(var).is_ok())
    }

    /// Check if this framework is installed on the system.
    ///
    /// Returns true if the framework's config directory exists or
    /// the framework's CLI tool is in PATH.
    fn is_installed(&self) -> bool;

    /// Remove fyi hooks from the framework's settings.
    ///
    /// Returns the modified settings with fyi hooks removed,
    /// or None if there are no fyi hooks to remove.
    ///
    /// # Arguments
    /// * `existing` - The existing settings file content
    ///
    /// # Returns
    /// Some(modified settings) if hooks were removed, None if no fyi hooks found.
    fn remove_hooks(&self, existing: serde_json::Value) -> Option<serde_json::Value>;
}

/// Parsed hook input with normalized fields.
///
/// This struct contains fields extracted from framework-specific hook JSON,
/// normalized to a common format for storage.
#[derive(Debug, Default, Clone)]
pub struct ParsedHookInput {
    /// Session identifier
    pub session_id: Option<String>,
    /// Tool use correlation ID
    pub tool_use_id: Option<String>,
    /// Tool name (Bash, Read, Write, etc.)
    pub tool_name: Option<String>,
    /// Subagent type for Task tool
    pub subagent_type: Option<String>,
    /// Spawned agent ID from PostToolUse
    pub spawned_agent_id: Option<String>,
    /// Permission mode
    pub permission_mode: Option<String>,
    /// Transcript file path
    pub transcript_path: Option<String>,
    /// Working directory
    pub cwd: Option<String>,
    /// Additional framework-specific fields
    pub extra: HashMap<String, serde_json::Value>,
}

/// Get all available framework adapters.
pub fn all_adapters() -> Vec<&'static dyn FrameworkAdapter> {
    vec![&ClaudeAdapter, &GeminiAdapter, &CodexAdapter]
}

/// Get a framework adapter by name.
pub fn get_adapter(name: &str) -> Option<&'static dyn FrameworkAdapter> {
    match name.to_lowercase().as_str() {
        "claude" => Some(&ClaudeAdapter),
        "gemini" => Some(&GeminiAdapter),
        "codex" => Some(&CodexAdapter),
        _ => None,
    }
}

/// Detect the current framework from environment variables.
///
/// Checks environment variables set by each framework to determine
/// which one is currently invoking fyi. Returns the first matching
/// framework if multiple are detected.
pub fn detect_framework() -> Option<&'static dyn FrameworkAdapter> {
    all_adapters().into_iter().find(|adapter| adapter.detect())
}

/// Detect all frameworks that match current environment variables.
///
/// Useful for diagnosing ambiguous detection scenarios.
pub fn detect_all_frameworks() -> Vec<&'static dyn FrameworkAdapter> {
    all_adapters()
        .into_iter()
        .filter(|adapter| adapter.detect())
        .collect()
}

/// Get all frameworks that are installed on the system.
///
/// Uses the `is_installed()` method on each adapter to determine
/// if the framework's config directory exists or CLI tool is available.
pub fn installed_frameworks() -> Vec<&'static dyn FrameworkAdapter> {
    all_adapters()
        .into_iter()
        .filter(|adapter| adapter.is_installed())
        .collect()
}

/// Get the default framework (Claude Code).
pub fn default_adapter() -> &'static dyn FrameworkAdapter {
    &ClaudeAdapter
}

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

    #[test]
    fn test_get_adapter_claude() {
        assert!(get_adapter("claude").is_some());
        assert!(get_adapter("CLAUDE").is_some());
    }

    #[test]
    fn test_get_adapter_gemini() {
        assert!(get_adapter("gemini").is_some());
        assert!(get_adapter("GEMINI").is_some());
    }

    #[test]
    fn test_get_adapter_unknown() {
        assert!(get_adapter("unknown").is_none());
        assert!(get_adapter("").is_none());
    }

    #[test]
    fn test_get_adapter_codex() {
        assert!(get_adapter("codex").is_some());
        assert!(get_adapter("CODEX").is_some());
    }

    #[test]
    fn test_all_adapters() {
        let adapters = all_adapters();
        assert!(!adapters.is_empty());
        assert!(adapters.iter().any(|a| a.name() == "claude"));
        assert!(adapters.iter().any(|a| a.name() == "gemini"));
        assert!(adapters.iter().any(|a| a.name() == "codex"));
    }

    #[test]
    fn test_default_adapter() {
        let adapter = default_adapter();
        assert_eq!(adapter.name(), "claude");
    }
}