git-iris 2.0.8

AI-powered Git workflow assistant for smart commits, code reviews, changelogs, and release notes
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Agent setup service for Git-Iris
//!
//! This service handles all the setup and initialization for the agent framework,
//! including configuration loading, client creation, and agent setup.

use anyhow::Result;
use std::sync::Arc;

use crate::agents::context::TaskContext;
use crate::agents::iris::StructuredResponse;
use crate::agents::tools::with_active_repo_root;
use crate::agents::{AgentBackend, IrisAgent, IrisAgentBuilder};
use crate::common::CommonParams;
use crate::config::Config;
use crate::git::GitRepo;
use crate::providers::Provider;

/// Service for setting up agents with proper configuration
pub struct AgentSetupService {
    config: Config,
    git_repo: Option<GitRepo>,
}

impl AgentSetupService {
    /// Create a new setup service with the given configuration
    #[must_use]
    pub fn new(config: Config) -> Self {
        Self {
            config,
            git_repo: None,
        }
    }

    /// Create setup service from common parameters (following existing patterns)
    ///
    /// # Errors
    ///
    /// Returns an error when config loading, argument application, or repository setup fails.
    pub fn from_common_params(
        common_params: &CommonParams,
        repository_url: Option<String>,
    ) -> Result<Self> {
        let mut config = Config::load()?;

        // Apply common parameters to config (following existing pattern)
        common_params.apply_to_config(&mut config)?;

        let mut setup_service = Self::new(config);

        // Setup git repo if needed
        if let Some(repo_url) = repository_url {
            // Handle remote repository setup (following existing pattern)
            setup_service.git_repo = Some(GitRepo::new_from_url(Some(repo_url))?);
        } else {
            // Use local repository
            setup_service.git_repo = Some(GitRepo::new(&std::env::current_dir()?)?);
        }

        Ok(setup_service)
    }

    /// Create a configured Iris agent
    ///
    /// # Errors
    ///
    /// Returns an error when provider validation or agent construction fails.
    pub fn create_iris_agent(&mut self) -> Result<IrisAgent> {
        let backend = AgentBackend::from_config(&self.config)?;
        // Validate environment (API keys etc) before creating agent
        self.validate_provider(&backend)?;

        let mut agent = IrisAgentBuilder::new()
            .with_provider(&backend.provider_name)
            .with_model(&backend.model)
            .build()?;

        // Pass config and fast model to agent
        agent.set_config(self.config.clone());
        agent.set_fast_model(backend.fast_model);

        Ok(agent)
    }

    /// Validate provider configuration (API keys etc)
    fn validate_provider(&self, backend: &AgentBackend) -> Result<()> {
        let provider: Provider = backend
            .provider_name
            .parse()
            .map_err(|_| anyhow::anyhow!("Unsupported provider: {}", backend.provider_name))?;

        // Check API key - from config or environment
        let has_api_key = self
            .config
            .get_provider_config(provider.name())
            .is_some_and(crate::providers::ProviderConfig::has_api_key);

        if !has_api_key && std::env::var(provider.api_key_env()).is_err() {
            return Err(anyhow::anyhow!(
                "No API key found for {}. Set {} or configure in ~/.config/git-iris/config.toml",
                provider.name(),
                provider.api_key_env()
            ));
        }

        Ok(())
    }

    /// Get the git repository instance
    #[must_use]
    pub fn git_repo(&self) -> Option<&GitRepo> {
        self.git_repo.as_ref()
    }

    /// Get the configuration
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.config
    }
}

/// High-level function to handle tasks with agents using a common pattern
/// This is a convenience function that sets up an agent and executes a task
///
/// # Errors
///
/// Returns an error when setup, agent execution, or the caller-provided handler fails.
pub async fn handle_with_agent<F, Fut, T>(
    common_params: CommonParams,
    repository_url: Option<String>,
    capability: &str,
    task_prompt: &str,
    handler: F,
) -> Result<T>
where
    F: FnOnce(crate::agents::iris::StructuredResponse) -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    // Create setup service
    let mut setup_service = AgentSetupService::from_common_params(&common_params, repository_url)?;

    // Create agent
    let mut agent = setup_service.create_iris_agent()?;

    // Execute task with capability - now returns StructuredResponse
    let result = agent.execute_task(capability, task_prompt).await?;

    // Call the handler with the result
    handler(result).await
}

