File size: 8,841 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
"""Orchestrator registry and management."""

import asyncio
import os
import re
import shutil
import subprocess
from typing import Any
from pathlib import Path

from .config import OrchestratorConfig


class OrchestratorRegistry:
    """Registry for managing available orchestrators/CLIs."""

    def __init__(self):
        self.orchestrators: dict[str, OrchestratorConfig] = {}
        self._active_sessions: dict[str, asyncio.subprocess.Process] = {}

    def register(self, config: OrchestratorConfig) -> None:
        """Register an orchestrator."""
        self.orchestrators[config.name] = config

    def unregister(self, name: str) -> None:
        """Unregister an orchestrator."""
        self.orchestrators.pop(name, None)

    def get(self, name: str) -> OrchestratorConfig | None:
        """Get orchestrator configuration."""
        return self.orchestrators.get(name)

    def list_enabled(self) -> list[str]:
        """List all enabled orchestrators."""
        return [name for name, config in self.orchestrators.items() if config.enabled]

    @staticmethod
    def _resolve_command(cmd: list[str]) -> list[str]:
        """
        Resolve command to full path on Windows.

        On Windows, asyncio.create_subprocess_exec() doesn't reliably search PATH,
        so we need to resolve commands to their full paths using shutil.which().

        Args:
            cmd: Command list

        Returns:
            Resolved command (full path on Windows, original on Unix)
        """
        if os.name != "nt" or not cmd:
            # On Unix systems, PATH search works fine
            return cmd

        # On Windows, resolve the executable path
        resolved = shutil.which(cmd[0])
        if resolved:
            return [resolved] + cmd[1:]
        return cmd

    async def execute(
        self,
        orchestrator_name: str,
        task: str,
        timeout: int | None = None,
        progress_callback: Any = None,
    ) -> tuple[str, str, int]:
        """
        Execute a task using specified orchestrator.

        Args:
            orchestrator_name: Name of orchestrator to use
            task: Task description/query
            timeout: Optional timeout in seconds
            progress_callback: Optional async callback(line: str) for stdout streaming

        Returns:
            tuple: (stdout, stderr, return_code)
        """
        config = self.get(orchestrator_name)
        if not config:
            raise ValueError(f"Orchestrator '{orchestrator_name}' not found")

        if not config.enabled:
            raise ValueError(f"Orchestrator '{orchestrator_name}' is disabled")

        # Build command
        if isinstance(config.command, list):
            cmd = config.command + config.args + [task]
        else:
            cmd = [config.command] + config.args + [task]

        # Resolve command path on Windows
        resolved_cmd = self._resolve_command(cmd)

        # Execute with timeout
        timeout_seconds = timeout or config.timeout
        process = None

        # Build safe environment with allowlist approach
        # Only include essential environment variables
        allowed_env_vars = [
            'PATH', 'HOME', 'USER', 'LANG', 'LC_ALL', 'TERM',
            'PYTHONPATH', 'NODE_PATH', 'OPENROUTER_API_KEY',
            'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'GOOGLE_API_KEY',
            'TMPDIR', 'TEMP', 'TMP', 'USERPROFILE', 'SYSTEMROOT',
        ]
        safe_env = {}
        for key in allowed_env_vars:
            if key in os.environ:
                safe_env[key] = os.environ[key]

        # Add config-specified env vars with validation
        for key, value in config.env.items():
            # Validate env var name (alphanumeric and underscore only)
            if not re.match(r'^[A-Z_][A-Z0-9_]*$', key):
                import logging
                logging.getLogger(__name__).warning(
                    f"Skipping invalid environment variable name: {key}"
                )
                continue
            safe_env[key] = value

        stdout_chunks = []
        stderr_chunks = []

        async def _read_stream(stream, is_stderr: bool):
            while True:
                line = await stream.readline()
                if not line:
                    break
                text = line.decode("utf-8", errors="replace")
                if is_stderr:
                    stderr_chunks.append(text)
                else:
                    stdout_chunks.append(text)
                
                if on_output:
                    try:
                        await on_output(text, is_stderr)
                    except Exception:
                        pass  # Ignore callback errors

        try:
            process = await asyncio.create_subprocess_exec(
                *resolved_cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                env=safe_env,
            )

            stdout_chunks = []
            stderr_chunks = []

            async def read_stream(stream, chunks, callback=None):
                while True:
                    line = await stream.readline()
                    if not line:
                        break
                    decoded_line = line.decode("utf-8", errors="replace")
                    chunks.append(decoded_line)
                    if callback:
                        try:
                            if asyncio.iscoroutinefunction(callback):
                                await callback(decoded_line.strip())
                            else:
                                callback(decoded_line.strip())
                        except Exception:
                            pass  # Ignore callback errors to prevent crashing execution

            # Create tasks for reading stdout and stderr
            stdout_task = asyncio.create_task(
                read_stream(process.stdout, stdout_chunks, progress_callback)
            )
            stderr_task = asyncio.create_task(
                read_stream(process.stderr, stderr_chunks)
            )

            # Wait for everything to finish or timeout
            try:
                # We wait for the process AND the stream readers
                # This ensures we don't timeout if the process is done but streams are still being read
                # and conversely, we DO timeout if streams are blocked even if process is done (unlikely but possible)
                # or if process is hanging.
                await asyncio.wait_for(
                    asyncio.gather(process.wait(), stdout_task, stderr_task),
                    timeout=timeout_seconds
                )
            except asyncio.TimeoutError:
                # Timeout occurred - clean up everything
                if process:
                    try:
                        process.kill()
                    except ProcessLookupError:
                        pass
                
                # Cancel stream readers
                stdout_task.cancel()
                stderr_task.cancel()
                
                # Wait for cancellation to complete
                try:
                    await asyncio.gather(stdout_task, stderr_task, return_exceptions=True)
                except Exception:
                    pass

                raise TimeoutError(
                    f"Orchestrator '{orchestrator_name}' timed out after {timeout_seconds}s"
                )

            return (
                "".join(stdout_chunks),
                "".join(stderr_chunks),
                process.returncode or 0,
            )

        except Exception as e:
            if process and process.returncode is None:
                try:
                    process.kill()
                    await process.wait()
                except ProcessLookupError:
                    pass
            if isinstance(e, (TimeoutError, RuntimeError)):
                raise e
            raise RuntimeError(
                f"Orchestrator '{orchestrator_name}' failed: {str(e)}"
            ) from e

    def validate_all(self) -> dict[str, bool]:
        """
        Validate all registered orchestrators are available.

        Returns:
            dict: {orchestrator_name: is_available}
        """
        results = {}
        for name, config in self.orchestrators.items():
            cmd = config.command if isinstance(config.command, str) else config.command[0]
            try:
                subprocess.run(
                    ["which", cmd] if subprocess.os.name != "nt" else ["where", cmd],
                    capture_output=True,
                    check=True,
                )
                results[name] = True
            except subprocess.CalledProcessError:
                results[name] = False

        return results