File size: 3,116 Bytes
f33f7d1
 
4997b06
 
f33f7d1
4997b06
2bf281f
9febf4f
37f9abc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f33f7d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37f9abc
 
 
 
ea15e09
88750f0
37f9abc
f33f7d1
51c5f7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f33f7d1
37f9abc
f33f7d1
ea15e09
37f9abc
 
 
 
f33f7d1
 
37f9abc
 
 
f33f7d1
 
37f9abc
 
 
f33f7d1
37f9abc
 
 
d2e8017
 
f33f7d1
 
 
d2e8017
 
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
import os
import signal
import subprocess
from pathlib import Path

from multi_agent_sdlc.tools.shared.models import ProcessResult

from .environment import build_sandbox_environment


def normalise_process_output(
    output: str | bytes | None,
) -> str:
    """Convert subprocess output to a clean string."""
    if output is None:
        return ""

    if isinstance(output, bytes):
        return output.decode(
            "utf-8",
            errors="replace",
        ).strip()

    return output.strip()


def _start_process(
    command: list[str],
    project_directory: Path,
    stdin_text: str | None,
) -> subprocess.Popen[str]:
    """Start a process in an isolated process group."""

    return subprocess.Popen(
        command,
        cwd=project_directory,
        env=build_sandbox_environment(),
        stdin=subprocess.PIPE if stdin_text is not None else None,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        shell=False,
        start_new_session=True,
    )


def _terminate_process_group(
    process: subprocess.Popen[str],
    grace_period_seconds: int = 5,
) -> tuple[str, str]:
    """Terminate the process group and collect remaining output."""

    os.killpg(
        os.getpgid(process.pid),
        signal.SIGTERM,
    )

    try:
        return process.communicate(
            timeout=grace_period_seconds,
        )
    except subprocess.TimeoutExpired:
        os.killpg(
            os.getpgid(process.pid),
            signal.SIGKILL,
        )

        return process.communicate()


def execute_process(
    command: list[str],
    project_directory: Path,
    timeout_seconds: int,
    stdin_text: str | None = None,
) -> ProcessResult:
    """Execute an internally constructed command inside the project."""

    try:
        process = _start_process(
            command=command,
            project_directory=project_directory,
            stdin_text=stdin_text,
        )
    except OSError as error:
        return {
            "command": command,
            "exit_code": None,
            "stdout": "",
            "stderr": normalise_process_output(str(error)),
            "timed_out": False,
            "message": "Command could not be started.",
        }

    try:
        stdout, stderr = process.communicate(
            input=stdin_text,
            timeout=timeout_seconds,
        )

    except subprocess.TimeoutExpired as error:
        stdout, stderr = _terminate_process_group(process)

        return {
            "command": command,
            "exit_code": None,
            "stdout": normalise_process_output(stdout or error.stdout),
            "stderr": normalise_process_output(stderr or error.stderr),
            "timed_out": True,
            "message": (
                f"Command exceeded the {timeout_seconds}-second timeout. "
                "The process group was terminated."
            ),
        }

    return {
        "command": command,
        "exit_code": process.returncode,
        "stdout": stdout.strip(),
        "stderr": stderr.strip(),
        "timed_out": False,
    }