ccswarm 0.5.0

AI-powered multi-agent orchestration system with proactive intelligence, security monitoring, and session management
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
pub mod aider;
pub mod claude_api;
pub mod claude_code;
pub mod codex;
pub mod custom;

use anyhow::Result;
use async_trait::async_trait;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use tokio::process::Command;

use crate::agent::{Task, TaskResult};
use crate::identity::AgentIdentity;
use std::path::Path;

// ============================================================================
// Sensitive String Handling
// ============================================================================

/// A wrapper around sensitive string data (like API keys) that:
/// - Prevents accidental logging via custom Debug implementation
/// - Supports Clone, Serialize, Deserialize for config compatibility
/// - Uses secrecy::SecretString internally for memory safety
///
/// # Example
/// ```rust,ignore
/// let api_key = SensitiveString::new("sk-secret-key");
/// println!("{:?}", api_key); // Prints: SensitiveString(****)
/// let actual = api_key.expose(); // Get the actual value when needed
/// ```
#[derive(Clone)]
pub struct SensitiveString(SecretString);

impl SensitiveString {
    /// Create a new SensitiveString from a string
    pub fn new(value: impl Into<String>) -> Self {
        Self(SecretString::new(value.into().into()))
    }

    /// Expose the secret value. Use sparingly and only when necessary.
    pub fn expose(&self) -> &str {
        self.0.expose_secret()
    }

    /// Check if the underlying value is empty
    pub fn is_empty(&self) -> bool {
        self.0.expose_secret().is_empty()
    }
}

impl std::fmt::Debug for SensitiveString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SensitiveString(****)")
    }
}

impl std::fmt::Display for SensitiveString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "****")
    }
}

impl Serialize for SensitiveString {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // Never serialize the actual secret - serialize a placeholder
        serializer.serialize_str("[REDACTED]")
    }
}

impl<'de> Deserialize<'de> for SensitiveString {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        // If it's the placeholder, treat as empty (user should set via env var)
        if s == "[REDACTED]" {
            Ok(Self::new(""))
        } else {
            Ok(Self::new(s))
        }
    }
}

impl Default for SensitiveString {
    fn default() -> Self {
        Self::new("")
    }
}

impl From<String> for SensitiveString {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

impl From<&str> for SensitiveString {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

/// Supported AI providers for ccswarm agents
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum AIProvider {
    /// Claude Code (default)
    #[default]
    ClaudeCode,
    /// Aider AI coding assistant
    Aider,
    /// OpenAI Codex
    Codex,
    /// Custom command-based provider
    Custom,
}

impl AIProvider {
    /// Get display name for the provider
    pub fn display_name(&self) -> &'static str {
        match self {
            AIProvider::ClaudeCode => "Claude Code",
            AIProvider::Aider => "Aider",
            AIProvider::Codex => "OpenAI Codex",
            AIProvider::Custom => "Custom",
        }
    }

    /// Get provider color for UI display
    pub fn color(&self) -> &'static str {
        match self {
            AIProvider::ClaudeCode => "blue",
            AIProvider::Aider => "green",
            AIProvider::Codex => "purple",
            AIProvider::Custom => "gray",
        }
    }

    /// Get provider icon for UI display
    pub fn icon(&self) -> &'static str {
        match self {
            AIProvider::ClaudeCode => "🤖",
            AIProvider::Aider => "🔧",
            AIProvider::Codex => "🧠",
            AIProvider::Custom => "⚙️",
        }
    }
}

/// Common configuration trait for all providers
#[async_trait]
pub trait ProviderConfig: Send + Sync + Clone {
    /// Validate the provider configuration
    async fn validate(&self) -> Result<()>;

    /// Get environment variables needed for this provider
    fn get_env_vars(&self) -> HashMap<String, String>;

    /// Get working directory for this provider
    fn get_working_directory(&self) -> Option<PathBuf>;

    /// Check if provider is available on the system
    async fn is_available(&self) -> bool;
}

/// Provider execution trait for running tasks
#[async_trait]
pub trait ProviderExecutor: Send + Sync {
    /// Execute a prompt with the provider
    async fn execute_prompt(
        &self,
        prompt: &str,
        identity: &AgentIdentity,
        working_dir: &Path,
    ) -> Result<String>;

