Skip to main content

fyi_core/framework/
claude.rs

1//! Claude Code framework adapter.
2//!
3//! This adapter handles integration with Anthropic's Claude Code CLI tool.
4//! It is the default and most fully-featured adapter.
5
6use super::{FrameworkAdapter, ParsedHookInput};
7use crate::EventType;
8use std::path::PathBuf;
9
10/// Claude Code framework adapter.
11///
12/// Handles hook generation and event parsing for Claude Code.
13pub struct ClaudeAdapter;
14
15impl FrameworkAdapter for ClaudeAdapter {
16    fn name(&self) -> &'static str {
17        "claude"
18    }
19
20    fn display_name(&self) -> &'static str {
21        "Claude Code"
22    }
23
24    fn project_config_path(&self) -> PathBuf {
25        PathBuf::from(".claude/settings.json")
26    }
27
28    fn user_config_path(&self) -> Option<PathBuf> {
29        dirs::home_dir().map(|h| h.join(".claude/settings.json"))
30    }
31
32    fn generate_hooks_config(
33        &self,
34        enabled_events: &[EventType],
35        fyi_bin: &str,
36        otel_enabled: bool,
37        otel_port: u16,
38    ) -> serde_json::Value {
39        let mut hooks = serde_json::Map::new();
40
41        for event in enabled_events {
42            // For SessionStart with otel, also ensure the otel server is running
43            // Always include --framework flag for explicit framework identification
44            let command = if otel_enabled && *event == EventType::SessionStart {
45                format!(
46                    "{} otel start --port {} </dev/null >/dev/null 2>&1; {} log {} --framework claude",
47                    fyi_bin, otel_port, fyi_bin, event
48                )
49            } else {
50                format!("{} log {} --framework claude", fyi_bin, event)
51            };
52
53            let hook_entry = serde_json::json!([{
54                "matcher": "",
55                "hooks": [{
56                    "type": "command",
57                    "command": command,
58                    "timeout": 10
59                }]
60            }]);
61            hooks.insert(event.to_string(), hook_entry);
62        }
63
64        serde_json::json!({ "hooks": hooks })
65    }
66
67    fn merge_config(
68        &self,
69        generated: serde_json::Value,
70        existing: Option<serde_json::Value>,
71    ) -> serde_json::Value {
72        let mut settings = existing.unwrap_or_else(|| serde_json::json!({}));
73
74        // Merge hooks
75        if let Some(existing_hooks) = settings.get_mut("hooks") {
76            if let (Some(existing_obj), Some(new_obj)) = (
77                existing_hooks.as_object_mut(),
78                generated.get("hooks").and_then(|h| h.as_object()),
79            ) {
80                for (key, value) in new_obj {
81                    existing_obj.insert(key.clone(), value.clone());
82                }
83            }
84        } else {
85            settings["hooks"] = generated
86                .get("hooks")
87                .cloned()
88                .unwrap_or(serde_json::json!({}));
89        }
90
91        settings
92    }
93
94    fn parse_hook_input(
95        &self,
96        _event_type: &str,
97        stdin_json: &serde_json::Value,
98    ) -> ParsedHookInput {
99        ParsedHookInput {
100            session_id: stdin_json
101                .get("session_id")
102                .and_then(|v| v.as_str())
103                .map(String::from),
104            tool_use_id: stdin_json
105                .get("tool_use_id")
106                .and_then(|v| v.as_str())
107                .map(String::from),
108            tool_name: stdin_json
109                .get("tool_name")
110                .and_then(|v| v.as_str())
111                .map(String::from),
112            cwd: stdin_json
113                .get("cwd")
114                .and_then(|v| v.as_str())
115                .map(String::from),
116            permission_mode: stdin_json
117                .get("permission_mode")
118                .and_then(|v| v.as_str())
119                .map(String::from),
120            transcript_path: stdin_json
121                .get("transcript_path")
122                .and_then(|v| v.as_str())
123                .map(String::from),
124            // Extract subagent_type from tool_input.subagent_type (for Task tool)
125            subagent_type: stdin_json
126                .get("tool_input")
127                .and_then(|ti| ti.get("subagent_type"))
128                .and_then(|v| v.as_str())
129                .map(String::from),
130            // Extract spawned_agent_id from tool_response.agentId (for Task PostToolUse)
131            spawned_agent_id: stdin_json
132                .get("tool_response")
133                .and_then(|tr| tr.get("agentId"))
134                .and_then(|v| v.as_str())
135                .map(String::from),
136            ..Default::default()
137        }
138    }
139
140    fn map_event_type(&self, framework_event: &str) -> EventType {
141        // Claude Code uses the canonical event names directly
142        framework_event
143            .parse()
144            .unwrap_or_else(|_| EventType::Custom(framework_event.to_string()))
145    }
146
147    fn supported_events(&self) -> Vec<&'static str> {
148        vec![
149            "SessionStart",
150            "SessionEnd",
151            "PreToolUse",
152            "PostToolUse",
153            "PermissionRequest",
154            "PreCompact",
155            "Stop",
156            "SubagentStop",
157            "Notification",
158            "UserPromptSubmit",
159        ]
160    }
161
162    fn detection_env_vars(&self) -> &[&'static str] {
163        &["CLAUDE_SESSION_ID", "CLAUDE_PROJECT_DIR"]
164    }
165
166    fn is_installed(&self) -> bool {
167        // Check if ~/.claude exists or claude is in PATH
168        if let Some(config_path) = self.user_config_path()
169            && let Some(parent) = config_path.parent()
170            && parent.exists()
171        {
172            return true;
173        }
174        // Check if claude CLI is in PATH
175        which::which("claude").is_ok()
176    }
177
178    fn remove_hooks(&self, existing: serde_json::Value) -> Option<serde_json::Value> {
179        let mut settings = existing;
180        let mut modified = false;
181
182        // Remove only fyi hooks from settings, preserving user's custom hooks
183        if let Some(hooks) = settings.get_mut("hooks")
184            && let Some(hooks_obj) = hooks.as_object_mut()
185        {
186            // Process each event type
187            let keys: Vec<String> = hooks_obj.keys().cloned().collect();
188            for key in keys {
189                if let Some(event_hooks) = hooks_obj.get_mut(&key)
190                    && let Some(arr) = event_hooks.as_array_mut()
191                {
192                    // Filter out entries that contain fyi hooks
193                    let original_len = arr.len();
194                    arr.retain(|entry| {
195                        // Keep entry if it doesn't contain fyi hooks
196                        if let Some(inner_hooks) = entry.get("hooks").and_then(|h| h.as_array()) {
197                            // Check if any hook in this entry contains "fyi"
198                            !inner_hooks.iter().any(|hook| {
199                                hook.get("command")
200                                    .and_then(|c| c.as_str())
201                                    .is_some_and(|cmd| cmd.contains("fyi"))
202                            })
203                        } else {
204                            true // Keep entries without hooks array
205                        }
206                    });
207
208                    if arr.len() != original_len {
209                        modified = true;
210                    }
211
212                    // Remove the event key entirely if array is now empty
213                    if arr.is_empty() {
214                        hooks_obj.remove(&key);
215                    }
216                }
217            }
218
219            // If hooks object is now empty, remove it entirely
220            if hooks_obj.is_empty()
221                && let Some(obj) = settings.as_object_mut()
222            {
223                obj.remove("hooks");
224            }
225        }
226
227        // Remove OTel env vars
228        if let Some(env) = settings.get_mut("env")
229            && let Some(env_obj) = env.as_object_mut()
230        {
231            let otel_keys = [
232                "CLAUDE_CODE_ENABLE_TELEMETRY",
233                "OTEL_LOGS_EXPORTER",
234                "OTEL_EXPORTER_OTLP_PROTOCOL",
235                "OTEL_EXPORTER_OTLP_ENDPOINT",
236            ];
237            for key in otel_keys {
238                if env_obj.remove(key).is_some() {
239                    modified = true;
240                }
241            }
242
243            // If env object is now empty, remove it entirely
244            if env_obj.is_empty()
245                && let Some(obj) = settings.as_object_mut()
246            {
247                obj.remove("env");
248            }
249        }
250
251        if modified { Some(settings) } else { None }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn test_name() {
261        let adapter = ClaudeAdapter;
262        assert_eq!(adapter.name(), "claude");
263        assert_eq!(adapter.display_name(), "Claude Code");
264    }
265
266    #[test]
267    fn test_project_config_path() {
268        let adapter = ClaudeAdapter;
269        assert_eq!(
270            adapter.project_config_path(),
271            PathBuf::from(".claude/settings.json")
272        );
273    }
274
275    #[test]
276    fn test_map_event_type() {
277        let adapter = ClaudeAdapter;
278        assert_eq!(
279            adapter.map_event_type("SessionStart"),
280            EventType::SessionStart
281        );
282        assert_eq!(adapter.map_event_type("PreToolUse"), EventType::PreToolUse);
283        assert_eq!(
284            adapter.map_event_type("CustomEvent"),
285            EventType::Custom("CustomEvent".to_string())
286        );
287    }
288
289    #[test]
290    fn test_parse_hook_input() {
291        let adapter = ClaudeAdapter;
292        let input = serde_json::json!({
293            "session_id": "test-session",
294            "tool_use_id": "tool-123",
295            "tool_name": "Bash",
296            "cwd": "/home/user/project",
297            "permission_mode": "default",
298            "tool_input": {
299                "subagent_type": "Explore"
300            },
301            "tool_response": {
302                "agentId": "agent-456"
303            }
304        });
305
306        let parsed = adapter.parse_hook_input("PreToolUse", &input);
307
308        assert_eq!(parsed.session_id, Some("test-session".to_string()));
309        assert_eq!(parsed.tool_use_id, Some("tool-123".to_string()));
310        assert_eq!(parsed.tool_name, Some("Bash".to_string()));
311        assert_eq!(parsed.cwd, Some("/home/user/project".to_string()));
312        assert_eq!(parsed.permission_mode, Some("default".to_string()));
313        assert_eq!(parsed.subagent_type, Some("Explore".to_string()));
314        assert_eq!(parsed.spawned_agent_id, Some("agent-456".to_string()));
315    }
316
317    #[test]
318    fn test_generate_hooks_config() -> Result<(), String> {
319        let adapter = ClaudeAdapter;
320        let events = vec![EventType::SessionStart, EventType::PreToolUse];
321
322        let config = adapter.generate_hooks_config(&events, "fyi", false, 4318);
323
324        let hooks = config
325            .get("hooks")
326            .ok_or("missing hooks")?
327            .as_object()
328            .ok_or("hooks not an object")?;
329        assert!(hooks.contains_key("SessionStart"));
330        assert!(hooks.contains_key("PreToolUse"));
331
332        // Generated hooks include explicit --framework flag
333        let session_start = &hooks["SessionStart"][0]["hooks"][0];
334        let command = session_start["command"].as_str().ok_or("missing command")?;
335        assert!(command.contains("fyi log SessionStart"));
336        assert!(command.contains("--framework claude"));
337        Ok(())
338    }
339
340    #[test]
341    fn test_generate_hooks_config_with_otel() -> Result<(), String> {
342        let adapter = ClaudeAdapter;
343        let events = vec![EventType::SessionStart];
344
345        let config = adapter.generate_hooks_config(&events, "fyi", true, 4318);
346
347        let hooks = config
348            .get("hooks")
349            .ok_or("missing hooks")?
350            .as_object()
351            .ok_or("hooks not an object")?;
352        let session_start = &hooks["SessionStart"][0]["hooks"][0];
353        let command = session_start["command"].as_str().ok_or("missing command")?;
354
355        assert!(command.contains("otel start"));
356        assert!(command.contains("--port 4318"));
357        assert!(command.contains("--framework claude"));
358        Ok(())
359    }
360}