/// Simple factory function for creating agents with minimal configuration
///
/// # Errors
///
/// Returns an error when the provider configuration is invalid or agent construction fails.
pub fn create_agent_with_defaults(provider: &str, model: &str) -> Result<IrisAgent> {
    IrisAgentBuilder::new()
        .with_provider(provider)
        .with_model(model)
        .build()
}

/// Create an agent from environment variables
///
/// # Errors
///
/// Returns an error when agent construction fails.
pub fn create_agent_from_env() -> Result<IrisAgent> {
    let provider_str = std::env::var("IRIS_PROVIDER").unwrap_or_else(|_| "openai".to_string());
    let provider: Provider = provider_str.parse().unwrap_or_default();

    let model =
        std::env::var("IRIS_MODEL").unwrap_or_else(|_| provider.default_model().to_string());

    create_agent_with_defaults(provider.name(), &model)
}

// =============================================================================
// IrisAgentService - The primary interface for agent task execution
// =============================================================================

/// High-level service for executing agent tasks with structured context.
///
/// This is the primary interface for all agent-based operations in git-iris.
/// It handles:
/// - Configuration management
/// - Agent lifecycle
/// - Task context validation and formatting
/// - Environment validation
///
/// # Example
/// ```ignore
/// let service = IrisAgentService::from_common_params(&params, None)?;
/// let context = TaskContext::for_gen();
/// let result = service.execute_task("commit", context).await?;
/// ```
pub struct IrisAgentService {
    config: Config,
    git_repo: Option<Arc<GitRepo>>,
    provider: String,
    model: String,
    fast_model: String,
}

impl IrisAgentService {
    /// Create a new service with explicit provider configuration
    #[must_use]
    pub fn new(config: Config, provider: String, model: String, fast_model: String) -> Self {
        Self {
            config,
            git_repo: None,
            provider,
            model,
            fast_model,
        }
    }

    /// Create service from common CLI parameters
    ///
    /// This is the primary constructor for CLI usage. It:
    /// - Loads and applies configuration
    /// - Sets up the git repository (local or remote)
    /// - Validates the environment
    ///
    /// # Errors
    ///
    /// Returns an error when config loading, agent backend resolution, or repository setup fails.
    pub fn from_common_params(
        common_params: &CommonParams,
        repository_url: Option<String>,
    ) -> Result<Self> {
        let mut config = Config::load()?;
        common_params.apply_to_config(&mut config)?;

        // Determine backend (provider/model) from config
        let backend = AgentBackend::from_config(&config)?;

        let mut service = Self::new(
            config,
            backend.provider_name,
            backend.model,
            backend.fast_model,
        );

        // Setup git repo
        if let Some(repo_url) = repository_url {
            service.git_repo = Some(Arc::new(GitRepo::new_from_url(Some(repo_url))?));
        } else {
            service.git_repo = Some(Arc::new(GitRepo::new(&std::env::current_dir()?)?));
        }

        Ok(service)
    }

    /// Check that the environment is properly configured
    ///
    /// # Errors
    ///
    /// Returns an error when the active provider configuration is incomplete.
    pub fn check_environment(&self) -> Result<()> {
        self.config.check_environment()
    }

    /// Execute an agent task with structured context
    ///
    /// # Arguments
    /// * `capability` - The capability to invoke (e.g., "commit", "review", "pr")
    /// * `context` - Structured context describing what to analyze
    ///
    /// # Returns
    /// The structured response from the agent
    ///
    /// # Errors
    ///
    /// Returns an error when agent construction or task execution fails.
    pub async fn execute_task(
        &self,
        capability: &str,
        context: TaskContext,
    ) -> Result<StructuredResponse> {
        let run_task = async {
            let mut agent = self.create_agent()?;
            let task_prompt = Self::build_task_prompt(
                capability,
                &context,
                self.config.temp_instructions.as_deref(),
            );
            agent.execute_task(capability, &task_prompt).await
        };

        if let Some(repo) = &self.git_repo {
            with_active_repo_root(repo.repo_path(), run_task).await
        } else {
            run_task.await
        }
    }