    /// Execute a task with full context
    async fn execute_task(
        &self,
        task: &Task,
        identity: &AgentIdentity,
        working_dir: &Path,
    ) -> Result<TaskResult>;

    /// Test provider connectivity and functionality
    async fn health_check(&self, working_dir: &Path) -> Result<ProviderHealthStatus>;

    /// Get provider-specific capabilities
    fn get_capabilities(&self) -> ProviderCapabilities;
}

/// Provider health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderHealthStatus {
    pub is_healthy: bool,
    pub version: Option<String>,
    pub last_check: chrono::DateTime<chrono::Utc>,
    pub error_message: Option<String>,
    pub response_time_ms: Option<u64>,
}

/// Provider capabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderCapabilities {
    pub supports_json_output: bool,
    pub supports_streaming: bool,
    pub supports_file_operations: bool,
    pub supports_git_operations: bool,
    pub supports_code_execution: bool,
    pub max_context_length: Option<usize>,
    pub supported_languages: Vec<String>,
}

/// Output format for Claude Code CLI
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub enum OutputFormat {
    /// Plain text output
    #[default]
    Text,
    /// Structured JSON output with metadata
    Json,
    /// Streaming JSON output (each message as separate JSON object)
    StreamJson,
}

impl OutputFormat {
    /// Convert to CLI argument value
    pub fn as_cli_arg(&self) -> &'static str {
        match self {
            OutputFormat::Text => "text",
            OutputFormat::Json => "json",
            OutputFormat::StreamJson => "stream-json",
        }
    }
}

/// Claude Code provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeCodeConfig {
    /// Model to use (aliases: "sonnet", "opus", "haiku", "opusplan", or full model name)
    pub model: String,
    /// Whether to skip permission prompts
    pub dangerous_skip: bool,
    /// Output format: "text", "json", or "stream-json"
    pub output_format: OutputFormat,
    /// Append to system prompt (recommended over replacing)
    pub append_system_prompt: Option<String>,
    /// Custom commands available
    pub custom_commands: Vec<String>,
    /// MCP servers configuration
    pub mcp_servers: HashMap<String, serde_json::Value>,
    /// API key (optional, uses system default if not provided)
    /// Note: Uses SensitiveString to prevent accidental logging
    pub api_key: Option<SensitiveString>,
    /// Session ID for resuming conversations
    pub session_id: Option<String>,
    /// Resume a specific session
    pub resume_session: Option<String>,
    /// Continue most recent conversation
    pub continue_session: bool,
    /// Fork session instead of reusing original
    pub fork_session: bool,
    /// Maximum agentic turns in non-interactive mode
    pub max_turns: Option<u32>,
    /// Fallback model when primary is overloaded
    pub fallback_model: Option<String>,
    /// Allowed tools (whitelist)
    pub allowed_tools: Vec<String>,
    /// Disallowed tools (blacklist)
    pub disallowed_tools: Vec<String>,
    /// Enable verbose logging
    pub verbose: bool,
    /// Enable MCP debug mode
    pub mcp_debug: bool,
}

impl Default for ClaudeCodeConfig {
    fn default() -> Self {
        Self {
            model: "sonnet".to_string(), // Use model alias (recommended)
            dangerous_skip: false,
            output_format: OutputFormat::Json,
            append_system_prompt: None,
            custom_commands: Vec::new(),
            mcp_servers: HashMap::new(),
            api_key: None,
            session_id: None,
            resume_session: None,
            continue_session: false,
            fork_session: false,
            max_turns: None,
            fallback_model: None,
            allowed_tools: Vec::new(),
            disallowed_tools: Vec::new(),
            verbose: false,
            mcp_debug: false,
        }
    }
}

#[async_trait]
impl ProviderConfig for ClaudeCodeConfig {
    async fn validate(&self) -> Result<()> {
        // Check if claude command is available
        if !self.is_available().await {
            return Err(anyhow::anyhow!("Claude Code CLI not found in PATH"));
        }

        // Validate model name
        if self.model.is_empty() {
            return Err(anyhow::anyhow!("Model name cannot be empty"));
        }

        Ok(())
    }

