agent-docker-sandbox 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hemanth KR
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,296 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-docker-sandbox
3
+ Version: 0.1.0
4
+ Summary: Docker sandbox for AI agents: run LangChain deepagents code, shell commands and file tools in a secure, isolated local container. A local alternative to Daytona, E2B and Modal sandboxes.
5
+ Keywords: docker-sandbox,agent-sandbox,ai-agent-sandbox,code-sandbox,deepagents,langchain,langgraph,docker,sandbox,code-execution,code-interpreter,ai-agents,llm,llm-security,isolation
6
+ Author: Hemanth KR
7
+ Author-email: Hemanth KR <ktrhemanthh@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Typing :: Typed
21
+ Requires-Dist: deepagents>=0.7.38
22
+ Requires-Dist: docker>=7.1
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+
26
+ # agent-docker-sandbox
27
+
28
+ **Docker sandbox for AI agents.** Run [LangChain deepagents](https://github.com/langchain-ai/deepagents)
29
+ code, shell commands and file tools in a secure, isolated Docker container on your own machine.
30
+ A local, free alternative to cloud sandboxes like Daytona, E2B, Modal and Runloop: no account,
31
+ no API key, nothing leaves your machine.
32
+
33
+ ```python
34
+ from deepagents import create_deep_agent
35
+ from agent_docker_sandbox import DockerSandbox
36
+
37
+ with DockerSandbox() as sandbox:
38
+ agent = create_deep_agent(model=model, backend=sandbox)
39
+ agent.invoke({"messages": [{"role": "user", "content": "Write and run a prime sieve"}]})
40
+ ```
41
+
42
+ No Dockerfile or setup needed: agent-docker-sandbox pulls a stock Python image the first time and
43
+ prepares it for you.
44
+
45
+ **Use it when you want to:**
46
+
47
+ - run deepagents (or any LangChain/LangGraph agent) that executes code, without giving it your machine
48
+ - give an AI coding or data-analysis agent a safe place to run Python and shell commands
49
+ - run agent sandboxes locally instead of paying for a hosted sandbox service
50
+
51
+ ## Why agent-docker-sandbox
52
+
53
+ - **Locked down by default:** no network, a non-root user, all Linux capabilities dropped,
54
+ `no-new-privileges`, a read-only root filesystem, and memory, CPU and process limits. You
55
+ loosen what you need instead of remembering to tighten everything.
56
+ - **Everything runs inside the container:** `execute`, `ls`, `read`, `write`, `edit`, `grep`
57
+ and `glob` all go through the container. Paths, permissions and file ownership match what
58
+ the agent's own commands see, and nothing touches the host except the workspace you mount.
59
+ - **Commands can't run away:** each command runs with a time limit. When it times out,
60
+ every process it started is killed too, including ones running in the background. Output
61
+ is streamed and capped, and a command that hits the cap is stopped instead of filling memory.
62
+ - **Workspaces that persist when you want them to:** mount a host folder, or use a Docker
63
+ volume you can reuse across runs, for example one per conversation.
64
+ - **Small and dependency-light:** one module on top of the official Docker SDK.
65
+
66
+ ## Install
67
+
68
+ ```bash
69
+ pip install agent-docker-sandbox
70
+ # or
71
+ uv add agent-docker-sandbox
72
+ ```
73
+
74
+ You need Python 3.11+ and a running Docker daemon (Docker Desktop on Windows and macOS, or
75
+ Docker Engine on Linux).
76
+
77
+ ## Quickstart
78
+
79
+ ```python
80
+ from pathlib import Path
81
+
82
+ from deepagents import create_deep_agent
83
+ from agent_docker_sandbox import DockerSandbox, SandboxConfig
84
+
85
+ sandbox = DockerSandbox(
86
+ SandboxConfig(
87
+ host_dir=Path("work_dir"), # your folder, seen as /workspace inside the sandbox
88
+ timeout=120,
89
+ )
90
+ )
91
+
92
+ agent = create_deep_agent(
93
+ model=model,
94
+ system_prompt=(
95
+ "You are a data analyst. Your working directory is /workspace: "
96
+ "read inputs from there and save every output there."
97
+ ),
98
+ backend=sandbox,
99
+ )
100
+
101
+ try:
102
+ for step in agent.stream({"messages": [{"role": "user", "content": "Summarize sales.csv"}]}):
103
+ print(step)
104
+ finally:
105
+ sandbox.close()
106
+ ```
107
+
108
+ **Tell the agent about `/workspace` in its system prompt.** The root filesystem is read-only,
109
+ so writes anywhere other than `/workspace` and `/tmp` fail with `permission_denied`.
110
+
111
+ The container starts on first use and is removed by `close()`, when a `with` block exits, or
112
+ when the Python process exits. By default agent-docker-sandbox uses `python:3.13-slim` and pulls it if
113
+ it's missing.
114
+
115
+ ## Using your own image
116
+
117
+ The default image has Python's standard library only, and the sandbox has no network, so the
118
+ agent can't `pip install` at run time. When it needs packages, bake them into an image:
119
+
120
+ ```dockerfile
121
+ FROM python:3.13-slim
122
+ RUN pip install --no-cache-dir pandas scipy matplotlib
123
+ ```
124
+
125
+ ```bash
126
+ docker build -t my-agent-image .
127
+ ```
128
+
129
+ ```python
130
+ DockerSandbox(SandboxConfig(image="my-agent-image"))
131
+ ```
132
+
133
+ That's all. You don't need to create a user or a workspace folder: agent-docker-sandbox runs as a
134
+ non-root user and makes the workspace writable for it.
135
+
136
+ Any image with a POSIX `sh` works. What else it has changes what you get:
137
+
138
+ | In the image | Without it |
139
+ |---|---|
140
+ | `python3` | `execute` and file upload/download work, but deepagents' `read`, `edit`, `ls`, `grep` and `glob` tools don't (they run Python helpers in the sandbox) |
141
+ | `timeout`, `setsid -w` (in Debian and Ubuntu images) | Time limits and cleanup still work, enforced from the host instead of inside the container |
142
+
143
+ ## Configuration
144
+
145
+ Everything is set through `SandboxConfig`:
146
+
147
+ | Field | Default | What it does |
148
+ |---|---|---|
149
+ | `image` | `"python:3.13-slim"` | Image to run; pulled automatically if missing |
150
+ | `workdir` | `"/workspace"` | Working directory and workspace mount point |
151
+ | `host_dir` | `None` | Host folder to mount at `workdir`. `None` uses a Docker volume |
152
+ | `volume_name` | `None` | Use this named volume (created if missing) instead of a fresh one |
153
+ | `keep_volume` | `False` | Keep the throwaway volume after `close()` (named volumes are always kept) |
154
+ | `network` | `False` | `True` allows outbound network access |
155
+ | `user` | `"auto"` | Non-root user to run as. `"auto"` uses your own uid:gid when `host_dir` is set on Linux or macOS (so files stay yours and writable), otherwise `1000:1000`. Or give `"uid:gid"`; `None` uses the image's default user |
156
+ | `read_only_rootfs` | `True` | Mount the root filesystem read-only |
157
+ | `tmp_size` | `"256m"` | Size of the writable in-memory `/tmp` |
158
+ | `runtime` | `None` | Container runtime, for example `"runsc"` for gVisor |
159
+ | `memory` | `"512m"` | Memory limit (no swap beyond it) |
160
+ | `cpus` | `1.0` | CPU limit |
161
+ | `pids_limit` | `256` | Maximum number of processes |
162
+ | `timeout` | `120` | Default command time limit, in seconds |
163
+ | `max_output_bytes` | `100_000` | Output cap per command |
164
+ | `env` | `{}` | Extra environment variables |
165
+
166
+ agent-docker-sandbox sets `HOME=/tmp`, `MPLCONFIGDIR` and `UV_CACHE_DIR` under `/tmp`, so tools that
167
+ write caches (matplotlib, uv, pip) work on the read-only filesystem. Values in `env` override
168
+ these.
169
+
170
+ ## Recipes
171
+
172
+ **One persistent workspace per conversation.** Reuse a named volume so the agent finds its
173
+ files again on the next run:
174
+
175
+ ```python
176
+ sandbox = DockerSandbox(
177
+ SandboxConfig(volume_name=f"agent-{thread_id}")
178
+ )
179
+ ```
180
+
181
+ A volume you name yourself is never deleted by agent-docker-sandbox. Remove it with
182
+ `docker volume rm agent-<thread_id>` when you no longer need it.
183
+
184
+ **Allow network access.** For example, so the agent can call an API:
185
+
186
+ ```python
187
+ SandboxConfig(network=True)
188
+ ```
189
+
190
+ **Install packages at run time.** Needs network access and a writable system, so it weakens
191
+ isolation. Prefer [baking packages into the image](#using-your-own-image).
192
+
193
+ ```python
194
+ SandboxConfig(network=True, user=None, read_only_rootfs=False)
195
+ ```
196
+
197
+ **Stronger isolation with gVisor.** On a Linux host with
198
+ [gVisor](https://gvisor.dev/docs/user_guide/install/) installed and registered with Docker:
199
+
200
+ ```python
201
+ SandboxConfig(runtime="runsc")
202
+ ```
203
+
204
+ **Use it without an agent.** The sandbox is a normal deepagents backend, so you can call it
205
+ directly:
206
+
207
+ ```python
208
+ with DockerSandbox() as sbx:
209
+ result = sbx.execute("python -c 'print(2 + 2)'")
210
+ print(result.output, result.exit_code) # "4\n" 0
211
+
212
+ sbx.upload_files([("/workspace/data.csv", b"a,b\n1,2\n")])
213
+ [file] = sbx.download_files(["/workspace/data.csv"])
214
+ print(file.content)
215
+ ```
216
+
217
+ **Clean up after a crash.** Remove containers and throwaway volumes left behind by processes
218
+ that died before closing their sandbox. Volumes you named are kept. It also removes running
219
+ sandboxes, so call it at startup, before creating any:
220
+
221
+ ```python
222
+ DockerSandbox.cleanup_orphans()
223
+ ```
224
+
225
+ **Snapshot a sandbox.** Save the container's filesystem as an image you can start new
226
+ sandboxes from (the workspace volume is not included):
227
+
228
+ ```python
229
+ image_id = sbx.snapshot("my-agent-image", tag="after-setup")
230
+ ```
231
+
232
+ ## Command results
233
+
234
+ `execute()` returns deepagents' `ExecuteResponse`:
235
+
236
+ - `output`: stdout and stderr combined
237
+ - `exit_code`: the command's exit code; `124` means it hit the time limit (on every image)
238
+ - `truncated`: `True` if the output cap was reached and the command was stopped
239
+
240
+ On timeout or truncation, a short note is appended to `output` so the agent knows what
241
+ happened. Pass `timeout=` to `execute()` to override the default for one command.
242
+
243
+ If the container can't start, for example because the image doesn't exist and can't be
244
+ pulled, agent-docker-sandbox raises `agent_docker_sandbox.SandboxError`.
245
+
246
+ ## Security notes
247
+
248
+ agent-docker-sandbox reduces what a misbehaving agent can do, but a container is not a perfect security
249
+ boundary: it shares the host's kernel. For code you really don't trust:
250
+
251
+ - use `runtime="runsc"` (gVisor) on a Linux host, or run Docker inside a VM
252
+ - keep `network=False` unless the agent needs it
253
+ - mount a dedicated workspace folder, never your home directory or a project with secrets
254
+ - keep the resource limits; they stop runaway loops and fork bombs
255
+
256
+ Anyone who can reach the Docker daemon controls the host, so don't expose the daemon to the
257
+ agent.
258
+
259
+ ## FAQ
260
+
261
+ **How do I run deepagents in a Docker sandbox locally?**
262
+ `pip install agent-docker-sandbox`, then pass `DockerSandbox()` as the `backend` of
263
+ `create_deep_agent`. See [Quickstart](#quickstart).
264
+
265
+ **How is this different from Daytona, E2B, Modal or Runloop sandboxes?**
266
+ Those are hosted services: code runs on their servers and you need an account and API key.
267
+ agent-docker-sandbox runs the sandbox on your own machine with Docker, for free, and nothing
268
+ leaves your machine.
269
+
270
+ **How is this different from `deepagents-docker`?**
271
+ Both run deepagents in Docker. agent-docker-sandbox is locked down by default (no network,
272
+ non-root, read-only filesystem, no capabilities) and runs the file tools inside the container
273
+ instead of on the host folder.
274
+
275
+ **Can I use it without deepagents?**
276
+ Yes. `DockerSandbox` works on its own: call `execute()`, `upload_files()` and
277
+ `download_files()` directly. See [Recipes](#recipes).
278
+
279
+ **Does it work on Windows and macOS?**
280
+ Yes, with Docker Desktop. gVisor (`runtime="runsc"`) needs a Linux host.
281
+
282
+ **Is a Docker container secure enough for untrusted code?**
283
+ It stops most accidents and misbehavior. For hostile code, add gVisor or run Docker inside a
284
+ VM. See [Security notes](#security-notes).
285
+
286
+ ## Development
287
+
288
+ ```bash
289
+ git clone https://github.com/<you>/agent-docker-sandbox && cd agent-docker-sandbox
290
+ uv sync
291
+ uv run pytest # needs Docker; pulls python:3.13-slim and alpine, builds docker/Dockerfile
292
+ ```
293
+
294
+ ## License
295
+
296
+ MIT
@@ -0,0 +1,271 @@
1
+ # agent-docker-sandbox
2
+
3
+ **Docker sandbox for AI agents.** Run [LangChain deepagents](https://github.com/langchain-ai/deepagents)
4
+ code, shell commands and file tools in a secure, isolated Docker container on your own machine.
5
+ A local, free alternative to cloud sandboxes like Daytona, E2B, Modal and Runloop: no account,
6
+ no API key, nothing leaves your machine.
7
+
8
+ ```python
9
+ from deepagents import create_deep_agent
10
+ from agent_docker_sandbox import DockerSandbox
11
+
12
+ with DockerSandbox() as sandbox:
13
+ agent = create_deep_agent(model=model, backend=sandbox)
14
+ agent.invoke({"messages": [{"role": "user", "content": "Write and run a prime sieve"}]})
15
+ ```
16
+
17
+ No Dockerfile or setup needed: agent-docker-sandbox pulls a stock Python image the first time and
18
+ prepares it for you.
19
+
20
+ **Use it when you want to:**
21
+
22
+ - run deepagents (or any LangChain/LangGraph agent) that executes code, without giving it your machine
23
+ - give an AI coding or data-analysis agent a safe place to run Python and shell commands
24
+ - run agent sandboxes locally instead of paying for a hosted sandbox service
25
+
26
+ ## Why agent-docker-sandbox
27
+
28
+ - **Locked down by default:** no network, a non-root user, all Linux capabilities dropped,
29
+ `no-new-privileges`, a read-only root filesystem, and memory, CPU and process limits. You
30
+ loosen what you need instead of remembering to tighten everything.
31
+ - **Everything runs inside the container:** `execute`, `ls`, `read`, `write`, `edit`, `grep`
32
+ and `glob` all go through the container. Paths, permissions and file ownership match what
33
+ the agent's own commands see, and nothing touches the host except the workspace you mount.
34
+ - **Commands can't run away:** each command runs with a time limit. When it times out,
35
+ every process it started is killed too, including ones running in the background. Output
36
+ is streamed and capped, and a command that hits the cap is stopped instead of filling memory.
37
+ - **Workspaces that persist when you want them to:** mount a host folder, or use a Docker
38
+ volume you can reuse across runs, for example one per conversation.
39
+ - **Small and dependency-light:** one module on top of the official Docker SDK.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install agent-docker-sandbox
45
+ # or
46
+ uv add agent-docker-sandbox
47
+ ```
48
+
49
+ You need Python 3.11+ and a running Docker daemon (Docker Desktop on Windows and macOS, or
50
+ Docker Engine on Linux).
51
+
52
+ ## Quickstart
53
+
54
+ ```python
55
+ from pathlib import Path
56
+
57
+ from deepagents import create_deep_agent
58
+ from agent_docker_sandbox import DockerSandbox, SandboxConfig
59
+
60
+ sandbox = DockerSandbox(
61
+ SandboxConfig(
62
+ host_dir=Path("work_dir"), # your folder, seen as /workspace inside the sandbox
63
+ timeout=120,
64
+ )
65
+ )
66
+
67
+ agent = create_deep_agent(
68
+ model=model,
69
+ system_prompt=(
70
+ "You are a data analyst. Your working directory is /workspace: "
71
+ "read inputs from there and save every output there."
72
+ ),
73
+ backend=sandbox,
74
+ )
75
+
76
+ try:
77
+ for step in agent.stream({"messages": [{"role": "user", "content": "Summarize sales.csv"}]}):
78
+ print(step)
79
+ finally:
80
+ sandbox.close()
81
+ ```
82
+
83
+ **Tell the agent about `/workspace` in its system prompt.** The root filesystem is read-only,
84
+ so writes anywhere other than `/workspace` and `/tmp` fail with `permission_denied`.
85
+
86
+ The container starts on first use and is removed by `close()`, when a `with` block exits, or
87
+ when the Python process exits. By default agent-docker-sandbox uses `python:3.13-slim` and pulls it if
88
+ it's missing.
89
+
90
+ ## Using your own image
91
+
92
+ The default image has Python's standard library only, and the sandbox has no network, so the
93
+ agent can't `pip install` at run time. When it needs packages, bake them into an image:
94
+
95
+ ```dockerfile
96
+ FROM python:3.13-slim
97
+ RUN pip install --no-cache-dir pandas scipy matplotlib
98
+ ```
99
+
100
+ ```bash
101
+ docker build -t my-agent-image .
102
+ ```
103
+
104
+ ```python
105
+ DockerSandbox(SandboxConfig(image="my-agent-image"))
106
+ ```
107
+
108
+ That's all. You don't need to create a user or a workspace folder: agent-docker-sandbox runs as a
109
+ non-root user and makes the workspace writable for it.
110
+
111
+ Any image with a POSIX `sh` works. What else it has changes what you get:
112
+
113
+ | In the image | Without it |
114
+ |---|---|
115
+ | `python3` | `execute` and file upload/download work, but deepagents' `read`, `edit`, `ls`, `grep` and `glob` tools don't (they run Python helpers in the sandbox) |
116
+ | `timeout`, `setsid -w` (in Debian and Ubuntu images) | Time limits and cleanup still work, enforced from the host instead of inside the container |
117
+
118
+ ## Configuration
119
+
120
+ Everything is set through `SandboxConfig`:
121
+
122
+ | Field | Default | What it does |
123
+ |---|---|---|
124
+ | `image` | `"python:3.13-slim"` | Image to run; pulled automatically if missing |
125
+ | `workdir` | `"/workspace"` | Working directory and workspace mount point |
126
+ | `host_dir` | `None` | Host folder to mount at `workdir`. `None` uses a Docker volume |
127
+ | `volume_name` | `None` | Use this named volume (created if missing) instead of a fresh one |
128
+ | `keep_volume` | `False` | Keep the throwaway volume after `close()` (named volumes are always kept) |
129
+ | `network` | `False` | `True` allows outbound network access |
130
+ | `user` | `"auto"` | Non-root user to run as. `"auto"` uses your own uid:gid when `host_dir` is set on Linux or macOS (so files stay yours and writable), otherwise `1000:1000`. Or give `"uid:gid"`; `None` uses the image's default user |
131
+ | `read_only_rootfs` | `True` | Mount the root filesystem read-only |
132
+ | `tmp_size` | `"256m"` | Size of the writable in-memory `/tmp` |
133
+ | `runtime` | `None` | Container runtime, for example `"runsc"` for gVisor |
134
+ | `memory` | `"512m"` | Memory limit (no swap beyond it) |
135
+ | `cpus` | `1.0` | CPU limit |
136
+ | `pids_limit` | `256` | Maximum number of processes |
137
+ | `timeout` | `120` | Default command time limit, in seconds |
138
+ | `max_output_bytes` | `100_000` | Output cap per command |
139
+ | `env` | `{}` | Extra environment variables |
140
+
141
+ agent-docker-sandbox sets `HOME=/tmp`, `MPLCONFIGDIR` and `UV_CACHE_DIR` under `/tmp`, so tools that
142
+ write caches (matplotlib, uv, pip) work on the read-only filesystem. Values in `env` override
143
+ these.
144
+
145
+ ## Recipes
146
+
147
+ **One persistent workspace per conversation.** Reuse a named volume so the agent finds its
148
+ files again on the next run:
149
+
150
+ ```python
151
+ sandbox = DockerSandbox(
152
+ SandboxConfig(volume_name=f"agent-{thread_id}")
153
+ )
154
+ ```
155
+
156
+ A volume you name yourself is never deleted by agent-docker-sandbox. Remove it with
157
+ `docker volume rm agent-<thread_id>` when you no longer need it.
158
+
159
+ **Allow network access.** For example, so the agent can call an API:
160
+
161
+ ```python
162
+ SandboxConfig(network=True)
163
+ ```
164
+
165
+ **Install packages at run time.** Needs network access and a writable system, so it weakens
166
+ isolation. Prefer [baking packages into the image](#using-your-own-image).
167
+
168
+ ```python
169
+ SandboxConfig(network=True, user=None, read_only_rootfs=False)
170
+ ```
171
+
172
+ **Stronger isolation with gVisor.** On a Linux host with
173
+ [gVisor](https://gvisor.dev/docs/user_guide/install/) installed and registered with Docker:
174
+
175
+ ```python
176
+ SandboxConfig(runtime="runsc")
177
+ ```
178
+
179
+ **Use it without an agent.** The sandbox is a normal deepagents backend, so you can call it
180
+ directly:
181
+
182
+ ```python
183
+ with DockerSandbox() as sbx:
184
+ result = sbx.execute("python -c 'print(2 + 2)'")
185
+ print(result.output, result.exit_code) # "4\n" 0
186
+
187
+ sbx.upload_files([("/workspace/data.csv", b"a,b\n1,2\n")])
188
+ [file] = sbx.download_files(["/workspace/data.csv"])
189
+ print(file.content)
190
+ ```
191
+
192
+ **Clean up after a crash.** Remove containers and throwaway volumes left behind by processes
193
+ that died before closing their sandbox. Volumes you named are kept. It also removes running
194
+ sandboxes, so call it at startup, before creating any:
195
+
196
+ ```python
197
+ DockerSandbox.cleanup_orphans()
198
+ ```
199
+
200
+ **Snapshot a sandbox.** Save the container's filesystem as an image you can start new
201
+ sandboxes from (the workspace volume is not included):
202
+
203
+ ```python
204
+ image_id = sbx.snapshot("my-agent-image", tag="after-setup")
205
+ ```
206
+
207
+ ## Command results
208
+
209
+ `execute()` returns deepagents' `ExecuteResponse`:
210
+
211
+ - `output`: stdout and stderr combined
212
+ - `exit_code`: the command's exit code; `124` means it hit the time limit (on every image)
213
+ - `truncated`: `True` if the output cap was reached and the command was stopped
214
+
215
+ On timeout or truncation, a short note is appended to `output` so the agent knows what
216
+ happened. Pass `timeout=` to `execute()` to override the default for one command.
217
+
218
+ If the container can't start, for example because the image doesn't exist and can't be
219
+ pulled, agent-docker-sandbox raises `agent_docker_sandbox.SandboxError`.
220
+
221
+ ## Security notes
222
+
223
+ agent-docker-sandbox reduces what a misbehaving agent can do, but a container is not a perfect security
224
+ boundary: it shares the host's kernel. For code you really don't trust:
225
+
226
+ - use `runtime="runsc"` (gVisor) on a Linux host, or run Docker inside a VM
227
+ - keep `network=False` unless the agent needs it
228
+ - mount a dedicated workspace folder, never your home directory or a project with secrets
229
+ - keep the resource limits; they stop runaway loops and fork bombs
230
+
231
+ Anyone who can reach the Docker daemon controls the host, so don't expose the daemon to the
232
+ agent.
233
+
234
+ ## FAQ
235
+
236
+ **How do I run deepagents in a Docker sandbox locally?**
237
+ `pip install agent-docker-sandbox`, then pass `DockerSandbox()` as the `backend` of
238
+ `create_deep_agent`. See [Quickstart](#quickstart).
239
+
240
+ **How is this different from Daytona, E2B, Modal or Runloop sandboxes?**
241
+ Those are hosted services: code runs on their servers and you need an account and API key.
242
+ agent-docker-sandbox runs the sandbox on your own machine with Docker, for free, and nothing
243
+ leaves your machine.
244
+
245
+ **How is this different from `deepagents-docker`?**
246
+ Both run deepagents in Docker. agent-docker-sandbox is locked down by default (no network,
247
+ non-root, read-only filesystem, no capabilities) and runs the file tools inside the container
248
+ instead of on the host folder.
249
+
250
+ **Can I use it without deepagents?**
251
+ Yes. `DockerSandbox` works on its own: call `execute()`, `upload_files()` and
252
+ `download_files()` directly. See [Recipes](#recipes).
253
+
254
+ **Does it work on Windows and macOS?**
255
+ Yes, with Docker Desktop. gVisor (`runtime="runsc"`) needs a Linux host.
256
+
257
+ **Is a Docker container secure enough for untrusted code?**
258
+ It stops most accidents and misbehavior. For hostile code, add gVisor or run Docker inside a
259
+ VM. See [Security notes](#security-notes).
260
+
261
+ ## Development
262
+
263
+ ```bash
264
+ git clone https://github.com/<you>/agent-docker-sandbox && cd agent-docker-sandbox
265
+ uv sync
266
+ uv run pytest # needs Docker; pulls python:3.13-slim and alpine, builds docker/Dockerfile
267
+ ```
268
+
269
+ ## License
270
+
271
+ MIT
@@ -0,0 +1,59 @@
1
+ [project]
2
+ name = "agent-docker-sandbox"
3
+ version = "0.1.0"
4
+ description = "Docker sandbox for AI agents: run LangChain deepagents code, shell commands and file tools in a secure, isolated local container. A local alternative to Daytona, E2B and Modal sandboxes."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "docker-sandbox",
11
+ "agent-sandbox",
12
+ "ai-agent-sandbox",
13
+ "code-sandbox",
14
+ "deepagents",
15
+ "langchain",
16
+ "langgraph",
17
+ "docker",
18
+ "sandbox",
19
+ "code-execution",
20
+ "code-interpreter",
21
+ "ai-agents",
22
+ "llm",
23
+ "llm-security",
24
+ "isolation",
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 3 - Alpha",
28
+ "Intended Audience :: Developers",
29
+ "Operating System :: OS Independent",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Programming Language :: Python :: 3.14",
35
+ "Topic :: Security",
36
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
37
+ "Typing :: Typed",
38
+ ]
39
+ dependencies = [
40
+ "deepagents>=0.7.38",
41
+ "docker>=7.1",
42
+ ]
43
+
44
+ [[project.authors]]
45
+ name = "Hemanth KR"
46
+ email = "ktrhemanthh@gmail.com"
47
+
48
+ [build-system]
49
+ requires = ["uv_build>=0.13.6,<0.14.0"]
50
+ build-backend = "uv_build"
51
+
52
+ [[tool.uv.index]]
53
+ name = "testpypi"
54
+ url = "https://test.pypi.org/simple/"
55
+ publish-url = "https://test.pypi.org/legacy/"
56
+ explicit = true
57
+
58
+ [dependency-groups]
59
+ dev = ["pytest>=9.2.0"]
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "agent-docker-sandbox"
3
+ version = "0.1.0"
4
+ description = "Docker sandbox for AI agents: run LangChain deepagents code, shell commands and file tools in a secure, isolated local container. A local alternative to Daytona, E2B and Modal sandboxes."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Hemanth KR", email = "ktrhemanthh@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.11"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ keywords = ["docker-sandbox", "agent-sandbox", "ai-agent-sandbox", "code-sandbox", "deepagents", "langchain", "langgraph", "docker", "sandbox", "code-execution", "code-interpreter", "ai-agents", "llm", "llm-security", "isolation"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Topic :: Security",
23
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "deepagents>=0.7.38",
28
+ "docker>=7.1",
29
+ ]
30
+
31
+ [build-system]
32
+ requires = ["uv_build>=0.13.6,<0.14.0"]
33
+ build-backend = "uv_build"
34
+
35
+ [[tool.uv.index]]
36
+ # Only used for test uploads: `uv publish --index testpypi`
37
+ name = "testpypi"
38
+ url = "https://test.pypi.org/simple/"
39
+ publish-url = "https://test.pypi.org/legacy/"
40
+ explicit = true
41
+
42
+ [dependency-groups]
43
+ dev = [
44
+ "pytest>=9.2.0",
45
+ ]
@@ -0,0 +1,5 @@
1
+ """A hardened Docker sandbox backend for deepagents."""
2
+
3
+ from agent_docker_sandbox.engine import DEFAULT_IMAGE, DockerSandbox, SandboxConfig, SandboxError
4
+
5
+ __all__ = ["DEFAULT_IMAGE", "DockerSandbox", "SandboxConfig", "SandboxError"]
@@ -0,0 +1,532 @@
1
+ """A Docker-based sandbox engine for deepagents.
2
+
3
+ Drives the Docker Engine directly through the Docker SDK (no API server). One
4
+ `DockerSandbox` owns one long-lived container; every agent tool call
5
+ (`execute`, `ls`, `read`, `write`, `edit`, `grep`, `glob`) runs inside it.
6
+
7
+ Only four primitives are implemented here: `execute`, `upload_files`,
8
+ `download_files` and `id`. `BaseSandbox` builds all file tools on top of them.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import atexit
14
+ import io
15
+ import logging
16
+ import os
17
+ import posixpath
18
+ import shlex
19
+ import tarfile
20
+ import threading
21
+ import time
22
+ import uuid
23
+ import weakref
24
+ from collections import defaultdict
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+
28
+ import docker
29
+ from docker.errors import APIError, DockerException, NotFound
30
+ from docker.models.containers import Container
31
+ from deepagents.backends.protocol import (
32
+ ExecuteResponse,
33
+ FileDownloadResponse,
34
+ FileUploadResponse,
35
+ )
36
+ from deepagents.backends.sandbox import BaseSandbox
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+ LABEL = "agent-docker-sandbox"
41
+ DEFAULT_IMAGE = "python:3.13-slim"
42
+ TIMEOUT_EXIT_CODE = 124 # reported for every timeout, like GNU `timeout`
43
+ _TIMEOUT_EXIT_CODES = {124, 137, 143}
44
+ _HOST_GRACE_SECONDS = 10 # host-side safety margin on top of the in-container timeout
45
+
46
+ # Runs inside the container. When available, `setsid -w` puts the command in its
47
+ # own session, and `timeout` enforces the wall-clock limit (TERM, then KILL after
48
+ # 2s). Without them the host side enforces the limit. The pid file holds the
49
+ # wrapper shell's pid (= the session id under setsid) so the host can kill the
50
+ # command early, e.g. when the output cap is hit.
51
+ _WRAPPER_TEMPLATE = 'echo $$ > "$SBX_PID_FILE"; {run}; rc=$?; rm -f "$SBX_PID_FILE"; exit $rc'
52
+ _RUN_WITH_TIMEOUT = 'timeout -k 2 "$SBX_TIMEOUT" sh -c "$SBX_CMD"'
53
+ _RUN_PLAIN = 'sh -c "$SBX_CMD"'
54
+ # Kills everything the command started. Killing the process *group* is not enough:
55
+ # GNU `timeout` moves itself and the command into a new group. The session survives
56
+ # that, so kill every process whose session (or, without setsid, parent) is the
57
+ # wrapper. /proc/PID/stat fields after "comm)": state ppid pgrp session ...
58
+ # Uses `kill -s KILL`, the one spelling both dash and BusyBox accept.
59
+ _KILL_TREE = r"""
60
+ f=$1; sid=$(cat "$f" 2>/dev/null) || exit 0; rm -f "$f"
61
+ for s in /proc/[0-9]*/stat; do
62
+ l=$(cat "$s" 2>/dev/null) || continue
63
+ set -- ${l##*) }
64
+ if [ "$4" = "$sid" ] || [ "$2" = "$sid" ]; then
65
+ p=${s#/proc/}; kill -s KILL "${p%/stat}" 2>/dev/null
66
+ fi
67
+ done
68
+ kill -s KILL "$sid" 2>/dev/null; true
69
+ """
70
+ # Probes what the image offers, once per container.
71
+ _PROBE = (
72
+ "setsid -w true 2>/dev/null && echo setsid; "
73
+ "command -v timeout >/dev/null 2>&1 && echo timeout; "
74
+ "command -v python3 >/dev/null 2>&1 && echo python3; "
75
+ 'test -w "$1" && echo writable; true'
76
+ )
77
+ # Keeps the container alive; portable to images without `sleep infinity`.
78
+ _KEEPALIVE = ["sh", "-c", "while :; do sleep 3600; done"]
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class SandboxConfig:
83
+ """How a sandbox container is created and constrained."""
84
+
85
+ image: str = DEFAULT_IMAGE # any image with `sh`; python3 is needed for file tools
86
+ workdir: str = "/workspace"
87
+
88
+ # Workspace storage: bind-mount a host folder, or (default) use a named volume.
89
+ host_dir: Path | None = None
90
+ volume_name: str | None = None # reuse a volume across runs, e.g. one per thread_id
91
+ keep_volume: bool = False # keep the named volume after close()
92
+
93
+ # Isolation
94
+ network: bool = False # False = no network at all
95
+ # "auto": your own uid:gid when mounting host_dir on Linux/macOS (so files in it stay
96
+ # yours and writable), otherwise 1000:1000. Or "uid:gid" explicitly; None = image default.
97
+ user: str | None = "auto"
98
+ read_only_rootfs: bool = True
99
+ tmp_size: str = "256m"
100
+ runtime: str | None = None # e.g. "runsc" for gVisor (Linux hosts only)
101
+
102
+ # Resource limits
103
+ memory: str = "512m"
104
+ cpus: float = 1.0
105
+ pids_limit: int = 256
106
+
107
+ # Command defaults
108
+ timeout: int = 120
109
+ max_output_bytes: int = 100_000
110
+
111
+ env: dict[str, str] = field(default_factory=dict)
112
+
113
+
114
+ class SandboxError(RuntimeError):
115
+ pass
116
+
117
+
118
+ class DockerSandbox(BaseSandbox):
119
+ """A deepagents sandbox backend backed by one Docker container."""
120
+
121
+ def __init__(
122
+ self, config: SandboxConfig | None = None, *, client: docker.DockerClient | None = None
123
+ ):
124
+ self.config = config = config or SandboxConfig()
125
+ self._client = client or docker.from_env()
126
+ self._sid = uuid.uuid4().hex[:12]
127
+ self._container: Container | None = None
128
+ self._created_volume: str | None = None
129
+ self._lock = threading.Lock()
130
+ self._closed = False
131
+ self._has_setsid = self._has_timeout = False
132
+ self._user = _resolve_user(config)
133
+ self._uid, self._gid = _parse_user(self._user)
134
+ atexit.register(_close_ref, weakref.ref(self))
135
+
136
+ # ------------------------------------------------------------------ lifecycle
137
+
138
+ @property
139
+ def id(self) -> str:
140
+ return self._sid
141
+
142
+ @property
143
+ def container_name(self) -> str:
144
+ return f"agent-docker-sandbox-{self._sid}"
145
+
146
+ def start(self) -> DockerSandbox:
147
+ self._ensure_started()
148
+ return self
149
+
150
+ def _ensure_started(self) -> Container:
151
+ if self._container is not None:
152
+ return self._container
153
+ with self._lock:
154
+ if self._container is not None:
155
+ return self._container
156
+ if self._closed:
157
+ raise SandboxError("sandbox is closed")
158
+ self._container = self._start_container()
159
+ return self._container
160
+
161
+ def _start_container(self) -> Container:
162
+ cfg = self.config
163
+ self._ensure_image()
164
+
165
+ if cfg.host_dir is not None:
166
+ host = Path(cfg.host_dir).resolve()
167
+ host.mkdir(parents=True, exist_ok=True)
168
+ volumes = {str(host): {"bind": cfg.workdir, "mode": "rw"}}
169
+ else:
170
+ name = cfg.volume_name or self.container_name
171
+ try:
172
+ self._client.volumes.get(name)
173
+ except NotFound:
174
+ # Only throwaway volumes are deleted on close() or by cleanup_orphans();
175
+ # a volume the caller named persists.
176
+ ephemeral = cfg.volume_name is None
177
+ labels = {LABEL: "1", f"{LABEL}.ephemeral": "1" if ephemeral else "0"}
178
+ self._client.volumes.create(name, labels=labels)
179
+ if ephemeral:
180
+ self._created_volume = name
181
+ volumes = {name: {"bind": cfg.workdir, "mode": "rw"}}
182
+
183
+ env = {
184
+ # The rootfs is read-only, so point every tool's scratch space at /tmp.
185
+ "HOME": "/tmp",
186
+ "MPLCONFIGDIR": "/tmp/.matplotlib",
187
+ "UV_CACHE_DIR": "/tmp/.uv-cache",
188
+ "PYTHONDONTWRITEBYTECODE": "1",
189
+ **cfg.env,
190
+ }
191
+
192
+ kwargs: dict = dict(
193
+ image=cfg.image,
194
+ command=_KEEPALIVE,
195
+ name=self.container_name,
196
+ detach=True,
197
+ init=True, # reaps orphaned processes so they don't eat the pids limit
198
+ working_dir=cfg.workdir,
199
+ volumes=volumes,
200
+ environment=env,
201
+ labels={LABEL: "1", f"{LABEL}.id": self._sid},
202
+ network_mode="bridge" if cfg.network else "none",
203
+ mem_limit=cfg.memory,
204
+ memswap_limit=cfg.memory, # no swap beyond the memory limit
205
+ nano_cpus=int(cfg.cpus * 1e9),
206
+ pids_limit=cfg.pids_limit,
207
+ cap_drop=["ALL"],
208
+ security_opt=["no-new-privileges"],
209
+ read_only=cfg.read_only_rootfs,
210
+ tmpfs={"/tmp": f"rw,exec,nosuid,nodev,size={cfg.tmp_size},mode=1777"},
211
+ )
212
+ if self._user:
213
+ kwargs["user"] = self._user
214
+ if cfg.runtime:
215
+ kwargs["runtime"] = cfg.runtime
216
+
217
+ try:
218
+ container = self._client.containers.run(**kwargs)
219
+ self._prepare(container, volumes)
220
+ except DockerException as e:
221
+ self._remove_quietly()
222
+ raise SandboxError(f"failed to start sandbox container: {e}") from e
223
+ log.info("sandbox %s started (%s)", self._sid, cfg.image)
224
+ return container
225
+
226
+ def _ensure_image(self) -> None:
227
+ image = self.config.image
228
+ try:
229
+ self._client.images.get(image)
230
+ return
231
+ except NotFound:
232
+ pass
233
+ log.info("pulling image %s", image)
234
+ try:
235
+ self._client.images.pull(image)
236
+ except DockerException as e:
237
+ raise SandboxError(f"image {image!r} not found locally and could not be pulled: {e}") from e
238
+
239
+ def _probe(self, container: Container) -> set[str]:
240
+ _, out = container.exec_run(["sh", "-c", _PROBE, "sh", self.config.workdir])
241
+ return set((out or b"").decode(errors="replace").split())
242
+
243
+ def _prepare(self, container: Container, volumes: dict) -> None:
244
+ """Detect what the image supports and make sure the workspace is writable."""
245
+ found = self._probe(container)
246
+ self._has_setsid = "setsid" in found
247
+ self._has_timeout = "timeout" in found
248
+
249
+ if "writable" not in found and self.config.host_dir is None and self._uid:
250
+ # A new volume, or one mounted where the image has a root-owned dir, belongs
251
+ # to root. Hand its top directory to the sandbox user with a one-off container.
252
+ self._client.containers.run(
253
+ self.config.image,
254
+ entrypoint=["chown", f"{self._uid}:{self._gid}", self.config.workdir],
255
+ command=[],
256
+ user="0:0",
257
+ volumes=volumes,
258
+ network_mode="none",
259
+ cap_drop=["ALL"],
260
+ cap_add=["CHOWN"],
261
+ security_opt=["no-new-privileges"],
262
+ labels={LABEL: "1"},
263
+ remove=True,
264
+ )
265
+ found = self._probe(container)
266
+
267
+ if "writable" not in found:
268
+ log.warning("workspace %s is not writable by user %s", self.config.workdir, self._user)
269
+ if "python3" not in found:
270
+ log.warning(
271
+ "image %s has no python3: execute() works, but deepagents' file tools "
272
+ "(read, edit, ls, grep, glob) need it",
273
+ self.config.image,
274
+ )
275
+
276
+ def close(self) -> None:
277
+ with self._lock:
278
+ if self._closed:
279
+ return
280
+ self._closed = True
281
+ self._remove_quietly()
282
+ self._container = None
283
+
284
+ def _remove_quietly(self) -> None:
285
+ try:
286
+ self._client.containers.get(self.container_name).remove(force=True)
287
+ except DockerException:
288
+ pass
289
+ if self._created_volume and not self.config.keep_volume:
290
+ try:
291
+ self._client.volumes.get(self._created_volume).remove(force=True)
292
+ except DockerException:
293
+ pass
294
+
295
+ def __enter__(self) -> DockerSandbox:
296
+ return self.start()
297
+
298
+ def __exit__(self, *_exc: object) -> None:
299
+ self.close()
300
+
301
+ @classmethod
302
+ def cleanup_orphans(cls, client: docker.DockerClient | None = None) -> int:
303
+ """Remove sandbox containers, and their throwaway volumes, left behind by crashed
304
+ processes. Volumes created with `volume_name` are kept. Don't call this while
305
+ other sandboxes are running: their containers are removed too.
306
+
307
+ Returns the number of containers and volumes removed.
308
+ """
309
+ client = client or docker.from_env()
310
+ removed = 0
311
+ for c in client.containers.list(all=True, filters={"label": LABEL}):
312
+ c.remove(force=True)
313
+ removed += 1
314
+ for v in client.volumes.list(filters={"label": f"{LABEL}.ephemeral=1"}):
315
+ try:
316
+ v.remove(force=True)
317
+ removed += 1
318
+ except DockerException:
319
+ pass # still in use
320
+ return removed
321
+
322
+ def snapshot(self, repository: str, tag: str = "latest") -> str:
323
+ """Commit the container's filesystem to an image (the workspace volume is not included)."""
324
+ image = self._ensure_started().commit(repository=repository, tag=tag)
325
+ return image.id
326
+
327
+ # ------------------------------------------------------------------ execute
328
+
329
+ def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
330
+ container = self._ensure_started()
331
+ api = self._client.api
332
+ limit = timeout if timeout and timeout > 0 else self.config.timeout
333
+ cap = self.config.max_output_bytes
334
+ pid_file = f"/tmp/.agent-docker-sandbox-exec-{uuid.uuid4().hex}.pid"
335
+
336
+ script = _WRAPPER_TEMPLATE.format(run=_RUN_WITH_TIMEOUT if self._has_timeout else _RUN_PLAIN)
337
+ argv = ["setsid", "-w", "sh", "-c", script] if self._has_setsid else ["sh", "-c", script]
338
+ exec_id = api.exec_create(
339
+ container.id,
340
+ argv,
341
+ environment={"SBX_CMD": command, "SBX_TIMEOUT": str(limit), "SBX_PID_FILE": pid_file},
342
+ workdir=self.config.workdir,
343
+ stdout=True,
344
+ stderr=True,
345
+ )["Id"]
346
+ stream = api.exec_start(exec_id, stream=True, demux=False)
347
+
348
+ chunks: list[bytes] = []
349
+ size = 0
350
+ capped = threading.Event()
351
+
352
+ def pump() -> None:
353
+ # Keep reading to EOF even past the cap: Docker blocks the exec (and any
354
+ # inspect of it) while its output stream has unread data.
355
+ nonlocal size
356
+ for chunk in stream:
357
+ if capped.is_set():
358
+ continue
359
+ chunks.append(chunk)
360
+ size += len(chunk)
361
+ if size > cap:
362
+ capped.set()
363
+
364
+ start = time.monotonic()
365
+ reader = threading.Thread(target=pump, daemon=True)
366
+ reader.start()
367
+ # With `timeout` in the image the limit is enforced inside the container and the
368
+ # host only steps in if that fails; without it the host enforces it directly.
369
+ deadline = start + (limit + _HOST_GRACE_SECONDS if self._has_timeout else limit)
370
+ while reader.is_alive() and not capped.is_set() and time.monotonic() < deadline:
371
+ reader.join(0.05)
372
+ host_timed_out = reader.is_alive() and not capped.is_set()
373
+
374
+ if capped.is_set() or host_timed_out:
375
+ self._kill_group(container, pid_file)
376
+ reader.join(5)
377
+
378
+ exit_code = self._wait_exit_code(exec_id)
379
+ output = b"".join(chunks)[:cap].decode("utf-8", errors="replace")
380
+
381
+ if capped.is_set():
382
+ output += f"\n[output exceeded {cap} bytes; command was terminated]"
383
+ elif host_timed_out or (
384
+ # GNU timeout exits 124; BusyBox's exits with the signal status (143 TERM, 137 KILL).
385
+ exit_code in _TIMEOUT_EXIT_CODES and time.monotonic() - start >= limit
386
+ ):
387
+ output += f"\n[command timed out after {limit}s]"
388
+ exit_code = TIMEOUT_EXIT_CODE
389
+
390
+ return ExecuteResponse(output=output, exit_code=exit_code, truncated=capped.is_set())
391
+
392
+ def _kill_group(self, container: Container, pid_file: str) -> None:
393
+ # Detached, so a slow or stuck Docker call can never block execute().
394
+ api = self._client.api
395
+ try:
396
+ kill_id = api.exec_create(container.id, ["sh", "-c", _KILL_TREE, "sh", pid_file])["Id"]
397
+ api.exec_start(kill_id, detach=True)
398
+ except DockerException:
399
+ return
400
+ self._wait_exit_code(kill_id)
401
+
402
+ def _wait_exit_code(self, exec_id: str, wait: float = 5.0) -> int | None:
403
+ """Exit code of an exec, waiting briefly for it to finish; None if it hasn't."""
404
+ deadline = time.monotonic() + wait
405
+ while True:
406
+ try:
407
+ info = self._client.api.exec_inspect(exec_id)
408
+ except DockerException:
409
+ return None
410
+ if not info.get("Running") or time.monotonic() >= deadline:
411
+ return info.get("ExitCode")
412
+ time.sleep(0.05)
413
+
414
+ # ------------------------------------------------------------------ files
415
+
416
+ def _resolve(self, path: str) -> str | None:
417
+ if not path or "\x00" in path:
418
+ return None
419
+ if not path.startswith("/"):
420
+ path = posixpath.join(self.config.workdir, path)
421
+ return posixpath.normpath(path)
422
+
423
+ def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
424
+ container = self._ensure_started()
425
+ errors: dict[str, str | None] = {}
426
+ by_dir: dict[str, list[tuple[str, str, bytes]]] = defaultdict(list)
427
+
428
+ for path, data in files:
429
+ resolved = self._resolve(path)
430
+ if resolved is None or resolved == "/":
431
+ errors[path] = "invalid_path"
432
+ continue
433
+ by_dir[posixpath.dirname(resolved)].append((path, posixpath.basename(resolved), data))
434
+
435
+ if by_dir:
436
+ # Create parent dirs as the sandbox user, so the agent owns them.
437
+ mkdir = self.execute("mkdir -p -- " + " ".join(shlex.quote(d) for d in by_dir))
438
+ if mkdir.exit_code != 0:
439
+ log.debug("mkdir failed: %s", mkdir.output)
440
+
441
+ for directory, items in by_dir.items():
442
+ buf = io.BytesIO()
443
+ with tarfile.open(fileobj=buf, mode="w") as tar:
444
+ for _, name, data in items:
445
+ info = tarfile.TarInfo(name)
446
+ info.size = len(data)
447
+ info.mode = 0o644
448
+ info.uid, info.gid = self._uid, self._gid
449
+ info.mtime = int(time.time())
450
+ tar.addfile(info, io.BytesIO(data))
451
+ # Extract into the parent dir itself: Docker refuses archives aimed at a
452
+ # read-only rootfs path even when the entries would land in a volume.
453
+ try:
454
+ container.put_archive(directory, buf.getvalue())
455
+ err = None
456
+ except NotFound:
457
+ err = "invalid_path"
458
+ except APIError as e:
459
+ err = _map_api_error(e)
460
+ for original, _, _ in items:
461
+ errors[original] = err
462
+
463
+ return [FileUploadResponse(path=p, error=errors.get(p)) for p, _ in files]
464
+
465
+ def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
466
+ container = self._ensure_started()
467
+ results = []
468
+ for path in paths:
469
+ resolved = self._resolve(path)
470
+ if resolved is None:
471
+ results.append(FileDownloadResponse(path=path, error="invalid_path"))
472
+ continue
473
+ try:
474
+ stream, stat = container.get_archive(resolved)
475
+ except NotFound:
476
+ results.append(FileDownloadResponse(path=path, error="file_not_found"))
477
+ continue
478
+ except APIError as e:
479
+ results.append(FileDownloadResponse(path=path, error=_map_api_error(e)))
480
+ continue
481
+
482
+ if stat.get("mode", 0) & (1 << 31): # Go's os.ModeDir bit
483
+ results.append(FileDownloadResponse(path=path, error="is_directory"))
484
+ continue
485
+
486
+ with tarfile.open(fileobj=io.BytesIO(b"".join(stream))) as tar:
487
+ member = tar.next()
488
+ extracted = tar.extractfile(member) if member else None
489
+ if extracted is None:
490
+ results.append(FileDownloadResponse(path=path, error="file_not_found"))
491
+ else:
492
+ results.append(FileDownloadResponse(path=path, content=extracted.read()))
493
+ return results
494
+
495
+
496
+ _FALLBACK_USER = "1000:1000"
497
+
498
+
499
+ def _resolve_user(config: SandboxConfig) -> str | None:
500
+ if config.user != "auto":
501
+ return config.user
502
+ # A bind-mounted host folder keeps its host ownership on Linux. Running as the host
503
+ # user keeps it writable and leaves files owned by you. Never map to host root.
504
+ getuid = getattr(os, "getuid", None) # absent on Windows, where Docker Desktop maps ownership
505
+ if config.host_dir is not None and getuid is not None and getuid() != 0:
506
+ return f"{getuid()}:{os.getgid()}"
507
+ return _FALLBACK_USER
508
+
509
+
510
+ def _parse_user(user: str | None) -> tuple[int, int]:
511
+ if not user:
512
+ return 0, 0
513
+ uid, _, gid = user.partition(":")
514
+ try:
515
+ return int(uid), int(gid or uid)
516
+ except ValueError:
517
+ return 0, 0 # named user: Docker resolves ownership itself
518
+
519
+
520
+ def _map_api_error(e: APIError) -> str:
521
+ text = str(e).lower()
522
+ if "read-only" in text or "permission" in text:
523
+ return "permission_denied"
524
+ if "is a directory" in text or "not a directory" in text:
525
+ return "is_directory"
526
+ return str(e)
527
+
528
+
529
+ def _close_ref(ref: weakref.ReferenceType[DockerSandbox]) -> None:
530
+ sandbox = ref()
531
+ if sandbox is not None:
532
+ sandbox.close()