    /// Execute a task with a custom prompt (for backwards compatibility)
    ///
    /// # Errors
    ///
    /// Returns an error when agent construction or task execution fails.
    pub async fn execute_task_with_prompt(
        &self,
        capability: &str,
        task_prompt: &str,
    ) -> Result<StructuredResponse> {
        let run_task = async {
            let mut agent = self.create_agent()?;
            agent.execute_task(capability, task_prompt).await
        };

        if let Some(repo) = &self.git_repo {
            with_active_repo_root(repo.repo_path(), run_task).await
        } else {
            run_task.await
        }
    }

    /// Execute an agent task with style overrides
    ///
    /// Allows runtime override of preset and gitmoji settings without
    /// modifying the underlying config. Useful for UI flows where the
    /// user can change settings per-invocation.
    ///
    /// # Arguments
    /// * `capability` - The capability to invoke
    /// * `context` - Structured context describing what to analyze
    /// * `preset` - Optional preset name override (e.g., "conventional", "cosmic")
    /// * `use_gitmoji` - Optional gitmoji setting override
    /// * `instructions` - Optional custom instructions from the user
    ///
    /// # Errors
    ///
    /// Returns an error when agent construction or task execution fails.
    pub async fn execute_task_with_style(
        &self,
        capability: &str,
        context: TaskContext,
        preset: Option<&str>,
        use_gitmoji: Option<bool>,
        instructions: Option<&str>,
    ) -> Result<StructuredResponse> {
        let run_task = async {
            let mut config = self.config.clone();
            if let Some(p) = preset {
                config.temp_preset = Some(p.to_string());
            }
            if let Some(gitmoji) = use_gitmoji {
                config.use_gitmoji = gitmoji;
            }

            let mut agent = IrisAgentBuilder::new()
                .with_provider(&self.provider)
                .with_model(&self.model)
                .build()?;
            agent.set_config(config);
            agent.set_fast_model(self.fast_model.clone());

            let task_prompt = Self::build_task_prompt(capability, &context, instructions);
            agent.execute_task(capability, &task_prompt).await
        };

        if let Some(repo) = &self.git_repo {
            with_active_repo_root(repo.repo_path(), run_task).await
        } else {
            run_task.await
        }
    }

    /// Build a task prompt incorporating the context information and optional instructions
    fn build_task_prompt(
        capability: &str,
        context: &TaskContext,
        instructions: Option<&str>,
    ) -> String {
        let context_json = context.to_prompt_context();
        let diff_hint = context.diff_hint();

        // Build instruction suffix if provided
        let instruction_suffix = instructions
            .filter(|i| !i.trim().is_empty())
            .map(|i| format!("\n\n## Custom Instructions\n{}", i))
            .unwrap_or_default();

        // Extract version and date info if this is a Changelog context
        let version_info = if let TaskContext::Changelog {
            version_name, date, ..
        } = context
        {
            let version_str = version_name
                .as_ref()
                .map_or_else(|| "(derive from git refs)".to_string(), String::clone);
            format!(
                "\n\n## Version Information\n- Version: {}\n- Release Date: {}\n\nIMPORTANT: Use the exact version name and date provided above. Do NOT guess or make up version numbers or dates.",
                version_str, date
            )
        } else {
            String::new()
        };

        match capability {
            "commit" => format!(
                "Generate a commit message for the following context:\n{}\n\nUse: {}{}",
                context_json, diff_hint, instruction_suffix
            ),
            "review" => format!(
                "Review the code changes for the following context:\n{}\n\nUse: {}{}",
                context_json, diff_hint, instruction_suffix
            ),
            "pr" => format!(
                "Generate a pull request description for:\n{}\n\nUse: {}{}",
                context_json, diff_hint, instruction_suffix
            ),
            "changelog" => format!(
                "Generate a changelog for:\n{}\n\nUse: {}{}{}",
                context_json, diff_hint, version_info, instruction_suffix
            ),
            "release_notes" => format!(
                "Generate release notes for:\n{}\n\nUse: {}{}{}",
                context_json, diff_hint, version_info, instruction_suffix
            ),
            _ => format!(
                "Execute task with context:\n{}\n\nHint: {}{}",
                context_json, diff_hint, instruction_suffix
            ),
        }
    }

    /// Create a configured Iris agent
    fn create_agent(&self) -> Result<IrisAgent> {
        let mut agent = IrisAgentBuilder::new()
            .with_provider(&self.provider)
            .with_model(&self.model)
            .build()?;

        // Pass config and fast model to agent
        agent.set_config(self.config.clone());
        agent.set_fast_model(self.fast_model.clone());

        Ok(agent)
    }