    fn get_env_vars(&self) -> HashMap<String, String> {
        let mut env_vars = HashMap::new();

        if let Some(api_key) = &self.api_key {
            env_vars.insert(
                "ANTHROPIC_API_KEY".to_string(),
                api_key.expose().to_string(),
            );
        }

        env_vars
    }

    fn get_working_directory(&self) -> Option<PathBuf> {
        None // Claude Code uses current directory
    }

    async fn is_available(&self) -> bool {
        Command::new("claude")
            .arg("--version")
            .env_remove("CLAUDECODE")
            .env_remove("CLAUDE_CODE_ENTRYPOINT")
            .output()
            .await
            .map(|output| output.status.success())
            .unwrap_or(false)
    }
}

/// Aider provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiderConfig {
    /// Model to use (e.g., "gpt-4", "claude-3.5-sonnet")
    pub model: String,
    /// OpenAI API key (uses SensitiveString to prevent accidental logging)
    pub openai_api_key: Option<SensitiveString>,
    /// Anthropic API key (uses SensitiveString to prevent accidental logging)
    pub anthropic_api_key: Option<SensitiveString>,
    /// Auto-commit changes
    pub auto_commit: bool,
    /// Use git for version control
    pub git: bool,
    /// Additional aider arguments
    pub additional_args: Vec<String>,
    /// Aider executable path
    pub executable_path: Option<PathBuf>,
}

impl Default for AiderConfig {
    fn default() -> Self {
        Self {
            model: "gpt-4".to_string(),
            openai_api_key: None,
            anthropic_api_key: None,
            auto_commit: true,
            git: true,
            additional_args: Vec::new(),
            executable_path: None,
        }
    }
}

#[async_trait]
impl ProviderConfig for AiderConfig {
    async fn validate(&self) -> Result<()> {
        // Check if aider is available
        if !self.is_available().await {
            return Err(anyhow::anyhow!("Aider not found in PATH"));
        }

        // Check API keys based on model
        if self.model.starts_with("gpt-") && self.openai_api_key.is_none() {
            return Err(anyhow::anyhow!("OpenAI API key required for GPT models"));
        }

        if self.model.starts_with("claude-") && self.anthropic_api_key.is_none() {
            return Err(anyhow::anyhow!(
                "Anthropic API key required for Claude models"
            ));
        }

        Ok(())
    }

    fn get_env_vars(&self) -> HashMap<String, String> {
        let mut env_vars = HashMap::new();

        if let Some(openai_key) = &self.openai_api_key {
            env_vars.insert(
                "OPENAI_API_KEY".to_string(),
                openai_key.expose().to_string(),
            );
        }

        if let Some(anthropic_key) = &self.anthropic_api_key {
            env_vars.insert(
                "ANTHROPIC_API_KEY".to_string(),
                anthropic_key.expose().to_string(),
            );
        }

        env_vars
    }

    fn get_working_directory(&self) -> Option<PathBuf> {
        None // Aider uses current directory
    }

    async fn is_available(&self) -> bool {
        let cmd = if let Some(path) = &self.executable_path {
            path.to_string_lossy().to_string()
        } else {
            "aider".to_string()
        };

        Command::new(&cmd)
            .arg("--version")
            .output()
            .await
            .map(|output| output.status.success())
            .unwrap_or(false)
    }
}

/// OpenAI Codex provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodexConfig {
    /// OpenAI API key (uses SensitiveString to prevent accidental logging)
    pub api_key: SensitiveString,
    /// Model to use (e.g., "code-davinci-002")
    pub model: String,
    /// Maximum tokens for completion
    pub max_tokens: Option<u32>,
    /// Temperature for generation
    pub temperature: Option<f32>,
    /// API base URL (for custom endpoints)
    pub api_base: Option<String>,
    /// Organization ID
    pub organization: Option<String>,
    /// Enable JSON mode for structured output
    pub json_mode: Option<bool>,
    /// Enable streaming responses
    pub stream: Option<bool>,
}

impl Default for CodexConfig {
    fn default() -> Self {
        Self {
            api_key: SensitiveString::new(std::env::var("OPENAI_API_KEY").unwrap_or_default()),
            model: "gpt-4".to_string(), // Codex models are deprecated, using GPT-4
            max_tokens: Some(2048),
            temperature: Some(0.1),
            api_base: None,
            organization: None,
            json_mode: None,
            stream: None,
        }
    }
}

