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,301 @@
1
+ """What the user has agreed to run.
2
+
3
+ An MCP server, a hook and a verify command run code without asking the user:
4
+ one call after the other, without a question. When they come from the project,
5
+ that code was not written by the user, and cloning a repository must not be
6
+ enough to run it. So the code of a project waits for a decision, and the
7
+ decision is remembered in `~/.coderagent/trusted.json`.
8
+
9
+ The decision belongs to the command it was made for: a thing that changed its
10
+ command is a thing that has to be trusted again.
11
+ """
12
+
13
+ import copy
14
+ import hashlib
15
+ import json
16
+ import logging
17
+ from pathlib import Path
18
+
19
+ from coderagent.paths import config_home
20
+ from coderagent.tools.permissions import RULE_KEYS
21
+
22
+ logger = logging.getLogger("coderagent.trust")
23
+
24
+ TRUST_FILE = "trusted.json"
25
+ TRUSTED = "trusted"
26
+ DENIED = "denied"
27
+ TIGHT_MODES = ("plan", "readonly")
28
+ """The modes a project may set: they take tools away, they never give them."""
29
+ TIGHT_SANDBOX_MODES = ("read-only", "workspace-write")
30
+ """The sandbox modes a project may set: they close the sandbox, they never open it."""
31
+
32
+
33
+ def trust_path(user_home: Path | None = None) -> Path:
34
+ """The file with the decisions of the user."""
35
+ home = Path(user_home) if user_home else config_home()
36
+ return home / TRUST_FILE
37
+
38
+
39
+ def decisions(user_home: Path | None = None) -> dict[str, dict[str, dict]]:
40
+ """Every decision of the user, per project."""
41
+ path = trust_path(user_home)
42
+ if not path.exists():
43
+ return {}
44
+ try:
45
+ data = json.loads(path.read_text(encoding="utf-8"))
46
+ except json.JSONDecodeError:
47
+ return {}
48
+ return data if isinstance(data, dict) else {}
49
+
50
+
51
+ def project_key(project: Path) -> str:
52
+ """The key of a project: the directory whose configuration it is."""
53
+ return str(Path(project).resolve())
54
+
55
+
56
+ def decision(project: Path, key: str, command: str, user_home: Path | None = None) -> str:
57
+ """The decision for a thing of a project. Empty when there is none.
58
+
59
+ The command has to be the one that was trusted: when it changes, the thing
60
+ has to be trusted again.
61
+ """
62
+ record = decisions(user_home).get(project_key(project), {}).get(key)
63
+ if not isinstance(record, dict) or record.get("command") != command:
64
+ return ""
65
+ return str(record.get("decision", ""))
66
+
67
+
68
+ def is_trusted(project: Path, key: str, command: str, user_home: Path | None = None) -> bool:
69
+ """Whether the user has trusted this command of this project."""
70
+ return decision(project, key, command, user_home) == TRUSTED
71
+
72
+
73
+ def remember(project: Path, key: str, answer: str, command: str, user_home: Path | None = None) -> Path:
74
+ """Write the answer of the user into the trust table."""
75
+ path = trust_path(user_home)
76
+ path.parent.mkdir(parents=True, exist_ok=True)
77
+ table = decisions(user_home)
78
+ table.setdefault(project_key(project), {})[key] = {"decision": answer, "command": command}
79
+ path.write_text(json.dumps(table, indent=2, sort_keys=True), encoding="utf-8")
80
+ return path
81
+
82
+
83
+ def key_of(kind: str, command: str) -> str:
84
+ """A short key for a thing that has no name of its own."""
85
+ return f"{kind}:{hashlib.sha256(command.encode('utf-8')).hexdigest()[:8]}"
86
+
87
+
88
+ def waiting(project: dict, directory: Path, user_home: Path | None = None) -> dict[str, str]:
89
+ """The code of the project that waits for a decision of the user.
90
+
91
+ The key names the thing, the value is the command it would run.
92
+ """
93
+ pending: dict[str, str] = {}
94
+ for server in _entries(project, "mcp", "servers"):
95
+ command = str(server.get("command") or "")
96
+ key = f"mcp:{server.get('name')}"
97
+ if command and not is_trusted(directory, key, command, user_home):
98
+ pending[key] = command
99
+ for hook in _hooks(project):
100
+ command = str(hook.get("command") or "")
101
+ key = key_of("hook", command)
102
+ if command and not is_trusted(directory, key, command, user_home):
103
+ pending[key] = command
104
+ for command in _entries(project, "verify", "commands"):
105
+ command = str(command)
106
+ key = key_of("verify", command)
107
+ if command and not is_trusted(directory, key, command, user_home):
108
+ pending[key] = command
109
+ return pending
110
+
111
+
112
+ def without_untrusted(project: dict, directory: Path, user_home: Path | None = None) -> dict:
113
+ """The configuration of the project without the code that waits for a decision.
114
+
115
+ What is left out is left out entirely, so that the user level keeps what
116
+ it has: a project that is not trusted does not replace the user, it only
117
+ misses.
118
+ """
119
+ pending = waiting(project, directory, user_home)
120
+ if not pending:
121
+ return project
122
+ result = copy.deepcopy(project)
123
+ result.pop("profile", None)
124
+ result.pop("profiles", None)
125
+ """A project may not choose a set of permissions: that is the decision of the user."""
126
+ _without_servers(result, pending)
127
+ _without_hooks(result, pending)
128
+ _without_verify(result, pending)
129
+ return result
130
+
131
+
132
+ def _without_servers(result: dict, pending: dict[str, str]) -> None:
133
+ """The servers that are left are the ones the user has trusted."""
134
+ servers = _entries(result, "mcp", "servers")
135
+ kept = [server for server in servers if f"mcp:{server.get('name')}" not in pending]
136
+ if len(kept) == len(servers):
137
+ return
138
+ if kept:
139
+ result["mcp"]["servers"] = kept
140
+ else:
141
+ result["mcp"].pop("servers", None)
142
+
143
+
144
+ def _without_hooks(result: dict, pending: dict[str, str]) -> None:
145
+ """The hooks that are left are the ones the user has trusted."""
146
+ events = (result.get("hooks") or {}).get("events") or {}
147
+ for event, group in list(events.items()):
148
+ matchers = []
149
+ for matcher in group or []:
150
+ hooks = [
151
+ h for h in (matcher.get("hooks") or []) if key_of("hook", str(h.get("command") or "")) not in pending
152
+ ]
153
+ if hooks:
154
+ matcher["hooks"] = hooks
155
+ matchers.append(matcher)
156
+ if matchers:
157
+ events[event] = matchers
158
+ else:
159
+ events.pop(event, None)
160
+
161
+
162
+ def _without_verify(result: dict, pending: dict[str, str]) -> None:
163
+ """The commands that are left are the ones the user has trusted."""
164
+ commands = _entries(result, "verify", "commands")
165
+ kept = [command for command in commands if key_of("verify", str(command)) not in pending]
166
+ if len(kept) == len(commands):
167
+ return
168
+ if kept:
169
+ result["verify"]["commands"] = kept
170
+ else:
171
+ result["verify"].pop("commands", None)
172
+
173
+
174
+ def tightened(project: dict) -> dict:
175
+ """The configuration of the project without what would loosen the permissions.
176
+
177
+ The permissions are the user's: a project may say what the agent may not
178
+ do, never what it may do without asking. So the mode of the project is only
179
+ kept when it takes tools away, the directories it opens are dropped, and
180
+ the rules it brings may only deny.
181
+ """
182
+ result = copy.deepcopy(project)
183
+ result.pop("profile", None)
184
+ result.pop("profiles", None)
185
+ """A project may not choose a set of permissions: that is the decision of the user."""
186
+ result.pop("model", None)
187
+ """The model of a project would take the whole conversation to an address of
188
+ its own, and the key of the user with it. The model is the decision of the user."""
189
+ context = result.get("context")
190
+ if isinstance(context, dict):
191
+ """The summary of the context goes to a model: the project may not choose it."""
192
+ context.pop("summarize_model", None)
193
+ """The window is the one of the model: a project that claims a bigger one
194
+ would overflow it."""
195
+ context.pop("context_window", None)
196
+ sandbox = result.get("sandbox")
197
+ if isinstance(sandbox, dict):
198
+ """A project may close the sandbox, never open it, and never choose
199
+ where the commands of the agent run: an image of the project would
200
+ take the workspace of the user with it."""
201
+ if str(sandbox.get("mode") or "") not in TIGHT_SANDBOX_MODES:
202
+ sandbox.pop("mode", None)
203
+ for key in [key for key in sandbox if key != "mode"]:
204
+ sandbox.pop(key)
205
+ telemetry = result.get("telemetry")
206
+ if isinstance(telemetry, dict):
207
+ if str(telemetry.get("otel_endpoint") or ""):
208
+ """A project may close the trace, never send it somewhere else."""
209
+ telemetry.pop("otel_endpoint", None)
210
+ telemetry.pop("otel_headers", None)
211
+ permissions = result.get("permissions")
212
+ shell = result.get("shell_environment")
213
+ ui = result.get("ui")
214
+ if isinstance(ui, dict):
215
+ """A project may not choose the program that runs on the machine of the user."""
216
+ ui.pop("file_opener", None)
217
+ ui.pop("notify_command", None)
218
+ """The notifier runs a program of the project and hands it the answer of the agent."""
219
+ result.pop("history", None)
220
+ """The history belongs to the user: a project may neither hide it nor delete it."""
221
+ if isinstance(shell, dict):
222
+ """A project may hide more of the environment, never show what the user hid."""
223
+ shell.pop("include", None)
224
+ shell.pop("set", None)
225
+ """A project may not put variables into the environment of the agent: a
226
+ `LD_PRELOAD` or a `PATH` of its own would run its code on the machine of
227
+ the user, in every command the agent runs."""
228
+ if not isinstance(permissions, dict):
229
+ return result
230
+ if str(permissions.get("mode") or "") not in TIGHT_MODES:
231
+ permissions.pop("mode", None)
232
+ permissions.pop("include_dirs", None)
233
+ if str(permissions.get("network") or "") != "deny":
234
+ """A project may close the network, never open it."""
235
+ permissions.pop("network", None)
236
+ rules = permissions.get("rules")
237
+ permissions["rules"] = _denies_of(rules) if isinstance(rules, list) else []
238
+ return result
239
+
240
+
241
+ def _denies_of(rules: list) -> list[dict]:
242
+ """The rules of a project: they may only deny.
243
+
244
+ A rule that says something else is a deny as well: a broken deny must not
245
+ turn into an allow, and a project may not break the session of the user
246
+ with a rule it wrote wrong.
247
+ """
248
+ denies = []
249
+ for rule in rules:
250
+ if not isinstance(rule, dict):
251
+ continue
252
+ decision = str(rule.get("decision") or "")
253
+ if not decision or decision in ("allow", "ask"):
254
+ """A project may not allow itself what the user has to be asked for."""
255
+ continue
256
+ if decision != "deny":
257
+ logger.warning("The rule of the project has the unknown decision '%s': it is treated as a deny.", decision)
258
+ denies.append({**{key: value for key, value in rule.items() if key in RULE_KEYS}, "decision": "deny"})
259
+ return denies
260
+
261
+
262
+ def _entries(project: dict, section: str, key: str) -> list:
263
+ """The entries of a section of a configuration, whatever it holds."""
264
+ value = (project.get(section) or {}).get(key) or []
265
+ return value if isinstance(value, list) else []
266
+
267
+
268
+ def _matchers(project: dict) -> list[dict]:
269
+ """The hook matchers of a configuration."""
270
+ events = (project.get("hooks") or {}).get("events") or {}
271
+ matchers = []
272
+ for group in events.values():
273
+ matchers.extend(m for m in (group or []) if isinstance(m, dict))
274
+ return matchers
275
+
276
+
277
+ def _hooks(project: dict) -> list[dict]:
278
+ """The hooks of a configuration, whatever shape they have."""
279
+ hooks = []
280
+ for matcher in _matchers(project):
281
+ hooks.extend(h for h in (matcher.get("hooks") or []) if isinstance(h, dict))
282
+ return hooks
283
+
284
+
285
+ __all__ = [
286
+ "DENIED",
287
+ "TIGHT_MODES",
288
+ "TIGHT_SANDBOX_MODES",
289
+ "TRUSTED",
290
+ "TRUST_FILE",
291
+ "decision",
292
+ "decisions",
293
+ "is_trusted",
294
+ "key_of",
295
+ "project_key",
296
+ "remember",
297
+ "tightened",
298
+ "trust_path",
299
+ "waiting",
300
+ "without_untrusted",
301
+ ]
@@ -0,0 +1,11 @@
1
+ """The environments the commands of the agent run in.
2
+
3
+ The local one runs the commands on the machine of the user. The other ones are
4
+ containers: Docker, Singularity, bubblewrap, contree, and the containers that
5
+ SWE-ReX and Modal manage. They are chosen with `sandbox.type` in the
6
+ configuration and they are imported only when they are used.
7
+ """
8
+
9
+ from coderagent.environments.local import LocalEnvironment, LocalEnvironmentConfig, is_local
10
+
11
+ __all__ = ["LocalEnvironment", "LocalEnvironmentConfig", "is_local"]
@@ -0,0 +1,150 @@
1
+ """
2
+ [Bubblewrap](https://github.com/containers/bubblewrap) is a low-level, unprivileged sandboxing tool for Linux that enables running applications
3
+ in isolated environments with restricted access to the operating system and user data.
4
+ This environment uses bubblewrap to execute commands in a sandboxed environment.
5
+
6
+ !!! warning
7
+ This environment is experimental.
8
+
9
+ !!! warning
10
+ This environment is not supported on Windows.
11
+ """
12
+
13
+ import logging
14
+ import os
15
+ import platform
16
+ import shutil
17
+ import subprocess
18
+ import tempfile
19
+ import uuid
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from pydantic import BaseModel
24
+
25
+ from coderagent.compat import Submitted, recursive_merge
26
+
27
+
28
+ class BubblewrapEnvironmentConfig(BaseModel):
29
+ cwd: str = ""
30
+ """Working directory for the sandbox."""
31
+ env: dict[str, str] = {}
32
+ """Dictionary of environment variables to set in the sandbox."""
33
+ timeout: int = 30
34
+ """Timeout for the command in seconds."""
35
+ executable: str = os.getenv("MSWEA_BUBBLEWRAP_EXECUTABLE", "bwrap")
36
+ """Path to the bubblewrap executable."""
37
+ wrapper_args: list[str] = [
38
+ "--unshare-user-try",
39
+ "--ro-bind",
40
+ "/usr",
41
+ "/usr",
42
+ "--ro-bind",
43
+ "/bin",
44
+ "/bin",
45
+ "--ro-bind",
46
+ "/lib",
47
+ "/lib",
48
+ "--ro-bind",
49
+ "/lib64",
50
+ "/lib64",
51
+ "--ro-bind",
52
+ "/etc",
53
+ "/etc",
54
+ "--tmpfs",
55
+ "/tmp",
56
+ "--proc",
57
+ "/proc",
58
+ "--dev",
59
+ "/dev",
60
+ "--new-session",
61
+ "--setenv",
62
+ "PATH",
63
+ "/usr/local/bin:/usr/sbin:/usr/bin:/bin",
64
+ ]
65
+ """Arguments to pass to the bubblewrap executable."""
66
+
67
+
68
+ class BubblewrapEnvironment:
69
+ def __init__(
70
+ self, *, config_class: type = BubblewrapEnvironmentConfig, logger: logging.Logger | None = None, **kwargs
71
+ ):
72
+ """This class executes bash commands in a bubblewrap environment and a separate working
73
+ directory for each environment. See `BubblewrapEnvironmentConfig` for kwargs.
74
+ """
75
+ self.logger = logger or logging.getLogger("coderagent.environment")
76
+ self.config = config_class(**kwargs)
77
+ self.working_dir = Path(tempfile.gettempdir()) / f"coderagent-{uuid.uuid4().hex[:8]}"
78
+ self.working_dir.mkdir(parents=True, exist_ok=True)
79
+
80
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> dict[str, Any]:
81
+ """Execute a command in the bubblewrap environment and return the result as a dict."""
82
+ command = action.get("command", "")
83
+ cwd = cwd or self.config.cwd or str(self.working_dir)
84
+
85
+ cmd = [self.config.executable] + self.config.wrapper_args + ["--bind", cwd, cwd, "--chdir", cwd]
86
+
87
+ # Add environment variables
88
+ for key, value in self.config.env.items():
89
+ cmd.extend(["--setenv", key, value])
90
+
91
+ cmd.extend(["bash", "-c", command])
92
+
93
+ try:
94
+ result = subprocess.run(
95
+ cmd,
96
+ text=True,
97
+ timeout=timeout or self.config.timeout,
98
+ encoding="utf-8",
99
+ errors="replace",
100
+ stdout=subprocess.PIPE,
101
+ stderr=subprocess.STDOUT,
102
+ )
103
+ output = {"output": result.stdout, "returncode": result.returncode, "exception_info": ""}
104
+ except Exception as e:
105
+ raw_output = getattr(e, "output", None)
106
+ raw_output = (
107
+ raw_output.decode("utf-8", errors="replace") if isinstance(raw_output, bytes) else (raw_output or "")
108
+ )
109
+ output = {
110
+ "output": raw_output,
111
+ "returncode": -1,
112
+ "exception_info": f"An error occurred while executing the command: {e}",
113
+ "extra": {"exception_type": type(e).__name__, "exception": str(e)},
114
+ }
115
+ self._check_finished(output)
116
+ return output
117
+
118
+ def _check_finished(self, output: dict):
119
+ """Raises Submitted if the output indicates task completion."""
120
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
121
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
122
+ submission = "".join(lines[1:])
123
+ raise Submitted(
124
+ {
125
+ "role": "exit",
126
+ "content": submission,
127
+ "extra": {"exit_status": "Submitted", "submission": submission},
128
+ }
129
+ )
130
+
131
+ def cleanup(self):
132
+ if self.working_dir.exists():
133
+ shutil.rmtree(self.working_dir)
134
+
135
+ def __del__(self):
136
+ """Cleanup working_dir when object is destroyed."""
137
+ self.cleanup()
138
+
139
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
140
+ return recursive_merge(self.config.model_dump(), platform.uname()._asdict(), kwargs)
141
+
142
+ def serialize(self) -> dict:
143
+ return {
144
+ "info": {
145
+ "config": {
146
+ "environment": self.config.model_dump(mode="json"),
147
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
148
+ }
149
+ }
150
+ }
@@ -0,0 +1,146 @@
1
+ import logging
2
+ import os
3
+ import platform
4
+ import shlex
5
+ from dataclasses import asdict, is_dataclass
6
+ from numbers import Number
7
+ from typing import Any, NotRequired, TypedDict
8
+
9
+ from contree_sdk import ContreeSync
10
+ from contree_sdk.config import ContreeConfig
11
+ from contree_sdk.sdk.objects.image import ContreeImageSync
12
+ from pydantic import BaseModel
13
+
14
+ from coderagent.compat import Submitted, recursive_merge
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class ContreeEnvironmentConfig(BaseModel):
20
+ contree_config: ContreeConfig | dict[str, Any]
21
+
22
+ image: str
23
+ image_tag: str = None
24
+ """If set, used to pull image by tag. If fails, then it imports by `image` and sets `image_tag` value to image tag"""
25
+ cwd: str = "/"
26
+ """Working directory in which to execute commands."""
27
+ cwd_auto_create: bool = True
28
+ """Create cwd before running any commands."""
29
+ env: dict[str, str] = {}
30
+ """Environment variables to set in the container."""
31
+ forward_env: list[str] = []
32
+ """Environment variables to forward to the container.
33
+ Variables are only forwarded if they are set in the host environment.
34
+ In case of conflict with `env`, the `env` variables take precedence.
35
+ """
36
+ interpreter: list[str] = ["bash", "-c"]
37
+ """Interpreter to execute commands"""
38
+ timeout: int = 100
39
+ """Timeout for executing commands in the container."""
40
+ import_username: str | None = None
41
+ """Username that will be used if image needs to be imported."""
42
+ import_password: str | None = None
43
+ """Password that will be used if image needs to be imported."""
44
+
45
+
46
+ class ExecutionResult(TypedDict):
47
+ output: str
48
+ returncode: int
49
+ exception_info: str
50
+ extra: NotRequired[dict[str, Any]]
51
+
52
+
53
+ class ContreeEnvironment:
54
+ def __init__(self, *, config_class: type[ContreeEnvironmentConfig] = ContreeEnvironmentConfig, **kwargs):
55
+ """This class executes bash commands in a [ConTree](https://contree.dev) container
56
+ using [contree-sdk](https://github.com/nebius/contree-sdk)"""
57
+
58
+ self.config: ContreeEnvironmentConfig = config_class(**kwargs)
59
+ self.logger = logging.getLogger("coderagent.environment")
60
+
61
+ if isinstance(self.config.contree_config, dict):
62
+ self.config = self.config.model_copy(update={"contree_config": ContreeConfig(**self.config.contree_config)})
63
+
64
+ self.client = ContreeSync(config=self.config.contree_config)
65
+ self.session = self._pull_image().session()
66
+ if self.config.cwd_auto_create:
67
+ self.execute(
68
+ action={"command": f"mkdir -p {self.config.cwd}"},
69
+ cwd="/",
70
+ )
71
+
72
+ def _pull_image(self) -> ContreeImageSync:
73
+ return self.client.images.oci(
74
+ self.config.image,
75
+ tag=self.config.image_tag,
76
+ username=self.config.import_username,
77
+ password=self.config.import_password,
78
+ )
79
+
80
+ def _shell_command(self, command: str) -> str:
81
+ shell_cmd = " ".join(self.config.interpreter)
82
+ return f"{shell_cmd} {shlex.quote(command)}"
83
+
84
+ def execute(self, action: dict, cwd: str = "", *, timeout: int | None = None) -> ExecutionResult:
85
+ """Execute a command in the environment and return the raw output."""
86
+ command = action.get("command")
87
+
88
+ env = {k: v for k in self.config.forward_env if (v := os.getenv(k)) is not None}
89
+ env.update(self.config.env)
90
+
91
+ try:
92
+ self.session.run(
93
+ shell=self._shell_command(command),
94
+ cwd=cwd or self.config.cwd,
95
+ timeout=timeout or self.config.timeout,
96
+ disposable=False,
97
+ env=env or None,
98
+ ).wait()
99
+ output = {
100
+ "output": self.session.stdout + self.session.stderr,
101
+ "returncode": self.session.exit_code,
102
+ "exception_info": "",
103
+ }
104
+ except Exception as e:
105
+ raw_output = getattr(e, "output", None)
106
+ raw_output = (
107
+ raw_output.decode("utf-8", errors="replace") if isinstance(raw_output, bytes) else (raw_output or "")
108
+ )
109
+ extras = {}
110
+ if is_dataclass(e):
111
+ extras = {k: str(v) if not isinstance(v, Number) else v for k, v in asdict(e).items()}
112
+
113
+ output = {
114
+ "output": raw_output,
115
+ "returncode": -1,
116
+ "exception_info": f"An error occurred while executing the command: {e}",
117
+ "extra": {"exception_type": type(e).__name__, "exception": str(e), **extras},
118
+ }
119
+ self._check_finished(output)
120
+ return output
121
+
122
+ def _check_finished(self, output: dict):
123
+ """Raises Submitted if the output indicates task completion."""
124
+ lines = output.get("output", "").lstrip().splitlines(keepends=True)
125
+ if lines and lines[0].strip() == "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" and output["returncode"] == 0:
126
+ submission = "".join(lines[1:])
127
+ raise Submitted(
128
+ {
129
+ "role": "exit",
130
+ "content": submission,
131
+ "extra": {"exit_status": "Submitted", "submission": submission},
132
+ }
133
+ )
134
+
135
+ def get_template_vars(self, **kwargs) -> dict[str, Any]:
136
+ return recursive_merge(self.config.model_dump(), platform.uname()._asdict(), kwargs)
137
+
138
+ def serialize(self) -> dict:
139
+ return {
140
+ "info": {
141
+ "config": {
142
+ "environment": self.config.model_dump(mode="json"),
143
+ "environment_type": f"{self.__class__.__module__}.{self.__class__.__name__}",
144
+ }
145
+ }
146
+ }