coder-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,160 @@
1
+ import logging
2
+ import os
3
+ import platform
4
+ import shlex
5
+ import subprocess
6
+ import uuid
7
+ from typing import Any
8
+
9
+ from pydantic import BaseModel
10
+
11
+ from coderagent.compat import Submitted, recursive_merge
12
+
13
+
14
+ class DockerEnvironmentConfig(BaseModel):
15
+ image: str
16
+ cwd: str = "/"
17
+ """Working directory in which to execute commands."""
18
+ env: dict[str, str] = {}
19
+ """Environment variables to set in the container."""
20
+ forward_env: list[str] = []
21
+ """Environment variables to forward to the container.
22
+ Variables are only forwarded if they are set in the host environment.
23
+ In case of conflict with `env`, the `env` variables take precedence.
24
+ """
25
+ timeout: int = 30
26
+ """Timeout for executing commands in the container."""
27
+ executable: str = os.getenv("MSWEA_DOCKER_EXECUTABLE", "docker")
28
+ """Path to the docker/container executable."""
29
+ run_args: list[str] = ["--rm"]
30
+ """Additional arguments to pass to the docker/container executable.
31
+ Default is ["--rm"], which removes the container after it exits.
32
+ """
33
+ container_timeout: str = "2h"
34
+ """Max duration to keep container running. Uses the same format as the sleep command."""
35
+ pull_timeout: int = 120
36
+ """Timeout in seconds for pulling images."""
37
+ interpreter: list[str] = ["bash", "-lc"]
38
+ """Interpreter to use to execute commands. Default is ["bash", "-lc"].
39
+ The actual command will be appended as argument to this. Override this to e.g., modify shell flags
40
+ (e.g., to remove the `-l` flag to disable login shell) or to use python instead of bash to interpret commands.
41
+ """
42
+
43
+
44
+ class DockerEnvironment:
45
+ def __init__(
46
+ self,
47
+ *,
48
+ config_class: type = DockerEnvironmentConfig,
49
+ logger: logging.Logger | None = None,
50
+ **kwargs,
51
+ ):
52
+ """This class executes bash commands in a Docker container using direct docker commands.
53
+ See `DockerEnvironmentConfig` for keyword arguments.
54
+ """
55
+ self.logger = logger or logging.getLogger("coderagent.environment")
56
+ self.container_id: str | None = None
57
+ self.config = config_class(**kwargs)
58
+ self._start_container()
59
+
60
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
61
+ return recursive_merge(self.config.model_dump(), platform.uname()._asdict(), kwargs)
62
+
63
+ def serialize(self) -> dict:
64
+ return {
65
+ "info": {
66
+ "config": {
67
+ "environment": self.config.model_dump(mode="json"),
68
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
69
+ }
70
+ }
71
+ }
72
+
73
+ def _start_container(self):
74
+ """Start the Docker container and return the container ID."""
75
+ container_name = f"coderagent-{uuid.uuid4().hex[:8]}"
76
+ cmd = [
77
+ self.config.executable,
78
+ "run",
79
+ "-d",
80
+ "--name",
81
+ container_name,
82
+ "-w",
83
+ self.config.cwd,
84
+ *self.config.run_args,
85
+ self.config.image,
86
+ "sleep",
87
+ self.config.container_timeout,
88
+ ]
89
+ self.logger.debug(f"Starting container with command: {shlex.join(cmd)}")
90
+ result = subprocess.run(
91
+ cmd,
92
+ capture_output=True,
93
+ text=True,
94
+ timeout=self.config.pull_timeout, # docker pull might take a while
95
+ check=True,
96
+ )
97
+ self.logger.info(f"Started container {container_name} with ID {result.stdout.strip()}")
98
+ self.container_id = result.stdout.strip()
99
+
100
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> dict[str, Any]:
101
+ """Execute a command in the Docker container and return the result as a dict."""
102
+ command = action.get("command", "")
103
+ cwd = cwd or self.config.cwd
104
+ assert self.container_id, "Container not started"
105
+
106
+ cmd = [self.config.executable, "exec", "-w", cwd]
107
+ for key in self.config.forward_env:
108
+ if (value := os.getenv(key)) is not None:
109
+ cmd.extend(["-e", f"{key}={value}"])
110
+ for key, value in self.config.env.items():
111
+ cmd.extend(["-e", f"{key}={value}"])
112
+ cmd.extend([self.container_id, *self.config.interpreter, command])
113
+
114
+ try:
115
+ result = subprocess.run(
116
+ cmd,
117
+ text=True,
118
+ timeout=timeout or self.config.timeout,
119
+ encoding="utf-8",
120
+ errors="replace",
121
+ stdout=subprocess.PIPE,
122
+ stderr=subprocess.STDOUT,
123
+ )
124
+ output = {"output": result.stdout, "returncode": result.returncode, "exception_info": ""}
125
+ except Exception as e:
126
+ raw_output = getattr(e, "output", None)
127
+ raw_output = (
128
+ raw_output.decode("utf-8", errors="replace") if isinstance(raw_output, bytes) else (raw_output or "")
129
+ )
130
+ output = {
131
+ "output": raw_output,
132
+ "returncode": -1,
133
+ "exception_info": f"An error occurred while executing the command: {e}",
134
+ "extra": {"exception_type": type(e).__name__, "exception": str(e)},
135
+ }
136
+ self._check_finished(output)
137
+ return output
138
+
139
+ def _check_finished(self, output: dict):
140
+ """Raises Submitted if the output indicates task completion."""
141
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
142
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
143
+ submission = "".join(lines[1:])
144
+ raise Submitted(
145
+ {
146
+ "role": "exit",
147
+ "content": submission,
148
+ "extra": {"exit_status": "Submitted", "submission": submission},
149
+ }
150
+ )
151
+
152
+ def cleanup(self):
153
+ """Stop and remove the Docker container."""
154
+ if getattr(self, "container_id", None) is not None: # if init fails early, container_id might not be set
155
+ cmd = f"(timeout 60 {self.config.executable} stop {self.container_id} || {self.config.executable} rm -f {self.container_id}) >/dev/null 2>&1 &"
156
+ subprocess.Popen(cmd, shell=True)
157
+
158
+ def __del__(self):
159
+ """Cleanup container when object is destroyed."""
160
+ self.cleanup()
@@ -0,0 +1,110 @@
1
+ """The environment that runs the commands of the agent on this machine."""
2
+
3
+ import os
4
+ import platform
5
+ import signal
6
+ import subprocess
7
+ from typing import Any
8
+
9
+ from pydantic import BaseModel
10
+
11
+ from coderagent.compat.exceptions import Submitted
12
+ from coderagent.compat.serialize import recursive_merge
13
+
14
+
15
+ class LocalEnvironmentConfig(BaseModel):
16
+ cwd: str = ""
17
+ env: dict[str, str] = {}
18
+ timeout: int = 30
19
+
20
+
21
+ class LocalEnvironment:
22
+ """Runs the commands of the agent on the machine of the user."""
23
+
24
+ def __init__(self, *, config_class: type = LocalEnvironmentConfig, **kwargs):
25
+ self.config = config_class(**kwargs)
26
+ self.env_override: dict[str, str] | None = None
27
+ """The environment of the commands. None means: the environment of the user."""
28
+
29
+ def environment(self) -> dict[str, str]:
30
+ """The environment that the commands run with."""
31
+ return self.env_override if self.env_override is not None else os.environ | self.config.env
32
+
33
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> dict[str, Any]:
34
+ """Run a command and return what it said."""
35
+ command = action.get("command", "")
36
+ cwd = cwd or self.config.cwd or os.getcwd()
37
+ try:
38
+ result = _run(command, cwd, self.environment(), timeout or self.config.timeout)
39
+ output = {"output": result.stdout, "returncode": result.returncode, "exception_info": ""}
40
+ except Exception as e:
41
+ raw_output = getattr(e, "output", None)
42
+ raw_output = (
43
+ raw_output.decode("utf-8", errors="replace") if isinstance(raw_output, bytes) else (raw_output or "")
44
+ )
45
+ output = {
46
+ "output": raw_output,
47
+ "returncode": -1,
48
+ "exception_info": f"An error occurred while executing the command: {e}",
49
+ "extra": {"exception_type": type(e).__name__, "exception": str(e)},
50
+ }
51
+ self._check_finished(output)
52
+ return output
53
+
54
+ def _check_finished(self, output: dict):
55
+ """Raise Submitted if the output says that the task is done."""
56
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
57
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
58
+ submission = "".join(lines[1:])
59
+ raise Submitted(
60
+ {
61
+ "role": "exit",
62
+ "content": submission,
63
+ "extra": {"exit_status": "Submitted", "submission": submission},
64
+ }
65
+ )
66
+
67
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
68
+ return recursive_merge(self.config.model_dump(), platform.uname()._asdict(), os.environ, kwargs)
69
+
70
+ def serialize(self) -> dict:
71
+ return {
72
+ "info": {
73
+ "config": {
74
+ "environment": self.config.model_dump(mode="json"),
75
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
76
+ }
77
+ }
78
+ }
79
+
80
+
81
+ def _run(command: str, cwd: str, env: dict[str, str], timeout: int) -> subprocess.CompletedProcess[str]:
82
+ """Like subprocess.run, but kills the whole process group on timeout so no children are orphaned."""
83
+ process = subprocess.Popen(
84
+ command,
85
+ shell=True,
86
+ text=True,
87
+ cwd=cwd,
88
+ env=env,
89
+ encoding="utf-8",
90
+ errors="replace",
91
+ stdout=subprocess.PIPE,
92
+ stderr=subprocess.STDOUT,
93
+ start_new_session=os.name == "posix",
94
+ )
95
+ try:
96
+ stdout, _ = process.communicate(timeout=timeout)
97
+ except subprocess.TimeoutExpired:
98
+ os.killpg(process.pid, signal.SIGKILL) if os.name == "posix" else process.kill()
99
+ stdout, _ = process.communicate()
100
+ raise subprocess.TimeoutExpired(command, timeout, output=stdout)
101
+ return subprocess.CompletedProcess(command, process.returncode, stdout=stdout)
102
+
103
+
104
+ def is_local(environment: Any) -> bool:
105
+ """Whether the commands of the environment run on this machine.
106
+
107
+ None of the remote sandboxes has the environment of the commands, the local
108
+ one has it.
109
+ """
110
+ return hasattr(environment, "env_override")
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import logging
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ import uuid
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel
13
+
14
+ from coderagent.compat import Submitted, recursive_merge
15
+
16
+
17
+ class SingularityEnvironmentConfig(BaseModel):
18
+ image: str
19
+ cwd: str = "/"
20
+ env: dict[str, str] = {}
21
+ """Environment variables to set in the container."""
22
+ forward_env: list[str] = []
23
+ """Environment variables to forward to the container."""
24
+ timeout: int = 30
25
+ """Timeout for executing commands in the container."""
26
+ executable: str = os.getenv("MSWEA_SINGULARITY_EXECUTABLE", "singularity")
27
+ """Path to the singularity executable."""
28
+ sandbox_build_retries: int = 3
29
+ """Number of retries for building the sandbox if an error occurs."""
30
+ global_args: list[str] = ["--quiet"]
31
+ """Global arguments passed before the subcommand (e.g., --quiet, --debug)."""
32
+ exec_args: list[str] = ["--contain", "--cleanenv", "--fakeroot"]
33
+ """Arguments passed to `singularity exec`."""
34
+
35
+
36
+ class SingularityEnvironment:
37
+ def __init__(
38
+ self, *, config_class: type = SingularityEnvironmentConfig, logger: logging.Logger | None = None, **kwargs
39
+ ):
40
+ """Singularity environment. See `SingularityEnvironmentConfig` for kwargs."""
41
+ self.logger = logger or logging.getLogger("coderagent.environment")
42
+ self.config = config_class(**kwargs)
43
+ self.sandbox_dir = self._build_sandbox()
44
+
45
+ def _build_sandbox(self) -> Path:
46
+ # Building the sandbox can fail (very rarely), so we retry it
47
+ max_retries = self.config.sandbox_build_retries
48
+ for attempt in range(max_retries):
49
+ sandbox_dir = Path(tempfile.gettempdir()) / f"coderagent-{uuid.uuid4().hex[:8]}"
50
+ try:
51
+ subprocess.run(
52
+ [self.config.executable, "build", "--sandbox", sandbox_dir, self.config.image],
53
+ check=True,
54
+ capture_output=True,
55
+ )
56
+ break
57
+ except subprocess.CalledProcessError as e:
58
+ shutil.rmtree(sandbox_dir, ignore_errors=True)
59
+ self.logger.error(
60
+ f"Error building image {self.config.image}, stdout: {e.stdout}, stderr: {e.stderr} (attempt {attempt + 1}/{max_retries})"
61
+ )
62
+ if attempt == max_retries - 1:
63
+ raise
64
+ return sandbox_dir
65
+
66
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
67
+ return recursive_merge(self.config.model_dump(), kwargs)
68
+
69
+ def serialize(self) -> dict:
70
+ return {
71
+ "info": {
72
+ "config": {
73
+ "environment": self.config.model_dump(mode="json"),
74
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
75
+ }
76
+ }
77
+ }
78
+
79
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> dict[str, Any]:
80
+ """Execute a command in a Singularity container and return the result as a dict."""
81
+ command = action.get("command", "")
82
+ cmd = [self.config.executable, *self.config.global_args, "exec", *self.config.exec_args]
83
+
84
+ work_dir = cwd or self.config.cwd
85
+ if work_dir and work_dir != "/":
86
+ cmd.extend(["--pwd", work_dir])
87
+
88
+ for key in self.config.forward_env:
89
+ if (value := os.getenv(key)) is not None:
90
+ cmd.extend(["--env", f"{key}={value}"])
91
+ for key, value in self.config.env.items():
92
+ cmd.extend(["--env", f"{key}={value}"])
93
+
94
+ cmd.extend(["--writable", str(self.sandbox_dir), "bash", "-c", command])
95
+ try:
96
+ result = subprocess.run(
97
+ cmd,
98
+ text=True,
99
+ timeout=timeout or self.config.timeout,
100
+ encoding="utf-8",
101
+ errors="replace",
102
+ stdout=subprocess.PIPE,
103
+ stderr=subprocess.STDOUT,
104
+ )
105
+ output = {"output": result.stdout, "returncode": result.returncode, "exception_info": ""}
106
+ except Exception as e:
107
+ raw_output = getattr(e, "output", None)
108
+ raw_output = (
109
+ raw_output.decode("utf-8", errors="replace") if isinstance(raw_output, bytes) else (raw_output or "")
110
+ )
111
+ output = {
112
+ "output": raw_output,
113
+ "returncode": -1,
114
+ "exception_info": f"An error occurred while executing the command: {e}",
115
+ "extra": {"exception_type": type(e).__name__, "exception": str(e)},
116
+ }
117
+ self._check_finished(output)
118
+ return output
119
+
120
+ def _check_finished(self, output: dict):
121
+ """Raises Submitted if the output indicates task completion."""
122
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
123
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
124
+ submission = "".join(lines[1:])
125
+ raise Submitted(
126
+ {
127
+ "role": "exit",
128
+ "content": submission,
129
+ "extra": {"exit_status": "Submitted", "submission": submission},
130
+ }
131
+ )
132
+
133
+ def cleanup(self):
134
+ shutil.rmtree(self.sandbox_dir, ignore_errors=True)
135
+
136
+ def __del__(self):
137
+ """Cleanup sandbox when object is destroyed."""
138
+ self.cleanup()
@@ -0,0 +1,79 @@
1
+ import asyncio
2
+ from typing import Any
3
+
4
+ from pydantic import BaseModel
5
+ from swerex.deployment.docker import DockerDeployment
6
+ from swerex.runtime.abstract import Command as RexCommand
7
+
8
+ from coderagent.compat import Submitted, recursive_merge
9
+
10
+
11
+ class SwerexDockerEnvironmentConfig(BaseModel):
12
+ image: str
13
+ cwd: str = "/"
14
+ """Working directory in which to execute commands."""
15
+ timeout: int = 30
16
+ """Timeout for executing commands in the container."""
17
+ deployment_extra_kwargs: dict[str, Any] = {}
18
+ """Extra kwargs to pass to DockerDeployment."""
19
+
20
+
21
+ class SwerexDockerEnvironment:
22
+ def __init__(self, **kwargs):
23
+ """This class executes bash commands in a Docker container using SWE-ReX for sandboxing."""
24
+ self.config = SwerexDockerEnvironmentConfig(**kwargs)
25
+ self.deployment = DockerDeployment(image=self.config.image, **self.config.deployment_extra_kwargs)
26
+ asyncio.run(self.deployment.start())
27
+
28
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> dict[str, Any]:
29
+ """Execute a command in the environment and return the raw output."""
30
+ command = action.get("command", "")
31
+ try:
32
+ result = asyncio.run(
33
+ self.deployment.runtime.execute(
34
+ RexCommand(
35
+ command=command,
36
+ shell=True,
37
+ check=False,
38
+ cwd=cwd or self.config.cwd,
39
+ timeout=timeout or self.config.timeout,
40
+ merge_output_streams=True,
41
+ )
42
+ )
43
+ )
44
+ output = {"output": result.stdout, "returncode": result.exit_code, "exception_info": ""}
45
+ except Exception as e:
46
+ output = {
47
+ "output": str(e) if str(e) else "",
48
+ "returncode": -1,
49
+ "exception_info": f"An error occurred while executing the command: {e}",
50
+ "extra": {"exception_type": type(e).__name__, "exception": str(e)},
51
+ }
52
+ self._check_finished(output)
53
+ return output
54
+
55
+ def _check_finished(self, output: dict):
56
+ """Raises Submitted if the output indicates task completion."""
57
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
58
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
59
+ submission = "".join(lines[1:])
60
+ raise Submitted(
61
+ {
62
+ "role": "exit",
63
+ "content": submission,
64
+ "extra": {"exit_status": "Submitted", "submission": submission},
65
+ }
66
+ )
67
+
68
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
69
+ return recursive_merge(self.config.model_dump(), kwargs)
70
+
71
+ def serialize(self) -> dict:
72
+ return {
73
+ "info": {
74
+ "config": {
75
+ "environment": self.config.model_dump(mode="json"),
76
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,123 @@
1
+ import asyncio
2
+ from typing import Any
3
+
4
+ from pydantic import BaseModel
5
+ from swerex.deployment.modal import ModalDeployment
6
+ from swerex.runtime.abstract import Command as RexCommand
7
+
8
+ from coderagent.compat import Submitted, recursive_merge
9
+
10
+
11
+ class SwerexModalEnvironmentConfig(BaseModel):
12
+ image: str
13
+ """Image to use for the deployment. Can be:
14
+ - Dockerhub image name (e.g. `python:3.11-slim`)
15
+ - ECR image name (e.g. `123456789012.dkr.ecr.us-east-1.amazonaws.com/my-image:tag`)
16
+ - Path to a Dockerfile
17
+ """
18
+ cwd: str = "/"
19
+ """Working directory in which to execute commands."""
20
+ timeout: int = 30
21
+ """Timeout for executing commands in the container."""
22
+ env: dict[str, str] = {}
23
+ """Environment variables to set when executing commands."""
24
+ startup_timeout: float = 60.0
25
+ """The time to wait for the runtime to start."""
26
+ runtime_timeout: float = 3600.0
27
+ """The runtime timeout (how long the Modal sandbox can stay alive)."""
28
+ deployment_timeout: float = 3600.0
29
+ """The deployment timeout."""
30
+ install_pipx: bool = True
31
+ """Whether to install pipx in the container (required for swe-rex runtime)."""
32
+ modal_sandbox_kwargs: dict[str, Any] = {}
33
+ """Additional arguments to pass to `modal.Sandbox.create`."""
34
+
35
+
36
+ class SwerexModalEnvironment:
37
+ def __init__(self, **kwargs):
38
+ """This class executes bash commands in a Modal sandbox using SWE-ReX for remote execution.
39
+
40
+ Modal (https://modal.com) provides serverless cloud compute that can be used to run
41
+ sandboxed environments. This environment class uses SWE-ReX's ModalDeployment to
42
+ create and manage Modal sandboxes for command execution.
43
+
44
+ This is useful for:
45
+ - Training coding agents at scale with remote execution
46
+ - Running evaluations in isolated cloud environments
47
+ - Parallel execution across many instances
48
+
49
+ See `SwerexModalEnvironmentConfig` for keyword arguments.
50
+ """
51
+ self.config = SwerexModalEnvironmentConfig(**kwargs)
52
+ self.deployment = ModalDeployment(
53
+ image=self.config.image,
54
+ startup_timeout=self.config.startup_timeout,
55
+ runtime_timeout=self.config.runtime_timeout,
56
+ deployment_timeout=self.config.deployment_timeout,
57
+ install_pipx=self.config.install_pipx,
58
+ modal_sandbox_kwargs=self.config.modal_sandbox_kwargs,
59
+ )
60
+ asyncio.run(self.deployment.start())
61
+
62
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> dict[str, Any]:
63
+ """Execute a command in the environment and return the raw output."""
64
+ command = action.get("command", "") if isinstance(action, dict) else action
65
+ try:
66
+ result = asyncio.run(
67
+ self.deployment.runtime.execute(
68
+ RexCommand(
69
+ command=command,
70
+ shell=True,
71
+ check=False,
72
+ cwd=cwd or self.config.cwd,
73
+ timeout=timeout or self.config.timeout,
74
+ merge_output_streams=True,
75
+ env=self.config.env if self.config.env else None,
76
+ )
77
+ )
78
+ )
79
+ output = {"output": result.stdout, "returncode": result.exit_code, "exception_info": ""}
80
+ except Exception as e:
81
+ output = {
82
+ "output": str(e) if str(e) else "",
83
+ "returncode": -1,
84
+ "exception_info": f"An error occurred while executing the command: {e}",
85
+ "extra": {"exception_type": type(e).__name__, "exception": str(e)},
86
+ }
87
+ self._check_finished(output)
88
+ return output
89
+
90
+ def _check_finished(self, output: dict):
91
+ """Raises Submitted if the output indicates task completion."""
92
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
93
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
94
+ submission = "".join(lines[1:])
95
+ raise Submitted(
96
+ {
97
+ "role": "exit",
98
+ "content": submission,
99
+ "extra": {"exit_status": "Submitted", "submission": submission},
100
+ }
101
+ )
102
+
103
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
104
+ return recursive_merge(self.config.model_dump(), kwargs)
105
+
106
+ def serialize(self) -> dict:
107
+ return {
108
+ "info": {
109
+ "config": {
110
+ "environment": self.config.model_dump(mode="json"),
111
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
112
+ }
113
+ }
114
+ }
115
+
116
+ def stop(self):
117
+ async def _stop():
118
+ await asyncio.wait_for(self.deployment.stop(), timeout=10)
119
+
120
+ try:
121
+ asyncio.run(_stop())
122
+ except Exception:
123
+ pass
@@ -0,0 +1 @@
1
+ """The eval harness: run a suite of tasks and measure the agent."""