#[async_trait]
impl ProviderConfig for CodexConfig {
    async fn validate(&self) -> Result<()> {
        if self.api_key.is_empty() {
            return Err(anyhow::anyhow!("OpenAI API key is required"));
        }

        if self.model.is_empty() {
            return Err(anyhow::anyhow!("Model name cannot be empty"));
        }

        // Validate temperature range
        if let Some(temp) = self.temperature
            && !(0.0..=1.0).contains(&temp)
        {
            return Err(anyhow::anyhow!("Temperature must be between 0.0 and 1.0"));
        }

        Ok(())
    }

    fn get_env_vars(&self) -> HashMap<String, String> {
        let mut env_vars = HashMap::new();

        env_vars.insert(
            "OPENAI_API_KEY".to_string(),
            self.api_key.expose().to_string(),
        );

        if let Some(org) = &self.organization {
            env_vars.insert("OPENAI_ORGANIZATION".to_string(), org.clone());
        }

        if let Some(base) = &self.api_base {
            env_vars.insert("OPENAI_API_BASE".to_string(), base.clone());
        }

        env_vars
    }

    fn get_working_directory(&self) -> Option<PathBuf> {
        None
    }

    async fn is_available(&self) -> bool {
        // Check if we can make API calls (simplified check)
        !self.api_key.is_empty()
    }
}

/// Custom provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomConfig {
    /// Command to execute
    pub command: String,
    /// Arguments template (use {prompt} placeholder)
    pub args: Vec<String>,
    /// Environment variables to set
    pub env_vars: HashMap<String, String>,
    /// Working directory
    pub working_directory: Option<PathBuf>,
    /// Timeout in seconds
    pub timeout_seconds: Option<u64>,
    /// Whether the command supports JSON output
    pub supports_json: bool,
}

impl Default for CustomConfig {
    fn default() -> Self {
        Self {
            command: "echo".to_string(),
            args: vec!["{prompt}".to_string()],
            env_vars: HashMap::new(),
            working_directory: None,
            timeout_seconds: Some(300), // 5 minutes
            supports_json: false,
        }
    }
}

#[async_trait]
impl ProviderConfig for CustomConfig {
    async fn validate(&self) -> Result<()> {
        if self.command.is_empty() {
            return Err(anyhow::anyhow!("Command cannot be empty"));
        }

        // Check if command exists
        if !self.is_available().await {
            return Err(anyhow::anyhow!("Command '{}' not found", self.command));
        }

        Ok(())
    }

    fn get_env_vars(&self) -> HashMap<String, String> {
        self.env_vars.clone()
    }

    fn get_working_directory(&self) -> Option<PathBuf> {
        self.working_directory.clone()
    }

    async fn is_available(&self) -> bool {
        Command::new(&self.command)
            .arg("--help")
            .output()
            .await
            .is_ok()
    }
}

/// Complete provider configuration combining all provider types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderConfiguration {
    pub provider_type: AIProvider,
    pub claude_code: Option<ClaudeCodeConfig>,
    pub aider: Option<AiderConfig>,
    pub codex: Option<CodexConfig>,
    pub custom: Option<CustomConfig>,
}

impl Default for ProviderConfiguration {
    fn default() -> Self {
        Self {
            provider_type: AIProvider::ClaudeCode,
            claude_code: Some(ClaudeCodeConfig::default()),
            aider: None,
            codex: None,
            custom: None,
        }
    }
}

impl ProviderConfiguration {
    /// Create a new provider configuration for Claude Code
    pub fn claude_code(config: ClaudeCodeConfig) -> Self {
        Self {
            provider_type: AIProvider::ClaudeCode,
            claude_code: Some(config),
            aider: None,
            codex: None,
            custom: None,
        }
    }

    /// Create a new provider configuration for Aider
    pub fn aider(config: AiderConfig) -> Self {
        Self {
            provider_type: AIProvider::Aider,
            claude_code: None,
            aider: Some(config),
            codex: None,
            custom: None,
        }
    }

