Skip to main content

fyi_core/framework/
gemini.rs

1//! Gemini CLI framework adapter.
2//!
3//! This adapter handles integration with Google's Gemini CLI tool.
4//! Gemini CLI uses a similar hook system to Claude Code with the same
5//! JSON configuration structure in `.gemini/settings.json`.
6
7use super::{FrameworkAdapter, ParsedHookInput};
8use crate::EventType;
9use std::borrow::Cow;
10use std::path::PathBuf;
11
12/// Gemini CLI framework adapter.
13///
14/// Handles hook generation and event parsing for Gemini CLI.
15pub struct GeminiAdapter;
16
17impl FrameworkAdapter for GeminiAdapter {
18    fn name(&self) -> &'static str {
19        "gemini"
20    }
21
22    fn display_name(&self) -> &'static str {
23        "Gemini CLI"
24    }
25
26    fn project_config_path(&self) -> PathBuf {
27        PathBuf::from(".gemini/settings.json")
28    }
29
30    fn user_config_path(&self) -> Option<PathBuf> {
31        dirs::home_dir().map(|h| h.join(".gemini/settings.json"))
32    }
33
34    fn generate_hooks_config(
35        &self,
36        enabled_events: &[EventType],
37        fyi_bin: &str,
38        otel_enabled: bool,
39        otel_port: u16,
40    ) -> serde_json::Value {
41        let mut hooks = serde_json::Map::new();
42
43        // Gemini-supported event names
44        let gemini_events: std::collections::HashSet<&str> =
45            self.supported_events().into_iter().collect();
46
47        // Process canonical events that map to Gemini events
48        for event in enabled_events {
49            // Map canonical event types to Gemini CLI event names
50            let gemini_event = canonical_to_gemini(event);
51
52            // Skip events that Gemini doesn't support
53            if !gemini_events.contains(gemini_event.as_ref()) {
54                continue;
55            }
56
57            // For SessionStart with otel, also ensure the otel server is running
58            // Always include --framework flag for explicit framework identification
59            let command = if otel_enabled && *event == EventType::SessionStart {
60                format!(
61                    "{} otel start --port {} </dev/null >/dev/null 2>&1; {} log {} --framework gemini",
62                    fyi_bin, otel_port, fyi_bin, gemini_event
63                )
64            } else {
65                format!("{} log {} --framework gemini", fyi_bin, gemini_event)
66            };
67
68            let hook_entry = serde_json::json!([{
69                "hooks": [{
70                    "type": "command",
71                    "command": command,
72                    "timeout": 10000
73                }]
74            }]);
75            hooks.insert(gemini_event.into_owned(), hook_entry);
76        }
77
78        // Add framework-specific events that have no canonical equivalent
79        for event_name in self.framework_specific_events() {
80            // Skip if already added (shouldn't happen, but be safe)
81            if hooks.contains_key(event_name) {
82                continue;
83            }
84
85            let command = format!("{} log {} --framework gemini", fyi_bin, event_name);
86
87            let hook_entry = serde_json::json!([{
88                "hooks": [{
89                    "type": "command",
90                    "command": command,
91                    "timeout": 10000
92                }]
93            }]);
94            hooks.insert(event_name.to_string(), hook_entry);
95        }
96
97        serde_json::json!({
98            "tools": {
99                "enableHooks": true
100            },
101            "hooks": hooks
102        })
103    }
104
105    fn merge_config(
106        &self,
107        generated: serde_json::Value,
108        existing: Option<serde_json::Value>,
109    ) -> serde_json::Value {
110        let mut settings = existing.unwrap_or_else(|| serde_json::json!({}));
111
112        // Ensure tools.enableHooks is set
113        if let Some(tools) = settings.get_mut("tools") {
114            if let Some(tools_obj) = tools.as_object_mut() {
115                tools_obj.insert("enableHooks".to_string(), serde_json::json!(true));
116            }
117        } else {
118            settings["tools"] = serde_json::json!({ "enableHooks": true });
119        }
120
121        // Merge hooks
122        if let Some(existing_hooks) = settings.get_mut("hooks") {
123            if let (Some(existing_obj), Some(new_obj)) = (
124                existing_hooks.as_object_mut(),
125                generated.get("hooks").and_then(|h| h.as_object()),
126            ) {
127                for (key, value) in new_obj {
128                    existing_obj.insert(key.clone(), value.clone());
129                }
130            }
131        } else {
132            settings["hooks"] = generated
133                .get("hooks")
134                .cloned()
135                .unwrap_or(serde_json::json!({}));
136        }
137
138        settings
139    }
140
141    fn parse_hook_input(
142        &self,
143        _event_type: &str,
144        stdin_json: &serde_json::Value,
145    ) -> ParsedHookInput {
146        ParsedHookInput {
147            session_id: stdin_json
148                .get("session_id")
149                .and_then(|v| v.as_str())
150                .map(String::from),
151            tool_use_id: stdin_json
152                .get("tool_use_id")
153                .and_then(|v| v.as_str())
154                .map(String::from),
155            tool_name: stdin_json
156                .get("tool_name")
157                .and_then(|v| v.as_str())
158                .map(String::from),
159            cwd: stdin_json
160                .get("cwd")
161                .and_then(|v| v.as_str())
162                .map(String::from),
163            transcript_path: stdin_json
164                .get("transcript_path")
165                .and_then(|v| v.as_str())
166                .map(String::from),
167            // Gemini CLI provides tool_input directly (not nested)
168            subagent_type: stdin_json
169                .get("tool_input")
170                .and_then(|ti| ti.get("subagent_type"))
171                .and_then(|v| v.as_str())
172                .map(String::from),
173            // Note: Gemini CLI does not provide permission_mode or spawned_agent_id
174            ..Default::default()
175        }
176    }
177
178    fn map_event_type(&self, framework_event: &str) -> EventType {
179        match framework_event {
180            // Gemini CLI uses different names for tool events
181            "BeforeTool" => EventType::PreToolUse,
182            "AfterTool" => EventType::PostToolUse,
183            // BeforeAgent maps to UserPromptSubmit (after user submits prompt)
184            "BeforeAgent" => EventType::UserPromptSubmit,
185            // AfterAgent maps to Stop (both indicate agent finished processing)
186            "AfterAgent" => EventType::Stop,
187            // PreCompress maps to PreCompact
188            "PreCompress" => EventType::PreCompact,
189            // These are direct mappings
190            "SessionStart" => EventType::SessionStart,
191            "SessionEnd" => EventType::SessionEnd,
192            "Notification" => EventType::Notification,
193            // Model events and other Gemini-specific events become Custom
194            "BeforeModel" | "AfterModel" | "BeforeToolSelection" => {
195                EventType::Custom(framework_event.to_string())
196            }
197            // Try canonical parsing, fall back to custom
198            other => other
199                .parse()
200                .unwrap_or_else(|_| EventType::Custom(other.to_string())),
201        }
202    }
203
204    fn supported_events(&self) -> Vec<&'static str> {
205        vec![
206            "SessionStart",
207            "SessionEnd",
208            "BeforeAgent",
209            "AfterAgent",
210            "BeforeModel",
211            "AfterModel",
212            "BeforeToolSelection",
213            "BeforeTool",
214            "AfterTool",
215            "PreCompress",
216            "Notification",
217        ]
218    }
219
220    fn framework_specific_events(&self) -> Vec<&'static str> {
221        // These Gemini events have no canonical equivalent
222        vec!["BeforeModel", "AfterModel", "BeforeToolSelection"]
223    }
224
225    fn detection_env_vars(&self) -> &[&'static str] {
226        &["GEMINI_SESSION_ID", "GEMINI_PROJECT_DIR"]
227    }
228
229    fn is_installed(&self) -> bool {
230        // Check if ~/.gemini exists or gemini is in PATH
231        if let Some(config_path) = self.user_config_path()
232            && let Some(parent) = config_path.parent()
233            && parent.exists()
234        {
235            return true;
236        }
237        // Check if gemini CLI is in PATH
238        which::which("gemini").is_ok()
239    }
240
241    fn remove_hooks(&self, existing: serde_json::Value) -> Option<serde_json::Value> {
242        let mut settings = existing;
243        let mut modified = false;
244
245        // Remove only fyi hooks from settings, preserving user's custom hooks
246        if let Some(hooks) = settings.get_mut("hooks")
247            && let Some(hooks_obj) = hooks.as_object_mut()
248        {
249            // Process each event type
250            let keys: Vec<String> = hooks_obj.keys().cloned().collect();
251            for key in keys {
252                if let Some(event_hooks) = hooks_obj.get_mut(&key)
253                    && let Some(arr) = event_hooks.as_array_mut()
254                {
255                    // Filter out entries that contain fyi hooks
256                    let original_len = arr.len();
257                    arr.retain(|entry| {
258                        // Keep entry if it doesn't contain fyi hooks
259                        if let Some(inner_hooks) = entry.get("hooks").and_then(|h| h.as_array()) {
260                            // Check if any hook in this entry contains "fyi"
261                            !inner_hooks.iter().any(|hook| {
262                                hook.get("command")
263                                    .and_then(|c| c.as_str())
264                                    .is_some_and(|cmd| cmd.contains("fyi"))
265                            })
266                        } else {
267                            true // Keep entries without hooks array
268                        }
269                    });
270
271                    if arr.len() != original_len {
272                        modified = true;
273                    }
274
275                    // Remove the event key entirely if array is now empty
276                    if arr.is_empty() {
277                        hooks_obj.remove(&key);
278                    }
279                }
280            }
281
282            // If hooks object is now empty, remove it entirely
283            if hooks_obj.is_empty()
284                && let Some(obj) = settings.as_object_mut()
285            {
286                obj.remove("hooks");
287            }
288        }
289
290        // Remove OTel env vars from Gemini settings
291        if let Some(env) = settings.get_mut("env")
292            && let Some(env_obj) = env.as_object_mut()
293        {
294            let otel_keys = [
295                "OTEL_LOGS_EXPORTER",
296                "OTEL_EXPORTER_OTLP_PROTOCOL",
297                "OTEL_EXPORTER_OTLP_ENDPOINT",
298            ];
299            for key in otel_keys {
300                if env_obj.remove(key).is_some() {
301                    modified = true;
302                }
303            }
304
305            // If env object is now empty, remove it entirely
306            if env_obj.is_empty()
307                && let Some(obj) = settings.as_object_mut()
308            {
309                obj.remove("env");
310            }
311        }
312
313        if modified { Some(settings) } else { None }
314    }
315}
316
317/// Map canonical event types to Gemini CLI event names
318fn canonical_to_gemini(event: &EventType) -> Cow<'static, str> {
319    match event {
320        EventType::SessionStart => Cow::Borrowed("SessionStart"),
321        EventType::SessionEnd => Cow::Borrowed("SessionEnd"),
322        EventType::PreToolUse => Cow::Borrowed("BeforeTool"),
323        EventType::PostToolUse => Cow::Borrowed("AfterTool"),
324        EventType::UserPromptSubmit => Cow::Borrowed("BeforeAgent"),
325        EventType::PreCompact => Cow::Borrowed("PreCompress"),
326        EventType::Notification => Cow::Borrowed("Notification"),
327        // Map Stop to AfterAgent - both indicate agent finished processing
328        EventType::Stop => Cow::Borrowed("AfterAgent"),
329        // Events that don't have a Gemini equivalent use their canonical name
330        EventType::PermissionRequest => Cow::Borrowed("PermissionRequest"),
331        EventType::SubagentStop => Cow::Borrowed("SubagentStop"),
332        EventType::ApiRequest => Cow::Borrowed("ApiRequest"),
333        EventType::Custom(s) => Cow::Owned(s.clone()),
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn test_name() {
343        let adapter = GeminiAdapter;
344        assert_eq!(adapter.name(), "gemini");
345        assert_eq!(adapter.display_name(), "Gemini CLI");
346    }
347
348    #[test]
349    fn test_project_config_path() {
350        let adapter = GeminiAdapter;
351        assert_eq!(
352            adapter.project_config_path(),
353            PathBuf::from(".gemini/settings.json")
354        );
355    }
356
357    #[test]
358    fn test_map_event_type() {
359        let adapter = GeminiAdapter;
360        // Gemini-specific mappings
361        assert_eq!(adapter.map_event_type("BeforeTool"), EventType::PreToolUse);
362        assert_eq!(adapter.map_event_type("AfterTool"), EventType::PostToolUse);
363        assert_eq!(
364            adapter.map_event_type("BeforeAgent"),
365            EventType::UserPromptSubmit
366        );
367        // AfterAgent maps to Stop (both indicate agent finished processing)
368        assert_eq!(adapter.map_event_type("AfterAgent"), EventType::Stop);
369        assert_eq!(adapter.map_event_type("PreCompress"), EventType::PreCompact);
370        // Direct mappings
371        assert_eq!(
372            adapter.map_event_type("SessionStart"),
373            EventType::SessionStart
374        );
375        assert_eq!(adapter.map_event_type("SessionEnd"), EventType::SessionEnd);
376        assert_eq!(
377            adapter.map_event_type("Notification"),
378            EventType::Notification
379        );
380        // Model events become Custom
381        assert_eq!(
382            adapter.map_event_type("BeforeModel"),
383            EventType::Custom("BeforeModel".to_string())
384        );
385        assert_eq!(
386            adapter.map_event_type("AfterModel"),
387            EventType::Custom("AfterModel".to_string())
388        );
389    }
390
391    #[test]
392    fn test_parse_hook_input() {
393        let adapter = GeminiAdapter;
394        let input = serde_json::json!({
395            "session_id": "gemini-session-123",
396            "tool_use_id": "tool-456",
397            "tool_name": "write_file",
398            "cwd": "/home/user/project",
399            "transcript_path": "/tmp/transcript.jsonl",
400            "tool_input": {
401                "file_path": "/tmp/test.txt",
402                "content": "hello"
403            }
404        });
405
406        let parsed = adapter.parse_hook_input("BeforeTool", &input);
407
408        assert_eq!(parsed.session_id, Some("gemini-session-123".to_string()));
409        assert_eq!(parsed.tool_use_id, Some("tool-456".to_string()));
410        assert_eq!(parsed.tool_name, Some("write_file".to_string()));
411        assert_eq!(parsed.cwd, Some("/home/user/project".to_string()));
412        assert_eq!(
413            parsed.transcript_path,
414            Some("/tmp/transcript.jsonl".to_string())
415        );
416        // Verify that permission_mode and spawned_agent_id are not extracted
417        assert_eq!(parsed.permission_mode, None);
418        assert_eq!(parsed.spawned_agent_id, None);
419    }
420
421    #[test]
422    fn test_parse_hook_input_with_subagent_type() {
423        let adapter = GeminiAdapter;
424        let input = serde_json::json!({
425            "session_id": "gemini-123",
426            "tool_input": {
427                "subagent_type": "Explore"
428            }
429        });
430
431        let parsed = adapter.parse_hook_input("BeforeTool", &input);
432
433        assert_eq!(parsed.session_id, Some("gemini-123".to_string()));
434        assert_eq!(parsed.subagent_type, Some("Explore".to_string()));
435    }
436
437    #[test]
438    fn test_generate_hooks_config() -> Result<(), String> {
439        let adapter = GeminiAdapter;
440        let events = vec![EventType::SessionStart, EventType::PreToolUse];
441
442        let config = adapter.generate_hooks_config(&events, "fyi", false, 4318);
443
444        let hooks = config
445            .get("hooks")
446            .ok_or("missing hooks")?
447            .as_object()
448            .ok_or("hooks not an object")?;
449        // Should use Gemini event names
450        assert!(hooks.contains_key("SessionStart"));
451        assert!(hooks.contains_key("BeforeTool")); // PreToolUse -> BeforeTool
452
453        let before_tool = &hooks["BeforeTool"][0]["hooks"][0];
454        let command = before_tool["command"].as_str().ok_or("missing command")?;
455        assert!(command.contains("fyi log BeforeTool"));
456        // Should include explicit --framework flag
457        assert!(command.contains("--framework gemini"));
458        // Type should be "command"
459        assert_eq!(
460            before_tool["type"].as_str().ok_or("missing type")?,
461            "command"
462        );
463        // Timeout should be in milliseconds
464        assert_eq!(
465            before_tool["timeout"].as_i64().ok_or("missing timeout")?,
466            10000
467        );
468
469        // Should also include framework-specific events
470        assert!(
471            hooks.contains_key("BeforeModel"),
472            "Framework-specific BeforeModel should be included"
473        );
474        assert!(
475            hooks.contains_key("AfterModel"),
476            "Framework-specific AfterModel should be included"
477        );
478        assert!(
479            hooks.contains_key("BeforeToolSelection"),
480            "Framework-specific BeforeToolSelection should be included"
481        );
482        Ok(())
483    }
484
485    #[test]
486    fn test_framework_specific_events() {
487        let adapter = GeminiAdapter;
488        let events = adapter.framework_specific_events();
489
490        assert!(events.contains(&"BeforeModel"));
491        assert!(events.contains(&"AfterModel"));
492        assert!(events.contains(&"BeforeToolSelection"));
493        assert_eq!(events.len(), 3);
494    }
495
496    #[test]
497    fn test_generate_hooks_config_with_otel() -> Result<(), String> {
498        let adapter = GeminiAdapter;
499        let events = vec![EventType::SessionStart];
500
501        let config = adapter.generate_hooks_config(&events, "fyi", true, 4318);
502
503        let hooks = config
504            .get("hooks")
505            .ok_or("missing hooks")?
506            .as_object()
507            .ok_or("hooks not an object")?;
508        let session_start = &hooks["SessionStart"][0]["hooks"][0];
509        let command = session_start["command"].as_str().ok_or("missing command")?;
510
511        assert!(command.contains("otel start"));
512        assert!(command.contains("--port 4318"));
513        assert!(command.contains("--framework gemini"));
514        Ok(())
515    }
516
517    #[test]
518    fn test_merge_config_new() {
519        let adapter = GeminiAdapter;
520        let generated = serde_json::json!({
521            "hooks": {
522                "BeforeTool": [{"matcher": "", "hooks": []}]
523            }
524        });
525
526        let merged = adapter.merge_config(generated, None);
527
528        assert!(merged.get("hooks").is_some());
529        assert!(merged["hooks"].get("BeforeTool").is_some());
530    }
531
532    #[test]
533    fn test_merge_config_existing() {
534        let adapter = GeminiAdapter;
535        let generated = serde_json::json!({
536            "hooks": {
537                "BeforeTool": [{"matcher": "", "hooks": [{"command": "fyi log BeforeTool"}]}]
538            }
539        });
540        let existing = serde_json::json!({
541            "theme": "dark",
542            "hooks": {
543                "SessionStart": [{"matcher": "", "hooks": [{"command": "other-tool"}]}]
544            }
545        });
546
547        let merged = adapter.merge_config(generated, Some(existing));
548
549        // Should preserve existing settings
550        assert_eq!(merged["theme"], "dark");
551        // Should merge hooks
552        assert!(merged["hooks"].get("SessionStart").is_some());
553        assert!(merged["hooks"].get("BeforeTool").is_some());
554    }
555
556    #[test]
557    fn test_supported_events() {
558        let adapter = GeminiAdapter;
559        let events = adapter.supported_events();
560
561        assert!(events.contains(&"SessionStart"));
562        assert!(events.contains(&"BeforeTool"));
563        assert!(events.contains(&"AfterTool"));
564        assert!(events.contains(&"BeforeModel"));
565        assert!(events.contains(&"AfterModel"));
566    }
567
568    #[test]
569    fn test_detection_env_vars() {
570        let adapter = GeminiAdapter;
571        let vars = adapter.detection_env_vars();
572
573        assert!(vars.contains(&"GEMINI_SESSION_ID"));
574        assert!(vars.contains(&"GEMINI_PROJECT_DIR"));
575    }
576}