render-lab-tasks-e2b 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.
- render_lab_tasks_e2b-0.1.0/.gitignore +11 -0
- render_lab_tasks_e2b-0.1.0/LICENSE +21 -0
- render_lab_tasks_e2b-0.1.0/PKG-INFO +48 -0
- render_lab_tasks_e2b-0.1.0/README.md +33 -0
- render_lab_tasks_e2b-0.1.0/pyproject.toml +22 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/__init__.py +1 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/_app.py +3 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/client.py +482 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/create_sandbox.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/get_sandbox.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/get_sandbox_logs.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/get_sandbox_metrics.py +20 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/kill_sandbox.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/list_files.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/pause_sandbox.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/py.typed +0 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/read_file.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/resume_sandbox.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/retry.py +3 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/run_code.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/run_command.py +18 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/tasks.py +41 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/types.py +231 -0
- render_lab_tasks_e2b-0.1.0/src/render_lab_tasks_e2b/write_files.py +18 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Render Lab
|
|
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,48 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: render-lab-tasks-e2b
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: e2b tasks for Render Workflows
|
|
5
|
+
Project-URL: Repository, https://github.com/render-lab/render-tasks-python
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Requires-Dist: e2b-code-interpreter==2.9.2
|
|
10
|
+
Requires-Dist: e2b==2.46.4
|
|
11
|
+
Requires-Dist: httpx<0.29,>=0.28
|
|
12
|
+
Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
|
|
13
|
+
Requires-Dist: render==1.0.1
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# render-lab-tasks-e2b
|
|
17
|
+
|
|
18
|
+
Twelve E2B sandbox lifecycle, execution, filesystem, logs, and metrics tasks.
|
|
19
|
+
Wrapped tasks and raw injectable implementations live in `render_lab_tasks_e2b.tasks`.
|
|
20
|
+
The root does not register tasks or read credentials.
|
|
21
|
+
|
|
22
|
+
## Environment
|
|
23
|
+
|
|
24
|
+
`E2B_API_KEY` is required lazily. `E2B_API_URL` optionally overrides the control-plane
|
|
25
|
+
API and logs endpoint. The adapter defaults `E2B_CONNECTION_RETRIES` to `0` before
|
|
26
|
+
loading the SDK. If your application imports E2B independently, set that variable
|
|
27
|
+
to `0` before starting the process; the adapter rejects an SDK already initialized
|
|
28
|
+
with retries. The SDK versions are pinned because this setting is captured at import.
|
|
29
|
+
|
|
30
|
+
## Behavior and verification
|
|
31
|
+
|
|
32
|
+
Create finds running or paused sandboxes by caller idempotency key. Pause, resume,
|
|
33
|
+
and kill use the official async SDK. Task timeout fields stay in milliseconds and
|
|
34
|
+
are converted to SDK seconds. Nonzero command exits return their exit code/output.
|
|
35
|
+
Code, text, binary, and collection results use explicit limits. File metadata is
|
|
36
|
+
checked before reading, then the stream is checked again and closed on overflow.
|
|
37
|
+
No file is written onto the workflow host. Execution result text shares one budget,
|
|
38
|
+
and the complete code result is capped at 4 MB. See ADR-0017 for stricter bounds.
|
|
39
|
+
|
|
40
|
+
Source fixtures compare all twelve tasks and SDK arguments independently with TS.
|
|
41
|
+
Additional tests cover file growth and SDK retry configuration. Live sandbox tests
|
|
42
|
+
remain pending an E2B account and disposable sandbox resources.
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
pip install render-lab-tasks-e2b==0.1.0
|
|
48
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# render-lab-tasks-e2b
|
|
2
|
+
|
|
3
|
+
Twelve E2B sandbox lifecycle, execution, filesystem, logs, and metrics tasks.
|
|
4
|
+
Wrapped tasks and raw injectable implementations live in `render_lab_tasks_e2b.tasks`.
|
|
5
|
+
The root does not register tasks or read credentials.
|
|
6
|
+
|
|
7
|
+
## Environment
|
|
8
|
+
|
|
9
|
+
`E2B_API_KEY` is required lazily. `E2B_API_URL` optionally overrides the control-plane
|
|
10
|
+
API and logs endpoint. The adapter defaults `E2B_CONNECTION_RETRIES` to `0` before
|
|
11
|
+
loading the SDK. If your application imports E2B independently, set that variable
|
|
12
|
+
to `0` before starting the process; the adapter rejects an SDK already initialized
|
|
13
|
+
with retries. The SDK versions are pinned because this setting is captured at import.
|
|
14
|
+
|
|
15
|
+
## Behavior and verification
|
|
16
|
+
|
|
17
|
+
Create finds running or paused sandboxes by caller idempotency key. Pause, resume,
|
|
18
|
+
and kill use the official async SDK. Task timeout fields stay in milliseconds and
|
|
19
|
+
are converted to SDK seconds. Nonzero command exits return their exit code/output.
|
|
20
|
+
Code, text, binary, and collection results use explicit limits. File metadata is
|
|
21
|
+
checked before reading, then the stream is checked again and closed on overflow.
|
|
22
|
+
No file is written onto the workflow host. Execution result text shares one budget,
|
|
23
|
+
and the complete code result is capped at 4 MB. See ADR-0017 for stricter bounds.
|
|
24
|
+
|
|
25
|
+
Source fixtures compare all twelve tasks and SDK arguments independently with TS.
|
|
26
|
+
Additional tests cover file growth and SDK retry configuration. Live sandbox tests
|
|
27
|
+
remain pending an E2B account and disposable sandbox resources.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
pip install render-lab-tasks-e2b==0.1.0
|
|
33
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27,<2"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "render-lab-tasks-e2b"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "e2b tasks for Render Workflows"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.12"
|
|
13
|
+
dependencies = ["e2b==2.46.4","e2b-code-interpreter==2.9.2","render==1.0.1", "httpx>=0.28,<0.29", "render-lab-tasks-core>=0.1.1,<0.2"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/render-lab/render-tasks-python"
|
|
17
|
+
|
|
18
|
+
[tool.uv.sources]
|
|
19
|
+
render-lab-tasks-core = { workspace = true }
|
|
20
|
+
|
|
21
|
+
[tool.hatch.build.targets.wheel]
|
|
22
|
+
packages = ["src/render_lab_tasks_e2b"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Import .tasks explicitly to register durable tasks."""
|
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Injected vendor interface and one-attempt async HTTP adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import binascii
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from collections.abc import AsyncIterator, Mapping
|
|
10
|
+
from contextlib import asynccontextmanager
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from importlib import import_module
|
|
14
|
+
from typing import Any, Protocol, cast
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
from render_lab_tasks_core.bounded import (
|
|
18
|
+
MAX_BINARY_BYTES,
|
|
19
|
+
MAX_TEXT_BYTES,
|
|
20
|
+
BoundedText,
|
|
21
|
+
assert_json_limit,
|
|
22
|
+
bounded_binary,
|
|
23
|
+
bounded_text,
|
|
24
|
+
validate_byte_limit,
|
|
25
|
+
)
|
|
26
|
+
from render_lab_tasks_core.http import (
|
|
27
|
+
ApiError,
|
|
28
|
+
HttpClient,
|
|
29
|
+
enc,
|
|
30
|
+
js_string,
|
|
31
|
+
nullish,
|
|
32
|
+
pick,
|
|
33
|
+
query,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
from . import types as t
|
|
37
|
+
|
|
38
|
+
IDEMPOTENCY_METADATA_KEY = "_render_tasks_idempotency_key"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def iso(value: Any) -> str:
|
|
42
|
+
if isinstance(value, str):
|
|
43
|
+
return value
|
|
44
|
+
if not isinstance(value, datetime):
|
|
45
|
+
value = datetime.fromtimestamp(value / 1000, UTC)
|
|
46
|
+
return str(value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z"))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def sandbox(raw: Any) -> t.SandboxDTO:
|
|
50
|
+
return {
|
|
51
|
+
"sandboxId": raw.sandbox_id,
|
|
52
|
+
"templateId": raw.template_id,
|
|
53
|
+
"status": raw.state,
|
|
54
|
+
"startedAt": iso(raw.started_at),
|
|
55
|
+
"endAt": iso(raw.end_at),
|
|
56
|
+
"metadata": raw.metadata or {},
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def clamp(value: float) -> int:
|
|
61
|
+
if not math.isfinite(value):
|
|
62
|
+
raise ValueError("Collection limits must be finite numbers.")
|
|
63
|
+
return int(min(max(value, 1), 1000))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def page(returned: int, available: int, limit: int) -> t.BoundedCollection:
|
|
67
|
+
return {
|
|
68
|
+
"returned": returned,
|
|
69
|
+
"available": available,
|
|
70
|
+
"limit": limit,
|
|
71
|
+
"truncated": returned < available,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def empty_text(value: str) -> BoundedText:
|
|
76
|
+
return {
|
|
77
|
+
"text": "",
|
|
78
|
+
"byteCount": len(value.encode()),
|
|
79
|
+
"returnedBytes": 0,
|
|
80
|
+
"maxBytes": 0,
|
|
81
|
+
"truncated": bool(value),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Port(Protocol):
|
|
86
|
+
async def create_sandbox(self, input: t.CreateSandboxInput) -> t.CreateSandboxResult: ...
|
|
87
|
+
async def get_sandbox(self, input: t.SandboxIdInput) -> t.SandboxDTO: ...
|
|
88
|
+
async def get_sandbox_logs(self, input: t.GetSandboxLogsInput) -> t.GetSandboxLogsResult: ...
|
|
89
|
+
async def get_sandbox_metrics(
|
|
90
|
+
self, input: t.GetSandboxMetricsInput
|
|
91
|
+
) -> t.GetSandboxMetricsResult: ...
|
|
92
|
+
async def kill_sandbox(self, input: t.SandboxIdInput) -> t.SandboxLifecycleResult: ...
|
|
93
|
+
async def list_files(self, input: t.ListFilesInput) -> t.ListFilesResult: ...
|
|
94
|
+
async def pause_sandbox(self, input: t.PauseSandboxInput) -> t.SandboxLifecycleResult: ...
|
|
95
|
+
async def read_file(self, input: t.ReadFileInput) -> t.ReadFileResult: ...
|
|
96
|
+
async def resume_sandbox(self, input: t.SandboxIdInput) -> t.SandboxLifecycleResult: ...
|
|
97
|
+
async def run_code(self, input: t.RunCodeInput) -> t.RunCodeResult: ...
|
|
98
|
+
async def run_command(self, input: t.RunCommandInput) -> t.RunCommandResult: ...
|
|
99
|
+
async def write_files(self, input: t.WriteFilesInput) -> t.WriteFilesResult: ...
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class Deps:
|
|
104
|
+
e2b: Port
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Client:
|
|
108
|
+
def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
|
|
109
|
+
self.env = os.environ if env is None else env
|
|
110
|
+
self.http = http
|
|
111
|
+
self.sdk: Any = None
|
|
112
|
+
|
|
113
|
+
def _sdk(self) -> Any:
|
|
114
|
+
if self.sdk is not None:
|
|
115
|
+
return self.sdk
|
|
116
|
+
# The SDK captures this at import, so verify existing imports too.
|
|
117
|
+
os.environ.setdefault("E2B_CONNECTION_RETRIES", "0")
|
|
118
|
+
connection_retries = import_module("e2b.api").connection_retries
|
|
119
|
+
async_retries = import_module("e2b.api.client_async").connection_retries
|
|
120
|
+
AsyncSandbox = import_module("e2b_code_interpreter").AsyncSandbox
|
|
121
|
+
|
|
122
|
+
if connection_retries != 0 or async_retries != 0:
|
|
123
|
+
raise ValueError(
|
|
124
|
+
"Set E2B_CONNECTION_RETRIES=0 before importing the E2B SDK; durable "
|
|
125
|
+
"tasks own retries."
|
|
126
|
+
)
|
|
127
|
+
self.sdk = AsyncSandbox
|
|
128
|
+
return self.sdk
|
|
129
|
+
|
|
130
|
+
def _options(self) -> dict[str, Any]:
|
|
131
|
+
key = self.env.get("E2B_API_KEY")
|
|
132
|
+
if not key:
|
|
133
|
+
raise ValueError("E2B_API_KEY is required for the e2b.* tasks.")
|
|
134
|
+
options: dict[str, Any] = {"api_key": key}
|
|
135
|
+
if self.env.get("E2B_API_URL"):
|
|
136
|
+
options["api_url"] = self.env["E2B_API_URL"]
|
|
137
|
+
return options
|
|
138
|
+
|
|
139
|
+
async def _connect(self, identifier: str) -> Any:
|
|
140
|
+
options = self._options()
|
|
141
|
+
return await self._sdk().connect(identifier, **options)
|
|
142
|
+
|
|
143
|
+
async def create_sandbox(self, input: t.CreateSandboxInput) -> t.CreateSandboxResult:
|
|
144
|
+
key = input.get("idempotencyKey", "")
|
|
145
|
+
if not key.strip():
|
|
146
|
+
raise ValueError(
|
|
147
|
+
"e2b.createSandbox requires a non-empty idempotencyKey so a retried "
|
|
148
|
+
"create can re-find its sandbox."
|
|
149
|
+
)
|
|
150
|
+
options = self._options()
|
|
151
|
+
sdk = self._sdk()
|
|
152
|
+
from e2b import SandboxQuery, SandboxState
|
|
153
|
+
|
|
154
|
+
pager = sdk.list(
|
|
155
|
+
query=SandboxQuery(
|
|
156
|
+
metadata={IDEMPOTENCY_METADATA_KEY: key},
|
|
157
|
+
state=[SandboxState.RUNNING, SandboxState.PAUSED],
|
|
158
|
+
),
|
|
159
|
+
limit=2,
|
|
160
|
+
**options,
|
|
161
|
+
)
|
|
162
|
+
existing = await pager.next_items()
|
|
163
|
+
if existing:
|
|
164
|
+
return {**sandbox(existing[0]), "created": False}
|
|
165
|
+
kwargs = {
|
|
166
|
+
**options,
|
|
167
|
+
**pick(input, "template", "envs"),
|
|
168
|
+
"metadata": {**input.get("metadata", {}), IDEMPOTENCY_METADATA_KEY: key},
|
|
169
|
+
}
|
|
170
|
+
if "timeoutMs" in input:
|
|
171
|
+
kwargs["timeout"] = input["timeoutMs"] / 1000
|
|
172
|
+
if "allowInternetAccess" in input:
|
|
173
|
+
kwargs["allow_internet_access"] = input["allowInternetAccess"]
|
|
174
|
+
created = await sdk.create(**kwargs)
|
|
175
|
+
return {**sandbox(await sdk.get_info(created.sandbox_id, **options)), "created": True}
|
|
176
|
+
|
|
177
|
+
async def get_sandbox(self, input: t.SandboxIdInput) -> t.SandboxDTO:
|
|
178
|
+
options = self._options()
|
|
179
|
+
return sandbox(await self._sdk().get_info(input["sandboxId"], **options))
|
|
180
|
+
|
|
181
|
+
async def pause_sandbox(self, input: t.PauseSandboxInput) -> t.SandboxLifecycleResult:
|
|
182
|
+
options = self._options()
|
|
183
|
+
changed = await self._sdk().pause(
|
|
184
|
+
input["sandboxId"], keep_memory=input.get("keepMemory", True), **options
|
|
185
|
+
)
|
|
186
|
+
return {"sandboxId": input["sandboxId"], "status": "paused", "changed": changed}
|
|
187
|
+
|
|
188
|
+
async def resume_sandbox(self, input: t.SandboxIdInput) -> t.SandboxLifecycleResult:
|
|
189
|
+
await self._connect(input["sandboxId"])
|
|
190
|
+
return {"sandboxId": input["sandboxId"], "status": "running", "changed": True}
|
|
191
|
+
|
|
192
|
+
async def kill_sandbox(self, input: t.SandboxIdInput) -> t.SandboxLifecycleResult:
|
|
193
|
+
options = self._options()
|
|
194
|
+
changed = await self._sdk().kill(input["sandboxId"], **options)
|
|
195
|
+
return {"sandboxId": input["sandboxId"], "status": "killed", "changed": changed}
|
|
196
|
+
|
|
197
|
+
async def run_command(self, input: t.RunCommandInput) -> t.RunCommandResult:
|
|
198
|
+
maximum = validate_byte_limit(input.get("maxOutputBytes", 65536), MAX_TEXT_BYTES)
|
|
199
|
+
handle = await self._connect(input["sandboxId"])
|
|
200
|
+
try:
|
|
201
|
+
result = await handle.commands.run(
|
|
202
|
+
input["command"],
|
|
203
|
+
**pick(input, "cwd", "envs"),
|
|
204
|
+
timeout=input.get("timeoutMs", 60000) / 1000,
|
|
205
|
+
)
|
|
206
|
+
except Exception as error:
|
|
207
|
+
if not isinstance(getattr(error, "exit_code", None), (int, float)) or not all(
|
|
208
|
+
isinstance(getattr(error, key, None), str) for key in ("stdout", "stderr")
|
|
209
|
+
):
|
|
210
|
+
raise
|
|
211
|
+
result = error
|
|
212
|
+
return {
|
|
213
|
+
"sandboxId": input["sandboxId"],
|
|
214
|
+
"exitCode": result.exit_code,
|
|
215
|
+
"stdout": bounded_text(result.stdout, maximum),
|
|
216
|
+
"stderr": bounded_text(result.stderr, maximum),
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async def run_code(self, input: t.RunCodeInput) -> t.RunCodeResult:
|
|
220
|
+
maximum = validate_byte_limit(input.get("maxOutputBytes", 65536), MAX_TEXT_BYTES)
|
|
221
|
+
result_cap = validate_byte_limit(input.get("maxResultBytes", 262144), MAX_TEXT_BYTES)
|
|
222
|
+
artifact_cap = validate_byte_limit(input.get("maxArtifactBytes", 524288), MAX_BINARY_BYTES)
|
|
223
|
+
handle = await self._connect(input["sandboxId"])
|
|
224
|
+
raw = await handle.run_code(
|
|
225
|
+
input["code"],
|
|
226
|
+
**pick(input, "language", "envs"),
|
|
227
|
+
timeout=input.get("timeoutMs", 60000) / 1000,
|
|
228
|
+
)
|
|
229
|
+
texts = [r.text for r in raw.results if isinstance(r.text, str)]
|
|
230
|
+
per_result = max(1, result_cap // len(texts)) if texts else result_cap
|
|
231
|
+
results: list[BoundedText] = []
|
|
232
|
+
used = 0
|
|
233
|
+
for text in texts:
|
|
234
|
+
remaining = min(per_result, result_cap - used)
|
|
235
|
+
item = bounded_text(text, remaining) if remaining else empty_text(text)
|
|
236
|
+
used += item["returnedBytes"]
|
|
237
|
+
results.append(item)
|
|
238
|
+
artifacts: list[t.CodeArtifactDTO] = []
|
|
239
|
+
for cell in raw.results:
|
|
240
|
+
encoded = getattr(cell, "png", None) or getattr(cell, "jpeg", None)
|
|
241
|
+
if not isinstance(encoded, str):
|
|
242
|
+
continue
|
|
243
|
+
data = base64.b64decode(encoded, validate=True)
|
|
244
|
+
index = len(artifacts)
|
|
245
|
+
if len(data) > artifact_cap:
|
|
246
|
+
raise ValueError(
|
|
247
|
+
f"Code artifact {index} is {len(data)} bytes, above the "
|
|
248
|
+
f"maxArtifactBytes limit of {artifact_cap}. Write it to a "
|
|
249
|
+
"sandbox file and read it back with e2b.readFile, or use an "
|
|
250
|
+
"external signed destination."
|
|
251
|
+
)
|
|
252
|
+
artifacts.append(
|
|
253
|
+
{
|
|
254
|
+
"index": index,
|
|
255
|
+
"content": bounded_binary(
|
|
256
|
+
data,
|
|
257
|
+
"image/png" if getattr(cell, "png", None) is not None else "image/jpeg",
|
|
258
|
+
artifact_cap,
|
|
259
|
+
),
|
|
260
|
+
}
|
|
261
|
+
)
|
|
262
|
+
result: t.RunCodeResult = {
|
|
263
|
+
"sandboxId": input["sandboxId"],
|
|
264
|
+
"executionCount": raw.execution_count,
|
|
265
|
+
"textResults": results,
|
|
266
|
+
"artifacts": artifacts,
|
|
267
|
+
"stdout": bounded_text("".join(raw.logs.stdout), maximum),
|
|
268
|
+
"stderr": bounded_text("".join(raw.logs.stderr), maximum),
|
|
269
|
+
"error": {
|
|
270
|
+
"name": raw.error.name,
|
|
271
|
+
"value": raw.error.value,
|
|
272
|
+
"traceback": bounded_text(raw.error.traceback, maximum),
|
|
273
|
+
}
|
|
274
|
+
if raw.error
|
|
275
|
+
else None,
|
|
276
|
+
}
|
|
277
|
+
assert_json_limit("Code execution", result, 4_000_000)
|
|
278
|
+
return result
|
|
279
|
+
|
|
280
|
+
async def write_files(self, input: t.WriteFilesInput) -> t.WriteFilesResult:
|
|
281
|
+
files = input["files"]
|
|
282
|
+
if not 1 <= len(files) <= 100:
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"e2b.writeFiles accepts between 1 and 100 files, received {len(files)}."
|
|
285
|
+
)
|
|
286
|
+
if len({file["path"] for file in files}) != len(files):
|
|
287
|
+
raise ValueError("e2b.writeFiles rejects duplicate file paths in one call.")
|
|
288
|
+
maximum = validate_byte_limit(input.get("maxTotalBytes", 1048576), MAX_BINARY_BYTES)
|
|
289
|
+
decoded = []
|
|
290
|
+
total = 0
|
|
291
|
+
for file in files:
|
|
292
|
+
if file["encoding"] == "base64":
|
|
293
|
+
try:
|
|
294
|
+
data = base64.b64decode(file["content"], validate=True)
|
|
295
|
+
if base64.b64encode(data).decode() != file["content"]:
|
|
296
|
+
raise ValueError("noncanonical")
|
|
297
|
+
except (ValueError, binascii.Error):
|
|
298
|
+
raise ValueError(f"File {file['path']} is not canonical base64.") from None
|
|
299
|
+
else:
|
|
300
|
+
data = file["content"].encode()
|
|
301
|
+
total += len(data)
|
|
302
|
+
decoded.append(data)
|
|
303
|
+
if total > maximum:
|
|
304
|
+
raise ValueError(
|
|
305
|
+
f"e2b.writeFiles payload is {total} bytes, above the maxTotalBytes "
|
|
306
|
+
f"limit of {maximum}. Split the write or stage large files individually."
|
|
307
|
+
)
|
|
308
|
+
handle = await self._connect(input["sandboxId"])
|
|
309
|
+
await handle.files.write_files(
|
|
310
|
+
[
|
|
311
|
+
{"path": file["path"], "data": data}
|
|
312
|
+
for file, data in zip(files, decoded, strict=True)
|
|
313
|
+
]
|
|
314
|
+
)
|
|
315
|
+
return {
|
|
316
|
+
"sandboxId": input["sandboxId"],
|
|
317
|
+
"files": [
|
|
318
|
+
{"path": file["path"], "byteCount": len(data)}
|
|
319
|
+
for file, data in zip(files, decoded, strict=True)
|
|
320
|
+
],
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async def read_file(self, input: t.ReadFileInput) -> t.ReadFileResult:
|
|
324
|
+
encoding = input.get("encoding", "utf8")
|
|
325
|
+
maximum = validate_byte_limit(
|
|
326
|
+
input.get("maxBytes", 262144),
|
|
327
|
+
MAX_BINARY_BYTES if encoding == "base64" else MAX_TEXT_BYTES,
|
|
328
|
+
)
|
|
329
|
+
handle = await self._connect(input["sandboxId"])
|
|
330
|
+
info = await handle.files.get_info(input["path"])
|
|
331
|
+
if info.size > maximum:
|
|
332
|
+
raise ValueError(
|
|
333
|
+
f"File {input['path']} is {info.size} bytes, above the maxBytes "
|
|
334
|
+
f"limit of {maximum}. Narrow the read, or copy it to an external "
|
|
335
|
+
f"destination and return a reference."
|
|
336
|
+
)
|
|
337
|
+
data = bytearray()
|
|
338
|
+
async with await handle.files.read(input["path"], format="stream") as stream:
|
|
339
|
+
async for chunk in stream:
|
|
340
|
+
if len(data) + len(chunk) > maximum:
|
|
341
|
+
raise ValueError(
|
|
342
|
+
f"File {input['path']} grew beyond its {maximum}-byte limit "
|
|
343
|
+
f"during the read."
|
|
344
|
+
)
|
|
345
|
+
data.extend(chunk)
|
|
346
|
+
return {
|
|
347
|
+
"sandboxId": input["sandboxId"],
|
|
348
|
+
"path": input["path"],
|
|
349
|
+
"encoding": encoding,
|
|
350
|
+
"content": base64.b64encode(data).decode()
|
|
351
|
+
if encoding == "base64"
|
|
352
|
+
else data.decode("utf-8", errors="replace"),
|
|
353
|
+
"byteCount": len(data),
|
|
354
|
+
"returnedBytes": len(data),
|
|
355
|
+
"maxBytes": maximum,
|
|
356
|
+
"truncated": False,
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async def list_files(self, input: t.ListFilesInput) -> t.ListFilesResult:
|
|
360
|
+
limit = clamp(input.get("limit", 100))
|
|
361
|
+
handle = await self._connect(input["sandboxId"])
|
|
362
|
+
raw = await handle.files.list(input["path"])
|
|
363
|
+
entries: list[t.FileEntryDTO] = []
|
|
364
|
+
for row in raw[:limit]:
|
|
365
|
+
kind = (
|
|
366
|
+
"symlink"
|
|
367
|
+
if getattr(row, "symlink_target", None)
|
|
368
|
+
else {"file": "file", "dir": "directory"}.get(
|
|
369
|
+
getattr(getattr(row, "type", ""), "value", getattr(row, "type", "")), "other"
|
|
370
|
+
)
|
|
371
|
+
)
|
|
372
|
+
entries.append(
|
|
373
|
+
{
|
|
374
|
+
"name": row.name,
|
|
375
|
+
"path": row.path,
|
|
376
|
+
"type": cast(Any, kind),
|
|
377
|
+
"size": getattr(row, "size", 0) or 0,
|
|
378
|
+
}
|
|
379
|
+
)
|
|
380
|
+
return {
|
|
381
|
+
"sandboxId": input["sandboxId"],
|
|
382
|
+
"entries": entries,
|
|
383
|
+
"page": page(len(entries), len(raw), limit),
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async def get_sandbox_logs(self, input: t.GetSandboxLogsInput) -> t.GetSandboxLogsResult:
|
|
387
|
+
limit = clamp(input.get("limit", 100))
|
|
388
|
+
maximum = validate_byte_limit(input.get("maxBytes", 262144), MAX_TEXT_BYTES)
|
|
389
|
+
options = self._options()
|
|
390
|
+
api = HttpClient(
|
|
391
|
+
self.http,
|
|
392
|
+
options.get("api_url", "https://api.e2b.app"),
|
|
393
|
+
auth=lambda: {"X-API-Key": options["api_key"]},
|
|
394
|
+
label="E2B logs",
|
|
395
|
+
)
|
|
396
|
+
try:
|
|
397
|
+
raw = await api.call(
|
|
398
|
+
"/v2/sandboxes/"
|
|
399
|
+
+ enc(input["sandboxId"])
|
|
400
|
+
+ "/logs?"
|
|
401
|
+
+ query({**pick(input, "cursor", "direction", "level", "search"), "limit": limit})
|
|
402
|
+
)
|
|
403
|
+
except ApiError as error:
|
|
404
|
+
raise ValueError(f"E2B logs request failed ({error.status})") from None
|
|
405
|
+
per_message = max(1, maximum // limit)
|
|
406
|
+
logs: list[t.SandboxLogDTO] = []
|
|
407
|
+
used = 0
|
|
408
|
+
all_logs = raw.get("logs", [])
|
|
409
|
+
for row in all_logs:
|
|
410
|
+
if used >= maximum:
|
|
411
|
+
break
|
|
412
|
+
message = bounded_text(
|
|
413
|
+
js_string(nullish(row.get("message"), "")), min(per_message, maximum - used)
|
|
414
|
+
)
|
|
415
|
+
used += message["returnedBytes"]
|
|
416
|
+
level = {
|
|
417
|
+
"debug": "debug",
|
|
418
|
+
"warn": "warn",
|
|
419
|
+
"warning": "warn",
|
|
420
|
+
"error": "error",
|
|
421
|
+
"fatal": "error",
|
|
422
|
+
}.get(str(row.get("level", "")).lower(), "info")
|
|
423
|
+
logs.append(
|
|
424
|
+
{
|
|
425
|
+
"timestamp": iso(row.get("timestamp", 0)),
|
|
426
|
+
"level": cast(t.LogLevel, level),
|
|
427
|
+
"message": message,
|
|
428
|
+
"logger": row.get("logger") if isinstance(row.get("logger"), str) else None,
|
|
429
|
+
}
|
|
430
|
+
)
|
|
431
|
+
return {
|
|
432
|
+
"sandboxId": input["sandboxId"],
|
|
433
|
+
"logs": logs,
|
|
434
|
+
"cursor": raw.get("nextCursor"),
|
|
435
|
+
"page": page(len(logs), len(all_logs), limit),
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async def get_sandbox_metrics(
|
|
439
|
+
self, input: t.GetSandboxMetricsInput
|
|
440
|
+
) -> t.GetSandboxMetricsResult:
|
|
441
|
+
limit = clamp(input.get("limit", 100))
|
|
442
|
+
options = self._options()
|
|
443
|
+
kwargs = {
|
|
444
|
+
k: datetime.fromisoformat(input[k].replace("Z", "+00:00"))
|
|
445
|
+
for k in ("start", "end")
|
|
446
|
+
if k in input
|
|
447
|
+
}
|
|
448
|
+
raw = await self._sdk().get_metrics(input["sandboxId"], **kwargs, **options)
|
|
449
|
+
metrics: list[t.SandboxMetricDTO] = [
|
|
450
|
+
{
|
|
451
|
+
"timestamp": iso(row.timestamp),
|
|
452
|
+
"cpuUsedPct": row.cpu_used_pct,
|
|
453
|
+
"cpuCount": row.cpu_count,
|
|
454
|
+
"memoryUsedBytes": row.mem_used,
|
|
455
|
+
"memoryTotalBytes": row.mem_total,
|
|
456
|
+
"diskUsedBytes": row.disk_used,
|
|
457
|
+
"diskTotalBytes": row.disk_total,
|
|
458
|
+
}
|
|
459
|
+
for row in raw
|
|
460
|
+
]
|
|
461
|
+
metrics.sort(key=lambda row: row["timestamp"])
|
|
462
|
+
return {
|
|
463
|
+
"sandboxId": input["sandboxId"],
|
|
464
|
+
"metrics": metrics[:limit],
|
|
465
|
+
"page": page(min(limit, len(metrics)), len(metrics), limit),
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
@asynccontextmanager
|
|
470
|
+
async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
|
|
471
|
+
if deps is not None:
|
|
472
|
+
yield deps
|
|
473
|
+
else:
|
|
474
|
+
async with httpx.AsyncClient(
|
|
475
|
+
timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
|
|
476
|
+
) as http:
|
|
477
|
+
yield Deps(e2b=Client(http))
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
E2BPort = Port
|
|
481
|
+
E2BClient = Client
|
|
482
|
+
E2BDeps = Deps
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import CreateSandboxInput, CreateSandboxResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def create_sandbox_impl(
|
|
10
|
+
ctx: TaskContext, input: CreateSandboxInput, *, deps: Deps | None = None
|
|
11
|
+
) -> CreateSandboxResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.create_sandbox(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.createSandbox", retry=NO_RETRY)
|
|
17
|
+
async def create_sandbox(ctx: TaskContext, input: CreateSandboxInput) -> CreateSandboxResult:
|
|
18
|
+
return await create_sandbox_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import SandboxDTO, SandboxIdInput
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def get_sandbox_impl(
|
|
10
|
+
ctx: TaskContext, input: SandboxIdInput, *, deps: Deps | None = None
|
|
11
|
+
) -> SandboxDTO:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.get_sandbox(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.getSandbox", retry=NO_RETRY)
|
|
17
|
+
async def get_sandbox(ctx: TaskContext, input: SandboxIdInput) -> SandboxDTO:
|
|
18
|
+
return await get_sandbox_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import GetSandboxLogsInput, GetSandboxLogsResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def get_sandbox_logs_impl(
|
|
10
|
+
ctx: TaskContext, input: GetSandboxLogsInput, *, deps: Deps | None = None
|
|
11
|
+
) -> GetSandboxLogsResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.get_sandbox_logs(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.getSandboxLogs", retry=NO_RETRY)
|
|
17
|
+
async def get_sandbox_logs(ctx: TaskContext, input: GetSandboxLogsInput) -> GetSandboxLogsResult:
|
|
18
|
+
return await get_sandbox_logs_impl(ctx, input)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import GetSandboxMetricsInput, GetSandboxMetricsResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def get_sandbox_metrics_impl(
|
|
10
|
+
ctx: TaskContext, input: GetSandboxMetricsInput, *, deps: Deps | None = None
|
|
11
|
+
) -> GetSandboxMetricsResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.get_sandbox_metrics(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.getSandboxMetrics", retry=NO_RETRY)
|
|
17
|
+
async def get_sandbox_metrics(
|
|
18
|
+
ctx: TaskContext, input: GetSandboxMetricsInput
|
|
19
|
+
) -> GetSandboxMetricsResult:
|
|
20
|
+
return await get_sandbox_metrics_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import SandboxIdInput, SandboxLifecycleResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def kill_sandbox_impl(
|
|
10
|
+
ctx: TaskContext, input: SandboxIdInput, *, deps: Deps | None = None
|
|
11
|
+
) -> SandboxLifecycleResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.kill_sandbox(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.killSandbox", retry=NO_RETRY)
|
|
17
|
+
async def kill_sandbox(ctx: TaskContext, input: SandboxIdInput) -> SandboxLifecycleResult:
|
|
18
|
+
return await kill_sandbox_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import ListFilesInput, ListFilesResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def list_files_impl(
|
|
10
|
+
ctx: TaskContext, input: ListFilesInput, *, deps: Deps | None = None
|
|
11
|
+
) -> ListFilesResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.list_files(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.listFiles", retry=NO_RETRY)
|
|
17
|
+
async def list_files(ctx: TaskContext, input: ListFilesInput) -> ListFilesResult:
|
|
18
|
+
return await list_files_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import PauseSandboxInput, SandboxLifecycleResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def pause_sandbox_impl(
|
|
10
|
+
ctx: TaskContext, input: PauseSandboxInput, *, deps: Deps | None = None
|
|
11
|
+
) -> SandboxLifecycleResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.pause_sandbox(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.pauseSandbox", retry=NO_RETRY)
|
|
17
|
+
async def pause_sandbox(ctx: TaskContext, input: PauseSandboxInput) -> SandboxLifecycleResult:
|
|
18
|
+
return await pause_sandbox_impl(ctx, input)
|
|
File without changes
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import ReadFileInput, ReadFileResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def read_file_impl(
|
|
10
|
+
ctx: TaskContext, input: ReadFileInput, *, deps: Deps | None = None
|
|
11
|
+
) -> ReadFileResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.read_file(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.readFile", retry=NO_RETRY)
|
|
17
|
+
async def read_file(ctx: TaskContext, input: ReadFileInput) -> ReadFileResult:
|
|
18
|
+
return await read_file_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import SandboxIdInput, SandboxLifecycleResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def resume_sandbox_impl(
|
|
10
|
+
ctx: TaskContext, input: SandboxIdInput, *, deps: Deps | None = None
|
|
11
|
+
) -> SandboxLifecycleResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.resume_sandbox(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.resumeSandbox", retry=NO_RETRY)
|
|
17
|
+
async def resume_sandbox(ctx: TaskContext, input: SandboxIdInput) -> SandboxLifecycleResult:
|
|
18
|
+
return await resume_sandbox_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import RunCodeInput, RunCodeResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def run_code_impl(
|
|
10
|
+
ctx: TaskContext, input: RunCodeInput, *, deps: Deps | None = None
|
|
11
|
+
) -> RunCodeResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.run_code(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.runCode", retry=NO_RETRY)
|
|
17
|
+
async def run_code(ctx: TaskContext, input: RunCodeInput) -> RunCodeResult:
|
|
18
|
+
return await run_code_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import RunCommandInput, RunCommandResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def run_command_impl(
|
|
10
|
+
ctx: TaskContext, input: RunCommandInput, *, deps: Deps | None = None
|
|
11
|
+
) -> RunCommandResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.run_command(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.runCommand", retry=NO_RETRY)
|
|
17
|
+
async def run_command(ctx: TaskContext, input: RunCommandInput) -> RunCommandResult:
|
|
18
|
+
return await run_command_impl(ctx, input)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from ._app import app
|
|
2
|
+
from .create_sandbox import create_sandbox, create_sandbox_impl
|
|
3
|
+
from .get_sandbox import get_sandbox, get_sandbox_impl
|
|
4
|
+
from .get_sandbox_logs import get_sandbox_logs, get_sandbox_logs_impl
|
|
5
|
+
from .get_sandbox_metrics import get_sandbox_metrics, get_sandbox_metrics_impl
|
|
6
|
+
from .kill_sandbox import kill_sandbox, kill_sandbox_impl
|
|
7
|
+
from .list_files import list_files, list_files_impl
|
|
8
|
+
from .pause_sandbox import pause_sandbox, pause_sandbox_impl
|
|
9
|
+
from .read_file import read_file, read_file_impl
|
|
10
|
+
from .resume_sandbox import resume_sandbox, resume_sandbox_impl
|
|
11
|
+
from .run_code import run_code, run_code_impl
|
|
12
|
+
from .run_command import run_command, run_command_impl
|
|
13
|
+
from .write_files import write_files, write_files_impl
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"app",
|
|
17
|
+
"create_sandbox",
|
|
18
|
+
"create_sandbox_impl",
|
|
19
|
+
"get_sandbox",
|
|
20
|
+
"get_sandbox_impl",
|
|
21
|
+
"get_sandbox_logs",
|
|
22
|
+
"get_sandbox_logs_impl",
|
|
23
|
+
"get_sandbox_metrics",
|
|
24
|
+
"get_sandbox_metrics_impl",
|
|
25
|
+
"kill_sandbox",
|
|
26
|
+
"kill_sandbox_impl",
|
|
27
|
+
"list_files",
|
|
28
|
+
"list_files_impl",
|
|
29
|
+
"pause_sandbox",
|
|
30
|
+
"pause_sandbox_impl",
|
|
31
|
+
"read_file",
|
|
32
|
+
"read_file_impl",
|
|
33
|
+
"resume_sandbox",
|
|
34
|
+
"resume_sandbox_impl",
|
|
35
|
+
"run_code",
|
|
36
|
+
"run_code_impl",
|
|
37
|
+
"run_command",
|
|
38
|
+
"run_command_impl",
|
|
39
|
+
"write_files",
|
|
40
|
+
"write_files_impl",
|
|
41
|
+
]
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""JSON contracts ported from the pinned TypeScript pack."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal, NotRequired, TypedDict
|
|
6
|
+
|
|
7
|
+
from render_lab_tasks_core.bounded import BoundedBinary, BoundedText
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RawCodeExecutionErrorVariant1(TypedDict):
|
|
11
|
+
name: str
|
|
12
|
+
value: str
|
|
13
|
+
traceback: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RawCodeExecutionArtifactsItem(TypedDict):
|
|
17
|
+
contentType: Literal["image/png"] | Literal["image/jpeg"]
|
|
18
|
+
bytes: bytes
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class WriteFilesResultFilesItem(TypedDict):
|
|
22
|
+
path: str
|
|
23
|
+
byteCount: float
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
type SandboxStatus = Literal["running"] | Literal["paused"]
|
|
27
|
+
|
|
28
|
+
type CodeLanguage = (
|
|
29
|
+
Literal["python"]
|
|
30
|
+
| Literal["javascript"]
|
|
31
|
+
| Literal["typescript"]
|
|
32
|
+
| Literal["r"]
|
|
33
|
+
| Literal["java"]
|
|
34
|
+
| Literal["bash"]
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
type LogLevel = Literal["debug"] | Literal["info"] | Literal["warn"] | Literal["error"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SandboxDTO(TypedDict):
|
|
41
|
+
sandboxId: str
|
|
42
|
+
templateId: str
|
|
43
|
+
status: SandboxStatus
|
|
44
|
+
startedAt: str
|
|
45
|
+
endAt: str
|
|
46
|
+
metadata: dict[str, str]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CreateSandboxInput(TypedDict):
|
|
50
|
+
idempotencyKey: str
|
|
51
|
+
template: NotRequired[str]
|
|
52
|
+
timeoutMs: NotRequired[float]
|
|
53
|
+
metadata: NotRequired[dict[str, str]]
|
|
54
|
+
envs: NotRequired[dict[str, str]]
|
|
55
|
+
allowInternetAccess: NotRequired[bool]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class CreateSandboxResult(SandboxDTO):
|
|
59
|
+
created: bool
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SandboxIdInput(TypedDict):
|
|
63
|
+
sandboxId: str
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class PauseSandboxInput(SandboxIdInput):
|
|
67
|
+
keepMemory: NotRequired[bool]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class SandboxLifecycleResult(TypedDict):
|
|
71
|
+
sandboxId: str
|
|
72
|
+
status: SandboxStatus | Literal["killed"]
|
|
73
|
+
changed: bool
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class RunCommandInput(SandboxIdInput):
|
|
77
|
+
command: str
|
|
78
|
+
cwd: NotRequired[str]
|
|
79
|
+
envs: NotRequired[dict[str, str]]
|
|
80
|
+
timeoutMs: NotRequired[float]
|
|
81
|
+
maxOutputBytes: NotRequired[float]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class RunCommandResult(TypedDict):
|
|
85
|
+
sandboxId: str
|
|
86
|
+
exitCode: float
|
|
87
|
+
stdout: BoundedText
|
|
88
|
+
stderr: BoundedText
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class RunCodeInput(SandboxIdInput):
|
|
92
|
+
code: str
|
|
93
|
+
language: NotRequired[CodeLanguage]
|
|
94
|
+
envs: NotRequired[dict[str, str]]
|
|
95
|
+
timeoutMs: NotRequired[float]
|
|
96
|
+
maxOutputBytes: NotRequired[float]
|
|
97
|
+
maxResultBytes: NotRequired[float]
|
|
98
|
+
maxArtifactBytes: NotRequired[float]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class CodeErrorDTO(TypedDict):
|
|
102
|
+
name: str
|
|
103
|
+
value: str
|
|
104
|
+
traceback: BoundedText
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class CodeArtifactDTO(TypedDict):
|
|
108
|
+
index: float
|
|
109
|
+
content: BoundedBinary
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class RunCodeResult(TypedDict):
|
|
113
|
+
sandboxId: str
|
|
114
|
+
executionCount: float | None
|
|
115
|
+
textResults: list[BoundedText]
|
|
116
|
+
artifacts: list[CodeArtifactDTO]
|
|
117
|
+
stdout: BoundedText
|
|
118
|
+
stderr: BoundedText
|
|
119
|
+
error: CodeErrorDTO | None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class WriteFileInput(TypedDict):
|
|
123
|
+
path: str
|
|
124
|
+
encoding: Literal["utf8"] | Literal["base64"]
|
|
125
|
+
content: str
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class WriteFilesInput(SandboxIdInput):
|
|
129
|
+
files: list[WriteFileInput]
|
|
130
|
+
maxTotalBytes: NotRequired[float]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class WriteFilesResult(TypedDict):
|
|
134
|
+
sandboxId: str
|
|
135
|
+
files: list[WriteFilesResultFilesItem]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class ReadFileInput(SandboxIdInput):
|
|
139
|
+
path: str
|
|
140
|
+
encoding: NotRequired[Literal["utf8"] | Literal["base64"]]
|
|
141
|
+
maxBytes: NotRequired[float]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ReadFileResult(TypedDict):
|
|
145
|
+
sandboxId: str
|
|
146
|
+
path: str
|
|
147
|
+
encoding: Literal["utf8"] | Literal["base64"]
|
|
148
|
+
content: str
|
|
149
|
+
byteCount: float
|
|
150
|
+
returnedBytes: float
|
|
151
|
+
maxBytes: float
|
|
152
|
+
truncated: Literal[False]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class ListFilesInput(SandboxIdInput):
|
|
156
|
+
path: str
|
|
157
|
+
limit: NotRequired[float]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class FileEntryDTO(TypedDict):
|
|
161
|
+
name: str
|
|
162
|
+
path: str
|
|
163
|
+
type: Literal["file"] | Literal["directory"] | Literal["symlink"] | Literal["other"]
|
|
164
|
+
size: float
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class ListFilesResult(TypedDict):
|
|
168
|
+
sandboxId: str
|
|
169
|
+
entries: list[FileEntryDTO]
|
|
170
|
+
page: BoundedCollection
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class GetSandboxLogsInput(SandboxIdInput):
|
|
174
|
+
cursor: NotRequired[float]
|
|
175
|
+
direction: NotRequired[Literal["forward"] | Literal["backward"]]
|
|
176
|
+
level: NotRequired[LogLevel]
|
|
177
|
+
search: NotRequired[str]
|
|
178
|
+
limit: NotRequired[float]
|
|
179
|
+
maxBytes: NotRequired[float]
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class SandboxLogDTO(TypedDict):
|
|
183
|
+
timestamp: str
|
|
184
|
+
level: LogLevel
|
|
185
|
+
message: BoundedText
|
|
186
|
+
logger: str | None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class GetSandboxLogsResult(TypedDict):
|
|
190
|
+
sandboxId: str
|
|
191
|
+
logs: list[SandboxLogDTO]
|
|
192
|
+
cursor: float | None
|
|
193
|
+
page: BoundedCollection
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class GetSandboxMetricsInput(SandboxIdInput):
|
|
197
|
+
start: NotRequired[str]
|
|
198
|
+
end: NotRequired[str]
|
|
199
|
+
limit: NotRequired[float]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class SandboxMetricDTO(TypedDict):
|
|
203
|
+
timestamp: str
|
|
204
|
+
cpuUsedPct: float
|
|
205
|
+
cpuCount: float
|
|
206
|
+
memoryUsedBytes: float
|
|
207
|
+
memoryTotalBytes: float
|
|
208
|
+
diskUsedBytes: float
|
|
209
|
+
diskTotalBytes: float
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class GetSandboxMetricsResult(TypedDict):
|
|
213
|
+
sandboxId: str
|
|
214
|
+
metrics: list[SandboxMetricDTO]
|
|
215
|
+
page: BoundedCollection
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class RawCodeExecution(TypedDict):
|
|
219
|
+
executionCount: float | None
|
|
220
|
+
textResults: list[str]
|
|
221
|
+
artifacts: list[RawCodeExecutionArtifactsItem]
|
|
222
|
+
stdout: str
|
|
223
|
+
stderr: str
|
|
224
|
+
error: RawCodeExecutionErrorVariant1 | None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class BoundedCollection(TypedDict):
|
|
228
|
+
returned: int
|
|
229
|
+
available: int | None
|
|
230
|
+
limit: int
|
|
231
|
+
truncated: bool
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import NO_RETRY
|
|
6
|
+
from .types import WriteFilesInput, WriteFilesResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def write_files_impl(
|
|
10
|
+
ctx: TaskContext, input: WriteFilesInput, *, deps: Deps | None = None
|
|
11
|
+
) -> WriteFilesResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.e2b.write_files(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="e2b.writeFiles", retry=NO_RETRY)
|
|
17
|
+
async def write_files(ctx: TaskContext, input: WriteFilesInput) -> WriteFilesResult:
|
|
18
|
+
return await write_files_impl(ctx, input)
|