    /// Create a new provider configuration for Codex
    pub fn codex(config: CodexConfig) -> Self {
        Self {
            provider_type: AIProvider::Codex,
            claude_code: None,
            aider: None,
            codex: Some(config),
            custom: None,
        }
    }

    /// Create a new provider configuration for Custom
    pub fn custom(config: CustomConfig) -> Self {
        Self {
            provider_type: AIProvider::Custom,
            claude_code: None,
            aider: None,
            codex: None,
            custom: Some(config),
        }
    }

    /// Validate the configuration
    pub async fn validate(&self) -> Result<()> {
        match self.provider_type {
            AIProvider::ClaudeCode => {
                if let Some(config) = &self.claude_code {
                    config.validate().await
                } else {
                    Err(anyhow::anyhow!("Claude Code configuration missing"))
                }
            }
            AIProvider::Aider => {
                if let Some(config) = &self.aider {
                    config.validate().await
                } else {
                    Err(anyhow::anyhow!("Aider configuration missing"))
                }
            }
            AIProvider::Codex => {
                if let Some(config) = &self.codex {
                    config.validate().await
                } else {
                    Err(anyhow::anyhow!("Codex configuration missing"))
                }
            }
            AIProvider::Custom => {
                if let Some(config) = &self.custom {
                    config.validate().await
                } else {
                    Err(anyhow::anyhow!("Custom configuration missing"))
                }
            }
        }
    }

    /// Get environment variables for the active provider
    pub fn get_env_vars(&self) -> HashMap<String, String> {
        match self.provider_type {
            AIProvider::ClaudeCode => self
                .claude_code
                .as_ref()
                .map(|c| c.get_env_vars())
                .unwrap_or_default(),
            AIProvider::Aider => self
                .aider
                .as_ref()
                .map(|c| c.get_env_vars())
                .unwrap_or_default(),
            AIProvider::Codex => self
                .codex
                .as_ref()
                .map(|c| c.get_env_vars())
                .unwrap_or_default(),
            AIProvider::Custom => self
                .custom
                .as_ref()
                .map(|c| c.get_env_vars())
                .unwrap_or_default(),
        }
    }

    /// Check if the provider is available
    pub async fn is_available(&self) -> bool {
        match self.provider_type {
            AIProvider::ClaudeCode => {
                if let Some(config) = &self.claude_code {
                    config.is_available().await
                } else {
                    false
                }
            }
            AIProvider::Aider => {
                if let Some(config) = &self.aider {
                    config.is_available().await
                } else {
                    false
                }
            }
            AIProvider::Codex => {
                if let Some(config) = &self.codex {
                    config.is_available().await
                } else {
                    false
                }
            }
            AIProvider::Custom => {
                if let Some(config) = &self.custom {
                    config.is_available().await
                } else {
                    false
                }
            }
        }
    }
}

/// Factory for creating provider executors
pub struct ProviderFactory;

impl ProviderFactory {
    /// Create a provider executor from configuration
    pub fn create_executor(config: &ProviderConfiguration) -> Result<Box<dyn ProviderExecutor>> {
        match config.provider_type {
            AIProvider::ClaudeCode => {
                if let Some(claude_config) = &config.claude_code {
                    Ok(Box::new(claude_code::ClaudeCodeExecutor::new(
                        claude_config.clone(),
                    )))
                } else {
                    Err(anyhow::anyhow!("Claude Code configuration missing"))
                }
            }
            AIProvider::Aider => {
                if let Some(aider_config) = &config.aider {
                    Ok(Box::new(aider::AiderExecutor::new(aider_config.clone())))
                } else {
                    Err(anyhow::anyhow!("Aider configuration missing"))
                }
            }
            AIProvider::Codex => {
                if let Some(codex_config) = &config.codex {
                    Ok(Box::new(codex::CodexExecutor::new(codex_config.clone())?))
                } else {
                    Err(anyhow::anyhow!("Codex configuration missing"))
                }
            }
            AIProvider::Custom => {
                if let Some(custom_config) = &config.custom {
                    Ok(Box::new(custom::CustomExecutor::new(custom_config.clone())))
                } else {
                    Err(anyhow::anyhow!("Custom configuration missing"))
                }
            }
        }
    }
}