File size: 5,976 Bytes
6d5c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Code execution tool — wraps the existing DockerSandbox for agent use.

The agent uses this to:
- Run generated code and read actual output (not predicted output)
- Fix bugs through real execution feedback
- Validate implementations before declaring tasks done

Design reference:
  - GPT Codex: tight write→execute→observe→fix loop
"""

from __future__ import annotations

import logging
import os
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any

from agent.tools.base import BaseTool

LOGGER = logging.getLogger(__name__)

SUPPORTED_LANGUAGES = {"python", "javascript", "typescript", "bash", "go", "rust", "java"}


class CodeExecutorTool(BaseTool):
    """Execute arbitrary code in an isolated sandbox.

    Tries Docker sandbox first (full isolation), falls back to local
    subprocess for Python/Bash in dev mode.
    """

    name = "executor"
    description = "Execute code in any language and return actual stdout/stderr."

    def __init__(self, use_docker: bool = True, timeout: int = 60) -> None:
        self._use_docker = use_docker
        self._timeout = timeout
        self._mode = os.environ.get("ZENEX_EXECUTOR_MODE", "development").lower()
        self._allow_local_fallback = os.environ.get("ZENEX_ALLOW_LOCAL_EXEC", "1") == "1"
        self._sandbox = self._init_sandbox()

    def _init_sandbox(self):
        if not self._use_docker:
            return None
        try:
            from finetuning.docker_sandbox import DockerSandbox
            return DockerSandbox(timeout_seconds=self._timeout)
        except Exception as exc:
            LOGGER.warning("DockerSandbox unavailable: %s. Will use local subprocess fallback.", exc)
            return None

    def run(self, args: dict[str, Any]) -> dict[str, Any]:
        code = args.get("code", "")
        language = args.get("language", "python").lower()
        file_path = args.get("file_path")  # run an existing file instead of inline code
        should_cancel = args.get("_should_cancel")

        if file_path:
            try:
                code = Path(file_path).read_text(encoding="utf-8")
            except Exception as exc:
                return self._fail(f"Cannot read file {file_path}: {exc}")

        if not code.strip():
            return self._fail("No code provided to execute.")

        if language not in SUPPORTED_LANGUAGES:
            return self._fail(f"Unsupported language: {language}. Supported: {SUPPORTED_LANGUAGES}")

        if self._mode == "production" and not self._sandbox:
            return self._fail("Execution blocked: production mode requires Docker sandbox.")

        # Try Docker first
        if self._sandbox:
            try:
                if callable(should_cancel) and should_cancel():
                    return self._fail("Execution cancelled before start.")
                result = self._sandbox.execute(language, code)
                return {
                    "success": result.exit_code == 0,
                    "stdout": result.stdout,
                    "stderr": result.stderr,
                    "exit_code": result.exit_code,
                    "elapsed": result.elapsed_seconds,
                    "error": result.stderr if result.exit_code != 0 else "",
                }
            except Exception as exc:
                LOGGER.warning("Docker execution failed: %s. Falling back to local.", exc)

        # Local subprocess fallback (Python/Bash only)
        if not self._allow_local_fallback:
            return self._fail("Local execution fallback disabled by policy (ZENEX_ALLOW_LOCAL_EXEC=0).")
        return self._local_run(code, language, should_cancel=should_cancel)

    def _local_run(self, code: str, language: str, should_cancel=None) -> dict:
        if language not in ("python", "bash"):
            return self._fail(f"Local fallback only supports python/bash, not {language}.")

        with tempfile.NamedTemporaryFile(
            mode="w",
            suffix=".py" if language == "python" else ".sh",
            delete=False,
            encoding="utf-8",
        ) as f:
            f.write(code)
            tmp_path = f.name

        cmd = ["python3", tmp_path] if language == "python" else ["bash", tmp_path]
        start = time.time()
        try:
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            while proc.poll() is None:
                if callable(should_cancel) and should_cancel():
                    proc.kill()
                    stdout, stderr = proc.communicate(timeout=2)
                    return {
                        "success": False,
                        "stdout": stdout,
                        "stderr": stderr,
                        "exit_code": 130,
                        "elapsed": time.time() - start,
                        "error": "Execution cancelled.",
                    }
                if time.time() - start > self._timeout:
                    proc.kill()
                    stdout, stderr = proc.communicate(timeout=2)
                    return {
                        "success": False,
                        "stdout": stdout,
                        "stderr": stderr,
                        "exit_code": 124,
                        "elapsed": self._timeout,
                        "error": f"Execution timed out after {self._timeout}s.",
                    }
                time.sleep(0.1)

            stdout, stderr = proc.communicate(timeout=2)
            return {
                "success": proc.returncode == 0,
                "stdout": stdout,
                "stderr": stderr,
                "exit_code": proc.returncode,
                "elapsed": time.time() - start,
                "error": stderr if proc.returncode != 0 else "",
            }
        except Exception as exc:
            return self._fail(str(exc))
        finally:
            Path(tmp_path).unlink(missing_ok=True)