    /// Create a configured Iris agent with content update tools (for Studio chat)
    fn create_agent_with_content_updates(
        &self,
        sender: crate::agents::tools::ContentUpdateSender,
    ) -> Result<IrisAgent> {
        let mut agent = self.create_agent()?;
        agent.set_content_update_sender(sender);
        Ok(agent)
    }

    /// Execute a chat task with content update capabilities
    ///
    /// This is used by Studio to enable Iris to update content via tool calls.
    ///
    /// # Errors
    ///
    /// Returns an error when agent construction or chat execution fails.
    pub async fn execute_chat_with_updates(
        &self,
        task_prompt: &str,
        content_update_sender: crate::agents::tools::ContentUpdateSender,
    ) -> Result<StructuredResponse> {
        let run_task = async {
            let mut agent = self.create_agent_with_content_updates(content_update_sender)?;
            agent.execute_task("chat", task_prompt).await
        };

        if let Some(repo) = &self.git_repo {
            with_active_repo_root(repo.repo_path(), run_task).await
        } else {
            run_task.await
        }
    }

    /// Execute a chat task with streaming and content update capabilities
    ///
    /// Combines streaming output with tool-based content updates for the TUI chat.
    ///
    /// # Errors
    ///
    /// Returns an error when agent construction or chat streaming fails.
    pub async fn execute_chat_streaming<F>(
        &self,
        task_prompt: &str,
        content_update_sender: crate::agents::tools::ContentUpdateSender,
        on_chunk: F,
    ) -> Result<StructuredResponse>
    where
        F: FnMut(&str, &str) + Send,
    {
        let run_task = async {
            let mut agent = self.create_agent_with_content_updates(content_update_sender)?;
            agent
                .execute_task_streaming("chat", task_prompt, on_chunk)
                .await
        };

        if let Some(repo) = &self.git_repo {
            with_active_repo_root(repo.repo_path(), run_task).await
        } else {
            run_task.await
        }
    }

    /// Execute an agent task with streaming
    ///
    /// This method streams LLM output in real-time, calling the callback with each
    /// text chunk as it arrives. Ideal for TUI display of generation progress.
    ///
    /// # Arguments
    /// * `capability` - The capability to invoke (e.g., "review", "pr", "changelog")
    /// * `context` - Structured context describing what to analyze
    /// * `on_chunk` - Callback receiving `(chunk, aggregated_text)` for each delta
    ///
    /// # Returns
    /// The final structured response after streaming completes
    ///
    /// # Errors
    ///
    /// Returns an error when agent construction or streaming execution fails.
    pub async fn execute_task_streaming<F>(
        &self,
        capability: &str,
        context: TaskContext,
        on_chunk: F,
    ) -> Result<StructuredResponse>
    where
        F: FnMut(&str, &str) + Send,
    {
        let run_task = async {
            let mut agent = self.create_agent()?;
            let task_prompt = Self::build_task_prompt(
                capability,
                &context,
                self.config.temp_instructions.as_deref(),
            );
            agent
                .execute_task_streaming(capability, &task_prompt, on_chunk)
                .await
        };

        if let Some(repo) = &self.git_repo {
            with_active_repo_root(repo.repo_path(), run_task).await
        } else {
            run_task.await
        }
    }

    /// Get the configuration
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Get a mutable reference to the configuration
    pub fn config_mut(&mut self) -> &mut Config {
        &mut self.config
    }

    /// Attach a git repository to this service
    pub fn set_git_repo(&mut self, repo: GitRepo) {
        self.git_repo = Some(Arc::new(repo));
    }

    /// Get the git repository if available
    #[must_use]
    pub fn git_repo(&self) -> Option<&Arc<GitRepo>> {
        self.git_repo.as_ref()
    }

    /// Get the provider name
    #[must_use]
    pub fn provider(&self) -> &str {
        &self.provider
    }

    /// Get the model name
    #[must_use]
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Get the fast model name (for subagents and simple tasks)
    #[must_use]
    pub fn fast_model(&self) -> &str {
        &self.fast_model
    }

    /// Get the API key for the current provider from config
    #[must_use]
    pub fn api_key(&self) -> Option<String> {
        self.config
            .get_provider_config(&self.provider)
            .and_then(|pc| pc.api_key_if_set())
            .map(String::from)
    }
}