File size: 11,344 Bytes
8b02e7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Configuration file generator for orchestrators and delegation rules.

This module generates YAML configuration files based on user selections
during installation.
"""

import logging
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any

import yaml
from rich.console import Console
from rich.prompt import Confirm

from ..agent_discovery import AgentMetadata
from .agent_profiles import get_agent_profile
from .task_mapper import TASK_CATEGORIES

logger = logging.getLogger(__name__)
console = Console()


class ConfigGenerator:
    """Generates configuration files based on user selections."""

    def __init__(self):
        """Initialize the config generator."""
        self.orchestrators_config: dict[str, Any] = {}
        self.delegation_config: dict[str, Any] = {}

    def check_existing_configs(self, project_dir: Path) -> bool:
        """
        Check if configuration files already exist.
        
        Args:
            project_dir: Project directory path
            
        Returns:
            True if configs exist, False otherwise
        """
        config_dir = project_dir / "config"
        orchestrators_file = config_dir / "orchestrators.yaml"
        delegation_file = config_dir / "delegation_rules.yaml"

        return orchestrators_file.exists() or delegation_file.exists()

    def prompt_existing_configs(self, project_dir: Path) -> str:
        """
        Prompt user for how to handle existing configs.
        
        Args:
            project_dir: Project directory path
            
        Returns:
            User choice: "overwrite", "backup", or "skip"
        """
        console.print("\n[yellow]⚠ Existing configuration detected[/yellow]")
        console.print("\nConfiguration files already exist in this project.")
        console.print("You can:")
        console.print("  [cyan]O[/cyan]verwrite - Replace existing files with new configuration")
        console.print("  [cyan]B[/cyan]ackup   - Backup existing files and create new ones")
        console.print("  [cyan]S[/cyan]kip     - Keep existing files unchanged\n")

        choice = ""
        while choice not in ["o", "b", "s"]:
            choice = input("Choose an option (O/B/S): ").lower().strip()

        choice_map = {"o": "overwrite", "b": "backup", "s": "skip"}
        return choice_map[choice]

    def backup_existing_configs(self, project_dir: Path) -> None:
        """
        Backup existing configuration files.
        
        Args:
            project_dir: Project directory path
        """
        config_dir = project_dir / "config"
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        files_to_backup = [
            "orchestrators.yaml",
            "delegation_rules.yaml",
        ]

        for filename in files_to_backup:
            source = config_dir / filename
            if source.exists():
                backup_name = f"{source.stem}.backup_{timestamp}{source.suffix}"
                backup_path = config_dir / backup_name
                shutil.copy2(source, backup_path)
                console.print(f"[green]✓[/green] Backed up {filename} to {backup_name}")

    def generate_orchestrators_yaml(
        self,
        selected_agents: list[str],
        agent_metadata: dict[str, AgentMetadata],
    ) -> dict[str, Any]:
        """
        Generate orchestrators.yaml configuration.
        
        Args:
            selected_agents: List of selected agent names
            agent_metadata: Dictionary of agent name to metadata
            
        Returns:
            Orchestrators configuration dictionary
        """
        config: dict[str, Any] = {"orchestrators": {}}

        for agent_name in selected_agents:
            metadata = agent_metadata.get(agent_name)
            if not metadata:
                continue

            # Get command and args from metadata
            # command can be a string or list[str]
            if isinstance(metadata.command, list):
                command = metadata.command[0] if metadata.command else agent_name
                args = metadata.command[1:] if len(metadata.command) > 1 else []
            else:
                command = metadata.command or agent_name
                args = []

            # Build orchestrator config
            orch_config: dict[str, Any] = {
                "name": agent_name,
                "command": command,
                "args": args,
                "enabled": True,
                "env": {},
                "timeout": 300,
                "max_retries": 3,
            }

            config["orchestrators"][agent_name] = orch_config

        self.orchestrators_config = config
        return config

    def generate_delegation_rules_yaml(
        self,
        selected_agents: list[str],
        task_mappings: dict[str, str],
        agent_metadata: dict[str, AgentMetadata],
        primary_orchestrator: str,
    ) -> dict[str, Any]:
        """
        Generate delegation_rules.yaml configuration.
        
        Args:
            selected_agents: List of selected agent names
            task_mappings: Dictionary of task_key -> agent_name
            agent_metadata: Dictionary of agent name to metadata
            primary_orchestrator: Name of primary orchestrator
            
        Returns:
            Delegation rules configuration dictionary
        """
        config: dict[str, Any] = {
            "orchestrator": primary_orchestrator,
            "routing_strategy": "hybrid",
            "orchestrators": {},
            "rules": [],
        }

        # Build orchestrators section with capabilities
        for agent_name in selected_agents:
            metadata = agent_metadata.get(agent_name)
            if not metadata:
                continue

            profile = get_agent_profile(agent_name)
            capabilities = profile["capabilities"]

            # Get command and args from metadata
            # command can be a string or list[str]
            if isinstance(metadata.command, list):
                command = metadata.command[0] if metadata.command else agent_name
                args = metadata.command[1:] if len(metadata.command) > 1 else []
            else:
                command = metadata.command or agent_name
                args = []

            orch_config: dict[str, Any] = {
                "name": agent_name,
                "command": command,
                "args": args,
                "enabled": True,
                "env": {},
                "timeout": 300,
                "max_retries": 3,
                "cost_per_1k_tokens": 0.001,
                "capabilities": dict(capabilities),
            }

            config["orchestrators"][agent_name] = orch_config

        # Build delegation rules from task mappings
        # Create task key to category mapping
        category_map = {cat["key"]: cat for cat in TASK_CATEGORIES}

        priority = 10  # Start with high priority
        for task_key, agent_name in task_mappings.items():
            category = category_map.get(task_key)
            if not category:
                continue

            # Build pattern from examples
            pattern_parts = category["pattern_examples"]
            pattern = "|".join(pattern_parts)

            rule: dict[str, Any] = {
                "delegate_to": agent_name,
                "description": category["description"],
                "pattern": pattern,
                "priority": max(1, priority),
                "requires_approval": False,
            }

            config["rules"].append(rule)
            priority -= 1  # Decrease priority for next rule

        # Add fallback rule (general tasks)
        if "general" not in task_mappings:
            # Use primary orchestrator as fallback
            fallback_agent = primary_orchestrator
        else:
            fallback_agent = task_mappings["general"]

        fallback_rule: dict[str, Any] = {
            "delegate_to": fallback_agent,
            "description": "General queries and fallback",
            "pattern": ".*",
            "priority": 1,
            "requires_approval": False,
        }
        config["rules"].append(fallback_rule)

        self.delegation_config = config
        return config

    def save_configs(self, project_dir: Path) -> None:
        """
        Save configuration files to disk.
        
        Args:
            project_dir: Project directory path
        """
        config_dir = project_dir / "config"
        config_dir.mkdir(parents=True, exist_ok=True)

        # Save orchestrators.yaml
        orchestrators_file = config_dir / "orchestrators.yaml"
        with open(orchestrators_file, "w", encoding="utf-8") as f:
            yaml.dump(
                self.orchestrators_config,
                f,
                default_flow_style=False,
                sort_keys=False,
            )
        console.print(f"[green]✓[/green] Generated {orchestrators_file}")

        # Save delegation_rules.yaml
        delegation_file = config_dir / "delegation_rules.yaml"
        with open(delegation_file, "w", encoding="utf-8") as f:
            # Add header comment
            f.write("# Delegation MCP Configuration\n")
            f.write("# Auto-generated based on user selections\n\n")
            yaml.dump(
                self.delegation_config,
                f,
                default_flow_style=False,
                sort_keys=False,
            )
        console.print(f"[green]✓[/green] Generated {delegation_file}")

    def generate_configs(
        self,
        selected_agents: list[str],
        task_mappings: dict[str, str],
        agent_metadata: dict[str, AgentMetadata],
        primary_orchestrator: str,
        project_dir: Path,
        scope: str = "local",
    ) -> None:
        """
        Complete configuration generation flow.
        
        Args:
            selected_agents: List of selected agent names
            task_mappings: Dictionary of task_key -> agent_name
            agent_metadata: Dictionary of agent name to metadata
            primary_orchestrator: Name of primary orchestrator
            project_dir: Project directory path
            scope: Installation scope - "local" for project-level, "user" for user-level
        """
        # Determine config directory based on scope
        if scope == "user":
            config_base_dir = Path.home() / ".delegation-mcp"
        else:
            config_base_dir = project_dir
        
        # Check for existing configs
        if self.check_existing_configs(config_base_dir):
            choice = self.prompt_existing_configs(config_base_dir)

            if choice == "skip":
                console.print("\n[yellow]⚠[/yellow] Keeping existing configuration files\n")
                return
            elif choice == "backup":
                self.backup_existing_configs(config_base_dir)

        # Generate configurations
        self.generate_orchestrators_yaml(selected_agents, agent_metadata)
        self.generate_delegation_rules_yaml(
            selected_agents, task_mappings, agent_metadata, primary_orchestrator
        )

        # Save to disk
        self.save_configs(config_base_dir)
        console.print("\n[green]✓[/green] Configuration files generated successfully\n")