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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Gemini CLI framework adapter.
//!
//! This adapter handles integration with Google's Gemini CLI tool.
//! Gemini CLI uses a similar hook system to Claude Code with the same
//! JSON configuration structure in `.gemini/settings.json`.

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

/// Gemini CLI framework adapter.
///
/// Handles hook generation and event parsing for Gemini CLI.
pub struct GeminiAdapter;

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

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

    fn project_config_path(&self) -> PathBuf {
        PathBuf::from(".gemini/settings.json")
    }

    fn user_config_path(&self) -> Option<PathBuf> {
        dirs::home_dir().map(|h| h.join(".gemini/settings.json"))
    }

    fn generate_hooks_config(
        &self,
        enabled_events: &[EventType],
        fyi_bin: &str,
        otel_enabled: bool,
        otel_port: u16,
    ) -> serde_json::Value {
        let mut hooks = serde_json::Map::new();

        // Gemini-supported event names
        let gemini_events: std::collections::HashSet<&str> =
            self.supported_events().into_iter().collect();

        // Process canonical events that map to Gemini events
        for event in enabled_events {
            // Map canonical event types to Gemini CLI event names
            let gemini_event = canonical_to_gemini(event);

            // Skip events that Gemini doesn't support
            if !gemini_events.contains(gemini_event.as_ref()) {
                continue;
            }

            // For SessionStart with otel, also ensure the otel server is running
            // Always include --framework flag for explicit framework identification
            let command = if otel_enabled && *event == EventType::SessionStart {
                format!(
                    "{} otel start --port {} </dev/null >/dev/null 2>&1; {} log {} --framework gemini",
                    fyi_bin, otel_port, fyi_bin, gemini_event
                )
            } else {
                format!("{} log {} --framework gemini", fyi_bin, gemini_event)
            };

            let hook_entry = serde_json::json!([{
                "hooks": [{
                    "type": "command",
                    "command": command,
                    "timeout": 10000
                }]
            }]);
            hooks.insert(gemini_event.into_owned(), hook_entry);
        }

        // Add framework-specific events that have no canonical equivalent
        for event_name in self.framework_specific_events() {
            // Skip if already added (shouldn't happen, but be safe)
            if hooks.contains_key(event_name) {
                continue;
            }

            let command = format!("{} log {} --framework gemini", fyi_bin, event_name);

            let hook_entry = serde_json::json!([{
                "hooks": [{
                    "type": "command",
                    "command": command,
                    "timeout": 10000
                }]
            }]);
            hooks.insert(event_name.to_string(), hook_entry);
        }

        serde_json::json!({
            "tools": {
                "enableHooks": true
            },
            "hooks": hooks
        })
    }

    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!({}));

        // Ensure tools.enableHooks is set
        if let Some(tools) = settings.get_mut("tools") {
            if let Some(tools_obj) = tools.as_object_mut() {
                tools_obj.insert("enableHooks".to_string(), serde_json::json!(true));
            }
        } else {
            settings["tools"] = serde_json::json!({ "enableHooks": true });
        }

        // Merge hooks
        if let Some(existing_hooks) = settings.get_mut("hooks") {
            if let (Some(existing_obj), Some(new_obj)) = (
                existing_hooks.as_object_mut(),
                generated.get("hooks").and_then(|h| h.as_object()),
            ) {
                for (key, value) in new_obj {
                    existing_obj.insert(key.clone(), value.clone());
                }
            }
        } else {
            settings["hooks"] = generated
                .get("hooks")
                .cloned()
                .unwrap_or(serde_json::json!({}));
        }

        settings
    }

    fn parse_hook_input(
        &self,
        _event_type: &str,
        stdin_json: &serde_json::Value,
    ) -> ParsedHookInput {
        ParsedHookInput {
            session_id: stdin_json
                .get("session_id")
                .and_then(|v| v.as_str())
                .map(String::from),
            tool_use_id: stdin_json
                .get("tool_use_id")
                .and_then(|v| v.as_str())
                .map(String::from),
            tool_name: stdin_json
                .get("tool_name")
                .and_then(|v| v.as_str())
                .map(String::from),
            cwd: stdin_json
                .get("cwd")
                .and_then(|v| v.as_str())
                .map(String::from),
            transcript_path: stdin_json
                .get("transcript_path")
                .and_then(|v| v.as_str())
                .map(String::from),
            // Gemini CLI provides tool_input directly (not nested)
            subagent_type: stdin_json
                .get("tool_input")
                .and_then(|ti| ti.get("subagent_type"))
                .and_then(|v| v.as_str())
                .map(String::from),
            // Note: Gemini CLI does not provide permission_mode or spawned_agent_id
            ..Default::default()
        }
    }

    fn map_event_type(&self, framework_event: &str) -> EventType {
        match framework_event {
            // Gemini CLI uses different names for tool events
            "BeforeTool" => EventType::PreToolUse,
            "AfterTool" => EventType::PostToolUse,
            // BeforeAgent maps to UserPromptSubmit (after user submits prompt)
            "BeforeAgent" => EventType::UserPromptSubmit,
            // AfterAgent maps to Stop (both indicate agent finished processing)
            "AfterAgent" => EventType::Stop,
            // PreCompress maps to PreCompact
            "PreCompress" => EventType::PreCompact,
            // These are direct mappings
            "SessionStart" => EventType::SessionStart,
            "SessionEnd" => EventType::SessionEnd,
            "Notification" => EventType::Notification,
            // Model events and other Gemini-specific events become Custom
            "BeforeModel" | "AfterModel" | "BeforeToolSelection" => {
                EventType::Custom(framework_event.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> {
        vec![
            "SessionStart",
            "SessionEnd",
            "BeforeAgent",
            "AfterAgent",
            "BeforeModel",
            "AfterModel",
            "BeforeToolSelection",
            "BeforeTool",
            "AfterTool",
            "PreCompress",
            "Notification",
        ]
    }

    fn framework_specific_events(&self) -> Vec<&'static str> {
        // These Gemini events have no canonical equivalent
        vec!["BeforeModel", "AfterModel", "BeforeToolSelection"]
    }

    fn detection_env_vars(&self) -> &[&'static str] {
        &["GEMINI_SESSION_ID", "GEMINI_PROJECT_DIR"]
    }

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

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

        // Remove only fyi hooks from settings, preserving user's custom hooks
        if let Some(hooks) = settings.get_mut("hooks")
            && let Some(hooks_obj) = hooks.as_object_mut()
        {
            // Process each event type
            let keys: Vec<String> = hooks_obj.keys().cloned().collect();
            for key in keys {
                if let Some(event_hooks) = hooks_obj.get_mut(&key)
                    && let Some(arr) = event_hooks.as_array_mut()
                {
                    // Filter out entries that contain fyi hooks
                    let original_len = arr.len();
                    arr.retain(|entry| {
                        // Keep entry if it doesn't contain fyi hooks
                        if let Some(inner_hooks) = entry.get("hooks").and_then(|h| h.as_array()) {
                            // Check if any hook in this entry contains "fyi"
                            !inner_hooks.iter().any(|hook| {
                                hook.get("command")
                                    .and_then(|c| c.as_str())
                                    .is_some_and(|cmd| cmd.contains("fyi"))
                            })
                        } else {
                            true // Keep entries without hooks array
                        }
                    });

                    if arr.len() != original_len {
                        modified = true;
                    }

                    // Remove the event key entirely if array is now empty
                    if arr.is_empty() {
                        hooks_obj.remove(&key);
                    }
                }
            }

            // If hooks object is now empty, remove it entirely
            if hooks_obj.is_empty()
                && let Some(obj) = settings.as_object_mut()
            {
                obj.remove("hooks");
            }
        }

        // Remove OTel env vars from Gemini settings
        if let Some(env) = settings.get_mut("env")
            && let Some(env_obj) = env.as_object_mut()
        {
            let otel_keys = [
                "OTEL_LOGS_EXPORTER",
                "OTEL_EXPORTER_OTLP_PROTOCOL",
                "OTEL_EXPORTER_OTLP_ENDPOINT",
            ];
            for key in otel_keys {
                if env_obj.remove(key).is_some() {
                    modified = true;
                }
            }

            // If env object is now empty, remove it entirely
            if env_obj.is_empty()
                && let Some(obj) = settings.as_object_mut()
            {
                obj.remove("env");
            }
        }

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

/// Map canonical event types to Gemini CLI event names
fn canonical_to_gemini(event: &EventType) -> Cow<'static, str> {
    match event {
        EventType::SessionStart => Cow::Borrowed("SessionStart"),
        EventType::SessionEnd => Cow::Borrowed("SessionEnd"),
        EventType::PreToolUse => Cow::Borrowed("BeforeTool"),
        EventType::PostToolUse => Cow::Borrowed("AfterTool"),
        EventType::UserPromptSubmit => Cow::Borrowed("BeforeAgent"),
        EventType::PreCompact => Cow::Borrowed("PreCompress"),
        EventType::Notification => Cow::Borrowed("Notification"),
        // Map Stop to AfterAgent - both indicate agent finished processing
        EventType::Stop => Cow::Borrowed("AfterAgent"),
        // Events that don't have a Gemini equivalent use their canonical name
        EventType::PermissionRequest => Cow::Borrowed("PermissionRequest"),
        EventType::SubagentStop => Cow::Borrowed("SubagentStop"),
        EventType::ApiRequest => Cow::Borrowed("ApiRequest"),
        EventType::Custom(s) => Cow::Owned(s.clone()),
    }
}

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

    #[test]
    fn test_name() {
        let adapter = GeminiAdapter;
        assert_eq!(adapter.name(), "gemini");
        assert_eq!(adapter.display_name(), "Gemini CLI");
    }

    #[test]
    fn test_project_config_path() {
        let adapter = GeminiAdapter;
        assert_eq!(
            adapter.project_config_path(),
            PathBuf::from(".gemini/settings.json")
        );
    }

    #[test]
    fn test_map_event_type() {
        let adapter = GeminiAdapter;
        // Gemini-specific mappings
        assert_eq!(adapter.map_event_type("BeforeTool"), EventType::PreToolUse);
        assert_eq!(adapter.map_event_type("AfterTool"), EventType::PostToolUse);
        assert_eq!(
            adapter.map_event_type("BeforeAgent"),
            EventType::UserPromptSubmit
        );
        // AfterAgent maps to Stop (both indicate agent finished processing)
        assert_eq!(adapter.map_event_type("AfterAgent"), EventType::Stop);
        assert_eq!(adapter.map_event_type("PreCompress"), EventType::PreCompact);
        // Direct mappings
        assert_eq!(
            adapter.map_event_type("SessionStart"),
            EventType::SessionStart
        );
        assert_eq!(adapter.map_event_type("SessionEnd"), EventType::SessionEnd);
        assert_eq!(
            adapter.map_event_type("Notification"),
            EventType::Notification
        );
        // Model events become Custom
        assert_eq!(
            adapter.map_event_type("BeforeModel"),
            EventType::Custom("BeforeModel".to_string())
        );
        assert_eq!(
            adapter.map_event_type("AfterModel"),
            EventType::Custom("AfterModel".to_string())
        );
    }

    #[test]
    fn test_parse_hook_input() {
        let adapter = GeminiAdapter;
        let input = serde_json::json!({
            "session_id": "gemini-session-123",
            "tool_use_id": "tool-456",
            "tool_name": "write_file",
            "cwd": "/home/user/project",
            "transcript_path": "/tmp/transcript.jsonl",
            "tool_input": {
                "file_path": "/tmp/test.txt",
                "content": "hello"
            }
        });

        let parsed = adapter.parse_hook_input("BeforeTool", &input);

        assert_eq!(parsed.session_id, Some("gemini-session-123".to_string()));
        assert_eq!(parsed.tool_use_id, Some("tool-456".to_string()));
        assert_eq!(parsed.tool_name, Some("write_file".to_string()));
        assert_eq!(parsed.cwd, Some("/home/user/project".to_string()));
        assert_eq!(
            parsed.transcript_path,
            Some("/tmp/transcript.jsonl".to_string())
        );
        // Verify that permission_mode and spawned_agent_id are not extracted
        assert_eq!(parsed.permission_mode, None);
        assert_eq!(parsed.spawned_agent_id, None);
    }

    #[test]
    fn test_parse_hook_input_with_subagent_type() {
        let adapter = GeminiAdapter;
        let input = serde_json::json!({
            "session_id": "gemini-123",
            "tool_input": {
                "subagent_type": "Explore"
            }
        });

        let parsed = adapter.parse_hook_input("BeforeTool", &input);

        assert_eq!(parsed.session_id, Some("gemini-123".to_string()));
        assert_eq!(parsed.subagent_type, Some("Explore".to_string()));
    }

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

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

        let hooks = config
            .get("hooks")
            .ok_or("missing hooks")?
            .as_object()
            .ok_or("hooks not an object")?;
        // Should use Gemini event names
        assert!(hooks.contains_key("SessionStart"));
        assert!(hooks.contains_key("BeforeTool")); // PreToolUse -> BeforeTool

        let before_tool = &hooks["BeforeTool"][0]["hooks"][0];
        let command = before_tool["command"].as_str().ok_or("missing command")?;
        assert!(command.contains("fyi log BeforeTool"));
        // Should include explicit --framework flag
        assert!(command.contains("--framework gemini"));
        // Type should be "command"
        assert_eq!(
            before_tool["type"].as_str().ok_or("missing type")?,
            "command"
        );
        // Timeout should be in milliseconds
        assert_eq!(
            before_tool["timeout"].as_i64().ok_or("missing timeout")?,
            10000
        );

        // Should also include framework-specific events
        assert!(
            hooks.contains_key("BeforeModel"),
            "Framework-specific BeforeModel should be included"
        );
        assert!(
            hooks.contains_key("AfterModel"),
            "Framework-specific AfterModel should be included"
        );
        assert!(
            hooks.contains_key("BeforeToolSelection"),
            "Framework-specific BeforeToolSelection should be included"
        );
        Ok(())
    }

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

        assert!(events.contains(&"BeforeModel"));
        assert!(events.contains(&"AfterModel"));
        assert!(events.contains(&"BeforeToolSelection"));
        assert_eq!(events.len(), 3);
    }

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

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

        let hooks = config
            .get("hooks")
            .ok_or("missing hooks")?
            .as_object()
            .ok_or("hooks not an object")?;
        let session_start = &hooks["SessionStart"][0]["hooks"][0];
        let command = session_start["command"].as_str().ok_or("missing command")?;

        assert!(command.contains("otel start"));
        assert!(command.contains("--port 4318"));
        assert!(command.contains("--framework gemini"));
        Ok(())
    }

    #[test]
    fn test_merge_config_new() {
        let adapter = GeminiAdapter;
        let generated = serde_json::json!({
            "hooks": {
                "BeforeTool": [{"matcher": "", "hooks": []}]
            }
        });

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

        assert!(merged.get("hooks").is_some());
        assert!(merged["hooks"].get("BeforeTool").is_some());
    }

    #[test]
    fn test_merge_config_existing() {
        let adapter = GeminiAdapter;
        let generated = serde_json::json!({
            "hooks": {
                "BeforeTool": [{"matcher": "", "hooks": [{"command": "fyi log BeforeTool"}]}]
            }
        });
        let existing = serde_json::json!({
            "theme": "dark",
            "hooks": {
                "SessionStart": [{"matcher": "", "hooks": [{"command": "other-tool"}]}]
            }
        });

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

        // Should preserve existing settings
        assert_eq!(merged["theme"], "dark");
        // Should merge hooks
        assert!(merged["hooks"].get("SessionStart").is_some());
        assert!(merged["hooks"].get("BeforeTool").is_some());
    }

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

        assert!(events.contains(&"SessionStart"));
        assert!(events.contains(&"BeforeTool"));
        assert!(events.contains(&"AfterTool"));
        assert!(events.contains(&"BeforeModel"));
        assert!(events.contains(&"AfterModel"));
    }

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

        assert!(vars.contains(&"GEMINI_SESSION_ID"));
        assert!(vars.contains(&"GEMINI_PROJECT_DIR"));
    }
}