solari-e2b-compat 0.2.11__tar.gz → 0.2.13__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.
Files changed (33) hide show
  1. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/COMPAT.md +10 -6
  2. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/PKG-INFO +1 -1
  3. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/pyproject.toml +1 -1
  4. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/__init__.py +4 -1
  5. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_commands.py +48 -1
  6. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_sandbox.py +8 -0
  7. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_sync.py +4 -1
  8. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_template.py +118 -0
  9. solari_e2b_compat-0.2.13/solari_e2b/_vendor_user.py +61 -0
  10. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/__init__.py +46 -13
  11. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/exceptions.py +11 -0
  12. solari_e2b_compat-0.2.11/solari_e2b/_vendor_user.py +0 -40
  13. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/.gitignore +0 -0
  14. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/LICENSE +0 -0
  15. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/LICENSE-E2B +0 -0
  16. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/NOTICE +0 -0
  17. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/README.md +0 -0
  18. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_box.py +0 -0
  19. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_config.py +0 -0
  20. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_filesystem.py +0 -0
  21. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_git.py +0 -0
  22. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_loop.py +0 -0
  23. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_redact.py +0 -0
  24. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_request.py +0 -0
  25. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/_volume.py +0 -0
  26. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/charts.py +0 -0
  27. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/client.py +0 -0
  28. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/code_interpreter_async.py +0 -0
  29. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/code_interpreter_sync.py +0 -0
  30. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/constants.py +0 -0
  31. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/exceptions.py +0 -0
  32. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/code_interpreter/models.py +0 -0
  33. {solari_e2b_compat-0.2.11 → solari_e2b_compat-0.2.13}/solari_e2b/models.py +0 -0
@@ -1,6 +1,6 @@
1
1
  # COMPAT.md: E2B Python SDK compatibility (API shapes follow e2b 2.59 and e2b-code-interpreter 2.11)
2
2
 
3
- Checked against the current releases (e2b 2.63.0, e2b-code-interpreter 2.11.9) on 2026-11-07: the only public name this package lacks is the `GuestUnresponsiveException` class (and the `WriteData` type alias).
3
+ Checked against the current releases (e2b 2.64.0, e2b-code-interpreter 2.11.9) on 2026-11-16: the only public names this package lacks are the `WriteData` / `AsyncWriteData` type aliases. 2.63/2.64's `GuestUnresponsiveException`, `TemplatePaginator`, `AsyncTemplatePaginator` and `TemplateInfo` exist.
4
4
 
5
5
  Legend: **OK** works and is tested; **DIFF** works with a behaviour difference (explained); **NO** raises
6
6
  `SolariCompatUnsupported` naming the feature. "Live" means `tests/test_live_staging.py` runs it against staging.
@@ -30,7 +30,7 @@ and the differences that are specific to Python.
30
30
  | `request_timeout=` | OK. A deadline in seconds on the whole call (`0` removes the limit): `TimeoutException` when it passes. Not set: Solari's own transport limits apply (E2B's default is 60 s). On a streaming start (`commands.run`, `pty.create`) it bounds the start request; `run_code` has no per-call connection to bound, so there it has no effect and `timeout` is the limit. `Template.build` does not apply it either: E2B bounds each request of a build, not the build (the wait has its own cap). |
31
31
  | `validate_api_key=` | Accepted: E2B documents it as having no effect. |
32
32
  | `debug=True`, `retries=`, `http_version=`, `sandbox_url=`, `logger=` | NO. Raise `SolariCompatUnsupported` (`debug=False` is fine). They configure E2B's own transport and local debug mode. |
33
- | An unknown option | `TypeError`, as for any Python signature. No call swallows keyword arguments any more. |
33
+ | An unknown option | `TypeError`, as for any Python signature. No call swallows keyword arguments any more. `Sandbox.create(cpu_count=, idempotency_key=)` (E2B 2.64): NO (`SolariCompatUnsupported`). |
34
34
  | `api_key=` / `domain=` / `api_url=` on a call of an already connected sandbox | NO when it points elsewhere than the sandbox's own account; pass them to `create` / `connect`. |
35
35
  | `timeout=` arguments | Seconds, as in E2B. |
36
36
  | `E2B(...)` client, `ApiClient`, `ConnectionConfig`, `VolumeConnectionConfig`, `client` | NO. Real classes (they import, annotate and subclass), construction or use raises. |
@@ -79,7 +79,7 @@ and the differences that are specific to Python.
79
79
  | `write` over 32 MiB | One write is one frame on the control channel, so more than 32 MiB raises `InvalidArgumentException` before anything is sent. Get a signed URL with `sandbox.upload_url(path)` and PUT the bytes to it (E2B has no `files.upload`). |
80
80
  | `list(path, depth)`, `get_info` | OK, live | Every symlink (also a dangling one) is returned as itself: `type=FileType.SYMLINK`, `symlink_target`, `permissions` like `Lrwxrwxrwx`, and it is not descended into by `depth`. `owner` and `group` are filled in. One extra shell command per listing does this (it needs `/bin/sh`; without it the plain listing is used: links are followed, `owner` / `group` are empty, and a dangling link raises). |
81
81
  | `exists`, `make_dir`, `rename`, `remove` | OK, live | |
82
- | `watch_dir(path, on_event, recursive=)` | DIFF, live | `FilesystemEvent.name` is relative to the watched path. Solari reports creates as `write`. `include_entry=True` adds the entry (best effort: none when the path is already gone). `allow_network_mounts` has no effect (Solari's watcher has no such limit). A watch ends after `timeout` seconds (default 60; 0 disables); `on_exit(None)` is called once, whether it timed out or you called `stop()`. |
82
+ | `watch_dir(path, on_event, recursive=)` | DIFF, live | `FilesystemEvent.name` is relative to the watched path. A new file or directory is reported as `create`, as in E2B (the guest's watcher reports creates, writes, removes, renames and mode changes separately); an event type E2B has no name for is reported as `write`. `include_entry=True` adds the entry (best effort: none when the path is already gone). `allow_network_mounts` has no effect (Solari's watcher has no such limit). A watch ends after `timeout` seconds (default 60; 0 disables); `on_exit(None)` is called once, whether it timed out or you called `stop()`. |
83
83
  | `user=` on any filesystem call | NO | |
84
84
  | Which paths `files.*` can reach | OK, live | Every filesystem call runs as the sandbox user (`user`, or the Daytona/Runloop name), as in E2B: relative paths resolve against `/home/user`, `files.read('/etc/shadow')` and `files.write('/etc/x', ...)` are refused with the guest's `permission denied`, and what you write is owned by `user:user`. This needs a guest image that carries the fix (images built before it keep the old behaviour: `files.*` then ran as root and reached any path); `whoami` and `files.read('/etc/shadow')` tell you which you have. The `user` option on a filesystem call is still NO. |
85
85
 
@@ -89,7 +89,8 @@ and the differences that are specific to Python.
89
89
  | `run_code(code, language=None, context=None, ...)` | OK, live | Python (and `bash`). Passing both `language` and `context` raises `InvalidArgumentException`. Python state persists across calls in the default context. |
90
90
  | `run_code(..., envs=)` | OK, live | Set in the kernel's `os.environ` (or passed to `bash`) for that run only and put back after it, also when the code fails. |
91
91
  | Other languages | NO | The guest ships a Python kernel only: `javascript`, `typescript`, `r`, `java` raise. `bash` runs each call as a fresh shell (no state between calls). |
92
- | `on_stdout`, `on_stderr`, `on_result`, `on_error` | DIFF | Called after the run finishes, not while it runs (Solari returns the result in one reply). Sync or async callables. |
92
+ | `on_stdout`, `on_stderr` | OK | Called while the code runs, one message per line (an unfinished last line when it ends). Sync or async callables (an async one is scheduled, as everywhere in this package, and an exception in a callback never breaks the run). A guest that does not stream sends everything at the end. |
93
+ | `on_result`, `on_error` | DIFF | Called after the run finishes, not while it runs (Solari returns the results in one reply). Sync or async callables. |
93
94
  | `Execution` (`results`, `logs`, `error`, `text`) | DIFF | `execution_count` is `None`. `error` is `ExecutionError(name, value, traceback)`. The last result with a text repr is `is_main_result`. |
94
95
  | `Result` formats | DIFF | `text`, `html`, `markdown`, `svg`, `png`, `jpeg`, `latex`, `json` (as given by the kernel), `chart`. `pdf`, `javascript`, `data` and `extra` are not produced. `chart` is E2B's class for its type (`LineChart`, `ScatterChart`, `BarChart`, `SuperChart`, ... in `solari_e2b.code_interpreter.charts`) and appears when the guest kernel extracts a structured chart (not for every figure). |
95
96
  | `envs=` per run | NO | |
@@ -106,6 +107,8 @@ and the differences that are specific to Python.
106
107
  | `copy`, `copy_items` (and `force_upload`, `resolve_symlinks`, `gzip`, `Template(file_ignore_patterns=)` that only matter through them) | NO | The Solari gateway does not accept local files in a template build yet (it answers `LocalFilesUnsupported`), so this raises when called instead of failing at build time. Fetch files inside the build with `run_cmd` (`curl`) or `git_clone`. |
107
108
  | `set_user`, `set_start_cmd`, `set_ready_cmd`, `add_mcp_server`, dev containers | NO | Solari templates run no start command. Start processes after `Sandbox.create` with `commands.run(..., background=True)`. |
108
109
  | `skip_cache()`, `skip_cache=` | OK | Nothing to skip: Solari has no build cache, every build runs every step. |
110
+ | `Template.list(limit=, next_token=)` → `TemplatePaginator`, `AsyncTemplate.list(...)` → `AsyncTemplatePaginator`, of `TemplateInfo` (e2b 2.63+) | OK | The account's sandbox templates (built-ins and your own; desktop templates are left out). `template_id`, `names` (the template name), `build_status` (`READY`, `ERROR` for a failed build, else `BUILDING`), `cpu_count` / `memory_mb` (0 when the gateway does not report them), `created_at` and `is_default` / `public` (true for Solari's built-in templates) come from Solari; `build_id` is the template id (Solari templates have no separate builds), `updated_at` is `created_at`, `envd_version` is `"solari"`, and `disk_size_mb`, `build_count`, `spawn_count` are 0 (Solari does not track them). The gateway returns the whole list at once, so the first page reads it and `next_token` is an offset into it. |
111
+ | `GuestUnresponsiveException` (e2b 2.63+) | DIFF | A `SandboxException`, raised when the gateway answers `GuestUnreachable` (502): the guest's control channel did not answer while the sandbox started or resumed. E2B's cause (a snapshot taken while the guest agent was stuck, fixed with `on_resume="reboot"`) has no Solari counterpart; retry the call. `GuestUnresponsiveException.code` keeps E2B's value. |
109
112
  | `Template.build(template, name)`, `build_in_background`, `get_build_status`, `exists`, `alias_exists` | OK, live | `name:latest` is accepted; any other tag, and `tags=`: NO. `min_free_disk_mb=`: NO. `on_build_logs` receives a start entry, the build's own log lines (polled every few seconds from the gateway's build log), and an end entry. `get_build_status(..., logs_offset=)` returns `log_entries` / `logs` from that offset of the gateway's log tail (`stdout` lines are `info`, `stderr` lines `error`); the gateway keeps the newest 5000 lines of a build: `on_build_logs` keeps delivering new lines once that window is full (it finds where it left off), but a line that scrolled out before it was polled is lost, and `logs_offset` counts lines of the current window. A background build delivers only its start entry to `on_build_logs`. If the gateway cannot return the tail from the replica that answers (it keeps it in memory per replica), `log_entries` is empty and a warning says so. `status` is a `TemplateBuildStatus`, `reason` a `BuildStatusReason`. `Template.build` blocks (the `AsyncTemplate` twin is awaitable). |
110
113
  | `Template.assign_tags`, `remove_tags`, `get_tags`, `to_json`, `to_dockerfile` | NO | |
111
114
 
@@ -124,7 +127,7 @@ and the differences that are specific to Python.
124
127
  - Tested on Python 3.14; the code avoids syntax newer than 3.9 but only 3.14 is exercised here.
125
128
 
126
129
  ## Default user and home directory (matching E2B)
127
- **Sandboxes run as `user` in `/home/user` on the hosted Solari API, matching E2B's default** (checked on staging and production on 2026-11-03). Only a gateway or a template that predates user support falls back to root, as below.
130
+ **Sandboxes run as `user` in `/home/user` on the hosted Solari API, matching E2B's default** (checked on staging and production on 2026-11-03). A template built from a container image (Alpine, Ubuntu, any image base), and a gateway or template that predates user support, fall back to root, as below.
128
131
 
129
132
  Here, E2B sandboxes run as `user` in `/home/user`; commands, code and files all start there, and relative paths resolve against it. This package
130
133
  asks the gateway for exactly that at create time (`user: "user"`, `cwd: "/home/user"`; the gateway creates the user at first boot with passwordless
@@ -132,7 +135,8 @@ sudo). Restores from a snapshot keep the snapshot's own user.
132
135
  - **Gateway that predates `user` / `cwd`** (it answers 400 naming them, or ignores them): the plain create is used and the sandbox runs as **root in
133
136
  `/home/root`**, which is what this package did before. Check `whoami` if code depends on it.
134
137
  - **Template or snapshot made before user support** (the server answers 400 naming `user` with "the guest predates user support"): the plain create is used, the sandbox runs as **root**, and one warning says so. Rebuild the template to get the vendor user. The default code-interpreter template is named `code-interpreter-v2`, so upgrading this package builds a fresh one on first `Sandbox.create()`; an older `code-interpreter-v1` in your org is left alone and no longer used.
135
- - Shared isolation is commands and code only and takes no `user` / `cwd`; the compat packages never create shared sandboxes. `commands.run(..., user=)` is passed to the guest per call; `user=` on filesystem calls stays NO.
138
+ - **Template built from a container image** (`Template().from_image(...)`, `from_alpine_image()`, `from_ubuntu_image()` and the other image bases; the server answers 400 naming `user` with "not available on a template built from an image"): the guest cannot add `user` to an image's own user database, so the plain create is used and commands run as the image's default user: **root** unless the image sets `USER` (Alpine and most base images do not). One warning names this cause. Rebuilding does not change it; build on `from_base_image()` (Solari's base image) to get `user`. (Checked against the gateway and guest code, 2026-11-16.)
139
+ - Shared isolation is commands and code only and takes no `user` / `cwd`; the compat packages never create shared sandboxes. `commands.run(..., user=)` is passed to the guest per call; `user=` on filesystem calls stays NO. A foreground command on a shared sandbox you connect to runs over REST: its output arrives when the command ends, `envs` are honoured, and the deadline is REST's 1 s to 10 min. `git` (init, add, commit; checked live on a shared sandbox, TS and Python) runs through these commands and works. Background commands, stdin, `user`, files and PTYs stay refused with the gateway's own message.
136
140
 
137
141
  ## Snapshots, results and listing (0.2.1)
138
142
  - A template name that starts with `snap_` is always read as a snapshot id (name your templates otherwise). `Sandbox.create("snap_…")` restores from that snapshot (E2B's snapshot docs); killing the restored sandbox never deletes the snapshot.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: solari-e2b-compat
3
- Version: 0.2.11
3
+ Version: 0.2.13
4
4
  Summary: E2B-compatible Python interface (sandboxes and code interpreter) over Solari Sandboxes. Not affiliated with E2B.
5
5
  Project-URL: Homepage, https://getsolari.com
6
6
  Author: Solari
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "solari-e2b-compat"
7
- version = "0.2.11"
7
+ version = "0.2.13"
8
8
  description = "E2B-compatible Python interface (sandboxes and code interpreter) over Solari Sandboxes. Not affiliated with E2B."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -17,6 +17,7 @@ from ._sandbox import AsyncSandbox, AsyncSandboxPaginator, AsyncSnapshotPaginato
17
17
  from ._sync import CommandHandle, Git, Sandbox, SandboxPaginator, SnapshotPaginator, WatchHandle
18
18
  from ._template import (
19
19
  AsyncTemplate,
20
+ AsyncTemplatePaginator,
20
21
  BuildInfo,
21
22
  BuildStatusReason,
22
23
  CopyItem,
@@ -30,6 +31,8 @@ from ._template import (
30
31
  TemplateBuildStatus,
31
32
  TemplateBuildStatusResponse,
32
33
  TemplateClass,
34
+ TemplateInfo,
35
+ TemplatePaginator,
33
36
  TemplateTag,
34
37
  TemplateTagInfo,
35
38
  default_build_logger,
@@ -76,4 +79,4 @@ class _UnsupportedModule:
76
79
 
77
80
  client = _UnsupportedModule()
78
81
 
79
- __version__ = "0.2.11"
82
+ __version__ = "0.2.13"
@@ -17,6 +17,7 @@ from ._request import bounded
17
17
  from .exceptions import (
18
18
  CommandExitException,
19
19
  CommandResult,
20
+ InvalidArgumentException,
20
21
  NotFoundException,
21
22
  SandboxException,
22
23
  SolariCompatUnsupported,
@@ -32,6 +33,25 @@ class _DefaultTimeout(float):
32
33
 
33
34
 
34
35
  DEFAULT_COMMAND_TIMEOUT = _DefaultTimeout(60.0)
36
+
37
+ #: The deadlines Solari's REST exec takes (1 s to 10 min).
38
+ _REST_MIN_MS = 1000
39
+ _REST_MAX_MS = 600_000
40
+
41
+
42
+ def _is_shared_refusal(err: BaseException) -> bool:
43
+ """The gateway refused a command stream because the sandbox is ``shared`` (it runs commands over REST and code only)."""
44
+ return re.search(r"NotAvailableOnSharedIsolation|not available on a shared", str(err)) is not None
45
+
46
+
47
+ def _export_prefix(envs: Optional[Dict[str, str]]) -> str:
48
+ """``export NAME='value'`` line for each variable (names are checked, values single-quoted), or nothing."""
49
+ out = []
50
+ for name, value in (envs or {}).items():
51
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
52
+ raise InvalidArgumentException(f"{name!r} is not a valid environment variable name")
53
+ out.append("export " + name + "='" + str(value).replace("'", "'\\''") + "'\n")
54
+ return "".join(out)
35
55
  _next_pid = 1000
36
56
  _procs: Dict[str, Dict[int, "_Rec"]] = {}
37
57
  #: A command or PTY the guest no longer knows (it ended and was reaped): the guest answers ``unknown cmdId`` / ``unknown ptyId``.
@@ -296,7 +316,14 @@ class AsyncCommands:
296
316
  timeout: Optional[float] = DEFAULT_COMMAND_TIMEOUT,
297
317
  request_timeout: Optional[float] = None,
298
318
  ) -> Union[CommandResult, AsyncCommandHandle]:
299
- handle = await self._start(cmd, envs, user, cwd, on_stdout, on_stderr, bool(stdin), request_timeout)
319
+ try:
320
+ handle = await self._start(cmd, envs, user, cwd, on_stdout, on_stderr, bool(stdin), request_timeout)
321
+ except Exception as e: # noqa: BLE001
322
+ # A ``shared`` sandbox refuses command streams but runs commands over REST (commands and code only). Nothing started, so a
323
+ # foreground command that needs nothing the REST route lacks (stdin, or another user) runs there instead.
324
+ if not background and not stdin and not user and _is_shared_refusal(e):
325
+ return await self._run_over_rest(cmd, envs, cwd, on_stdout, on_stderr, timeout, request_timeout)
326
+ raise
300
327
  if background:
301
328
  # ``timeout`` of a background command is how long this connection to it lives; unset / 0 never cuts it.
302
329
  handle._arm(None if isinstance(timeout, _DefaultTimeout) else timeout)
@@ -312,6 +339,26 @@ class AsyncCommands:
312
339
  raise TimeoutException(f"Command timed out after {timeout:g}s") from None
313
340
  return await handle.wait()
314
341
 
342
+ async def _run_over_rest(self, cmd, envs, cwd, on_stdout, on_stderr, timeout, request_timeout) -> CommandResult:
343
+ """A foreground command on a ``shared`` sandbox: one REST call, so the output arrives when the command ends (the callbacks get it then,
344
+ once) and the process cannot be listed or killed by pid. A non-zero exit is a :class:`CommandExitException`, the deadline a
345
+ :class:`TimeoutException`, as on the streaming path. The REST route takes a deadline of 1 s to 10 min, so 0 / ``None`` (no
346
+ limit) means 10 min. ``envs`` become ``export NAME='value'`` lines before the command, which is what the shell does with them anyway."""
347
+ native = await self._box.is_native()
348
+ program, args = shell_args(native, f"exec 0</dev/null\n{_export_prefix(envs)}{cmd}")
349
+ wd = await self._box.abs(cwd) if cwd else await self._box.home()
350
+ timeout_ms = max(_REST_MIN_MS, min(int(timeout * 1000), _REST_MAX_MS)) if timeout else _REST_MAX_MS
351
+ r = await bounded(self._box.on(lambda sb: sb.commands.run(program, args=args, cwd=wd, timeout_ms=timeout_ms)), request_timeout)
352
+ if getattr(r, "timedOut", False):
353
+ raise TimeoutException(f"Command timed out after {timeout_ms / 1000:g}s")
354
+ if r.stdout:
355
+ fire(on_stdout, r.stdout)
356
+ if r.stderr:
357
+ fire(on_stderr, r.stderr)
358
+ if r.exitCode != 0:
359
+ raise CommandExitException(r.stderr, r.stdout, r.exitCode, None)
360
+ return CommandResult(stderr=r.stderr, stdout=r.stdout, exit_code=r.exitCode, error=None)
361
+
315
362
  async def _start(self, cmd, envs, user, cwd, on_stdout, on_stderr, stdin: bool = False, request_timeout: Optional[float] = None) -> AsyncCommandHandle:
316
363
  native = await self._box.is_native()
317
364
  # E2B starts a command with stdin closed unless stdin=True: a program that reads stdin gets end-of-file at once.
@@ -423,8 +423,16 @@ class AsyncSandbox:
423
423
  lifecycle: Optional[Dict[str, Any]] = None,
424
424
  volume_mounts: Optional[Dict[str, Any]] = None,
425
425
  logger: Any = None,
426
+ idempotency_key: Optional[str] = None,
427
+ *,
428
+ cpu_count: Optional[int] = None,
426
429
  **opts: Any,
427
430
  ) -> "AsyncSandbox":
431
+ # E2B 2.64 options Solari has no counterpart for yet: refused by name, never ignored (an unknown keyword is a TypeError).
432
+ if cpu_count is not None:
433
+ raise SolariCompatUnsupported("Sandbox.create option cpu_count", "a Solari sandbox gets its template's CPU count; build a template with the CPU count you want (Template.build cpu_count)")
434
+ if idempotency_key is not None:
435
+ raise SolariCompatUnsupported("Sandbox.create option idempotency_key", "Solari's sandbox create takes no caller-chosen idempotency key")
428
436
  if mcp is not None:
429
437
  raise SolariCompatUnsupported("mcp", "the E2B MCP gateway has no Solari equivalent")
430
438
  hardened = _wants_no_egress(network, allow_internet_access)
@@ -367,9 +367,12 @@ class Sandbox:
367
367
  lifecycle: Optional[Dict[str, Any]] = None,
368
368
  volume_mounts: Optional[Dict[str, Any]] = None,
369
369
  logger: Any = None,
370
+ idempotency_key: Optional[str] = None,
371
+ *,
372
+ cpu_count: Optional[int] = None,
370
373
  **opts: Any,
371
374
  ) -> "Sandbox":
372
- return cls._wrap(LOOP.run(cls._async_cls.create(template, timeout, metadata, envs, secure, allow_internet_access, mcp, network, iam, lifecycle, volume_mounts, logger, **opts)))
375
+ return cls._wrap(LOOP.run(cls._async_cls.create(template, timeout, metadata, envs, secure, allow_internet_access, mcp, network, iam, lifecycle, volume_mounts, logger, idempotency_key, cpu_count=cpu_count, **opts)))
373
376
 
374
377
  @classmethod
375
378
  def list(cls, query: Optional[SandboxQuery] = None, limit: Optional[int] = None, next_token: Optional[str] = None, order: Optional[str] = None, **opts: Any) -> SandboxPaginator:
@@ -139,6 +139,114 @@ class TemplateTag:
139
139
  CopyItem = Dict[str, Any]
140
140
 
141
141
 
142
+ @dataclass
143
+ class TemplateInfo:
144
+ """e2b 2.63+ template listing entry, filled from the Solari template list (COMPAT.md says which fields Solari does not
145
+ track)."""
146
+
147
+ template_id: str
148
+ #: Solari templates have no separate builds: the template id.
149
+ build_id: str
150
+ names: List[str]
151
+ #: True for Solari's built-in templates (every account can use them).
152
+ public: bool
153
+ #: True for Solari's built-in templates.
154
+ is_default: bool
155
+ build_status: TemplateBuildStatus
156
+ #: 0 when the gateway does not report it.
157
+ cpu_count: int
158
+ #: 0 when the gateway does not report it.
159
+ memory_mb: int
160
+ #: Not reported by Solari: 0.
161
+ disk_size_mb: int
162
+ envd_version: str
163
+ #: Not tracked by Solari: 0.
164
+ build_count: int
165
+ #: Not tracked by Solari: 0.
166
+ spawn_count: int
167
+ created_at: datetime
168
+ #: Solari does not track updates: the creation time.
169
+ updated_at: datetime
170
+ last_spawned_at: Optional[datetime] = None
171
+ description: Optional[str] = None
172
+ max_cpu_count: Optional[int] = None
173
+
174
+
175
+ def _template_info(v: Dict[str, Any]) -> TemplateInfo:
176
+ raw = v.get("createdAt")
177
+ try:
178
+ created = datetime.fromisoformat(raw.replace("Z", "+00:00")) if isinstance(raw, str) else datetime.fromtimestamp(0, timezone.utc)
179
+ except ValueError:
180
+ created = datetime.fromtimestamp(0, timezone.utc)
181
+ st = v.get("status")
182
+ status = TemplateBuildStatus.READY if st == "ready" else TemplateBuildStatus.ERROR if st == "failed" else TemplateBuildStatus.BUILDING
183
+ builtin = bool(v.get("builtin"))
184
+ return TemplateInfo(
185
+ template_id=v["templateId"], build_id=v["templateId"], names=[v.get("name") or v["templateId"]], public=builtin, is_default=builtin,
186
+ build_status=status, cpu_count=int(v.get("cpu") or 0), memory_mb=int(v.get("memMb") or 0), disk_size_mb=0, envd_version="solari",
187
+ build_count=0, spawn_count=0, created_at=created, updated_at=created,
188
+ )
189
+
190
+
191
+ class AsyncTemplatePaginator:
192
+ """e2b 2.63+ paginator over the account's sandbox templates (``AsyncTemplate.list()``). The gateway returns the whole list
193
+ at once, so the first page reads it and later pages are cut from it; ``next_token`` is the offset of the next page."""
194
+
195
+ def __init__(self, limit: Optional[int] = None, next_token: Optional[str] = None, **opts: Any) -> None:
196
+ if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1):
197
+ raise InvalidArgumentException("limit must be a positive integer")
198
+ if next_token is not None and not (isinstance(next_token, str) and next_token.isdigit()):
199
+ raise InvalidArgumentException("next_token must be a token returned by this paginator")
200
+ self._opts = api_opts(opts)
201
+ self._limit = limit or 100
202
+ self._next_token = next_token
203
+ self._has_next = True
204
+ self._all: Optional[List[TemplateInfo]] = None
205
+
206
+ @property
207
+ def has_next(self) -> bool:
208
+ return self._has_next
209
+
210
+ @property
211
+ def next_token(self) -> Optional[str]:
212
+ return self._next_token
213
+
214
+ async def next_items(self, **opts: Any) -> List[TemplateInfo]:
215
+ if not self._has_next:
216
+ raise TemplateException("No more items to fetch")
217
+ o = {**self._opts, **api_opts(opts)}
218
+ if self._all is None:
219
+ conn = resolve_conn(**o)
220
+ try:
221
+ views = await bounded(conn.templates.list(), o.get("request_timeout"))
222
+ except Exception as e: # noqa: BLE001
223
+ raise translate(e) from e
224
+ self._all = [_template_info(v) for v in views if v.get("kind") == "sandbox"]
225
+ start = int(self._next_token) if self._next_token else 0
226
+ page = self._all[start : start + self._limit]
227
+ self._next_token = str(start + self._limit) if start + self._limit < len(self._all) else None
228
+ self._has_next = self._next_token is not None
229
+ return page
230
+
231
+
232
+ class TemplatePaginator:
233
+ """Blocking ``Template.list()`` pages."""
234
+
235
+ def __init__(self, limit: Optional[int] = None, next_token: Optional[str] = None, **opts: Any) -> None:
236
+ self._t = AsyncTemplatePaginator(limit, next_token, **opts)
237
+
238
+ @property
239
+ def has_next(self) -> bool:
240
+ return self._t.has_next
241
+
242
+ @property
243
+ def next_token(self) -> Optional[str]:
244
+ return self._t.next_token
245
+
246
+ def next_items(self, **opts: Any) -> List[TemplateInfo]:
247
+ return LOOP.run(self._t.next_items(**opts))
248
+
249
+
142
250
  q = shlex.quote
143
251
  _IMAGES = {
144
252
  "from_debian_image": ("debian", "stable"),
@@ -520,6 +628,11 @@ class AsyncTemplate(TemplateBase):
520
628
  reason = BuildStatusReason(message=v["error"], log_entries=entries) if v.get("error") else None
521
629
  return TemplateBuildStatusResponse(build_id=build_info.build_id, template_id=build_info.template_id, status=status, log_entries=entries, logs=[e.message for e in entries], reason=reason)
522
630
 
631
+ @classmethod
632
+ def list(cls, *, limit: Optional[int] = None, next_token: Optional[str] = None, **opts: Any) -> AsyncTemplatePaginator:
633
+ """e2b 2.63+: the account's sandbox templates, page by page."""
634
+ return AsyncTemplatePaginator(limit, next_token, **opts)
635
+
523
636
  @classmethod
524
637
  async def exists(cls, name: str, **opts: Any) -> bool:
525
638
  o = api_opts(opts)
@@ -558,6 +671,11 @@ class Template(TemplateBase):
558
671
  def get_build_status(cls, build_info: BuildInfo, logs_offset: Optional[int] = None, **opts: Any) -> TemplateBuildStatusResponse:
559
672
  return LOOP.run(AsyncTemplate.get_build_status(build_info, logs_offset, **opts))
560
673
 
674
+ @classmethod
675
+ def list(cls, *, limit: Optional[int] = None, next_token: Optional[str] = None, **opts: Any) -> TemplatePaginator:
676
+ """e2b 2.63+: the account's sandbox templates, page by page."""
677
+ return TemplatePaginator(limit, next_token, **opts)
678
+
561
679
  @classmethod
562
680
  def exists(cls, name: str, **opts: Any) -> bool:
563
681
  return LOOP.run(AsyncTemplate.exists(name, **opts))
@@ -0,0 +1,61 @@
1
+ """Create sandboxes that run as E2b's default user (commands, code and files default to its home)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import warnings
7
+ from typing import Any
8
+
9
+ from solari_core.errors import GatewayError
10
+
11
+ VENDOR_USER = "user"
12
+ VENDOR_HOME = "/home/user"
13
+
14
+
15
+ def _refuses_user_fields(e: BaseException) -> bool:
16
+ return isinstance(e, GatewayError) and e.status == 400 and re.search(r"\b(user|cwd)\b", repr(getattr(e, "body", None)), re.I) is not None
17
+
18
+ def _reason_of(e: BaseException) -> str:
19
+ """The gateway's reason for refusing ``user`` (its 400 says why), so the warning names the real cause."""
20
+ body = getattr(e, "body", None)
21
+ for s in (getattr(body, "error", None), getattr(body, "message", None), str(e)):
22
+ if isinstance(s, str) and s:
23
+ return s
24
+ return ""
25
+
26
+
27
+ def root_warning_text(reason: str) -> str:
28
+ """The warning for a sandbox that runs as root because the gateway would not give it the vendor user, built from the
29
+ gateway's reason. A template built from a container image (Alpine, Ubuntu, any ``FROM`` image) keeps the image's own
30
+ accounts: the guest cannot add a user there, and rebuilding does not change that."""
31
+ head = f"solari-e2b-compat: the sandbox runs as root instead of '{VENDOR_USER}'"
32
+ if re.search(r"built from an image|rootDir", reason, re.I):
33
+ return (
34
+ f"{head} because its template was built from a container image (for example Alpine), and Solari cannot add the "
35
+ f"'{VENDOR_USER}' account to an image's own user database: commands run as the image's default user (root unless the "
36
+ f"image sets USER). Rebuilding the template does not change this; build the template on from_base_image() (Solari's base image) to get '{VENDOR_USER}'."
37
+ )
38
+ if re.search(r"predates user support", reason, re.I):
39
+ return f"{head} because the template or snapshot was made before user support shipped. Rebuild it to get the vendor user."
40
+ if re.search(r"host pool", reason, re.I):
41
+ return f"{head} because this server's host pool cannot run sandboxes as a chosen user yet. Nothing in your template causes this."
42
+ return f"{head} because the server would not create the user" + (f" ({reason})." if reason else ".")
43
+
44
+
45
+ def _warn_root(e: BaseException) -> None:
46
+ warnings.warn(root_warning_text(_reason_of(e)), RuntimeWarning, stacklevel=4)
47
+
48
+
49
+ async def create_as_vendor_user(solari: Any, **opts: Any) -> Any:
50
+ """``solari.create(**opts)`` with ``user`` / ``cwd`` set to E2b's defaults. A gateway that predates them (it answers 400
51
+ naming them) gets the plain create, and the sandbox runs as root there (COMPAT.md). Restores from a snapshot keep the
52
+ snapshot's own user and are sent without them."""
53
+ if opts.get("from_snapshot") is not None:
54
+ return await solari.create(**opts)
55
+ try:
56
+ return await solari.create(**opts, user=VENDOR_USER, cwd=VENDOR_HOME)
57
+ except GatewayError as e:
58
+ if not _refuses_user_fields(e):
59
+ raise
60
+ _warn_root(e)
61
+ return await solari.create(**opts)
@@ -292,6 +292,29 @@ _PLOTTING = re.compile(r"matplotlib|pyplot|\bplt\b|seaborn|\bsns\b|\bfigure\b|\.
292
292
  _ENTITIES = (("&lt;", "<"), ("&gt;", ">"), ("&quot;", '"'), ("&#39;", "'"), ("&nbsp;", " "), ("&amp;", "&"))
293
293
 
294
294
 
295
+ class _Lines:
296
+ """Output as it arrives, one E2B message per line. Core delivers text in whatever pieces the guest writes (or the whole output at the end
297
+ from a guest that does not stream); this joins them into lines and fires the user's handler for each, and ``end()`` delivers an unfinished
298
+ last line."""
299
+
300
+ def __init__(self, handler: Optional[Callable[..., Any]], error: bool) -> None:
301
+ self._handler, self._error, self._buf = handler, error, ""
302
+
303
+ def push(self, chunk: str) -> None:
304
+ self._buf += chunk
305
+ while True:
306
+ i = self._buf.find("\n")
307
+ if i < 0:
308
+ return
309
+ line, self._buf = self._buf[: i + 1], self._buf[i + 1:]
310
+ fire(self._handler, OutputMessage(line, time.time_ns(), self._error))
311
+
312
+ def end(self) -> None:
313
+ if self._buf:
314
+ line, self._buf = self._buf, ""
315
+ fire(self._handler, OutputMessage(line, time.time_ns(), self._error))
316
+
317
+
295
318
  def per_line(text: str) -> List[str]:
296
319
  """One entry per line, newline kept, as E2B delivers kernel output (one message per print)."""
297
320
  return re.findall(r"[^\n]*\n|[^\n]+$", text)
@@ -458,28 +481,30 @@ class AsyncSandbox(_AsyncBase):
458
481
  # `request_timeout` only bounds how long E2B waits for the run to start answering; Solari answers once, when the run ends,
459
482
  # so it has no effect here (`timeout` bounds the whole run).
460
483
  env = dict(envs) if envs else None
461
- coro = self._run_bash(code, env) if lang == "bash" else self._run_python(code, lang, context, env)
484
+ # Output goes to the handlers while the code runs (core streams it; a guest that does not stream delivers it all at the end).
485
+ out = _Lines(on_stdout, False) if on_stdout else None
486
+ err = _Lines(on_stderr, True) if on_stderr else None
487
+ coro = self._run_bash(code, env, out, err) if lang == "bash" else self._run_python(code, lang, context, env, out, err)
462
488
  try:
463
489
  ex = await (asyncio.wait_for(coro, timeout) if timeout and timeout > 0 else coro)
464
490
  except asyncio.TimeoutError:
465
491
  raise TimeoutException(f"Execution timed out after {timeout:g}s (the kernel keeps running the code)") from None
466
- now = time.time_ns()
467
- for l in ex.logs.stdout:
468
- fire(on_stdout, OutputMessage(l, now, False))
469
- for l in ex.logs.stderr:
470
- fire(on_stderr, OutputMessage(l, now, True))
492
+ if out:
493
+ out.end()
494
+ if err:
495
+ err.end()
471
496
  for r in ex.results:
472
497
  fire(on_result, r)
473
498
  if ex.error:
474
499
  fire(on_error, ex.error)
475
500
  return ex
476
501
 
477
- async def _run_python(self, code: str, language: str, context: Optional[Context], envs: Optional[Dict[str, str]] = None) -> Execution:
502
+ async def _run_python(self, code: str, language: str, context: Optional[Context], envs: Optional[Dict[str, str]] = None, out: Optional["_Lines"] = None, err: Optional["_Lines"] = None) -> Execution:
478
503
  if language not in _PY:
479
504
  raise SolariCompatUnsupported(f'run_code language "{language}"', "the Solari guest ships a Python kernel (and bash through language='bash')")
480
505
  cid = context.id if context else None
481
506
  if not envs:
482
- return await self._run_python_code(code, cid)
507
+ return await self._run_python_code(code, cid, out, err)
483
508
  # `envs` for one run: set in the kernel's os.environ before the code and put back after it, also when the code fails.
484
509
  setup = (
485
510
  "import os as __solari_os, json as __solari_json\n"
@@ -493,21 +518,29 @@ class AsyncSandbox(_AsyncBase):
493
518
  )
494
519
  await self._box.on(lambda sb: sb.run_code(setup, language="python", context_id=cid))
495
520
  try:
496
- return await self._run_python_code(code, cid)
521
+ return await self._run_python_code(code, cid, out, err)
497
522
  finally:
498
523
  try:
499
524
  await self._box.on(lambda sb: sb.run_code(restore, language="python", context_id=cid))
500
525
  except Exception: # noqa: BLE001
501
526
  pass
502
527
 
503
- async def _run_python_code(self, code: str, cid: Optional[str]) -> Execution:
528
+ async def _run_python_code(self, code: str, cid: Optional[str], out: Optional["_Lines"] = None, err: Optional["_Lines"] = None) -> Execution:
504
529
  plotting = bool(_PLOTTING.search(code))
505
530
  if plotting:
506
531
  try:
507
532
  await self._box.on(lambda sb: sb.run_code(CHART_HOOK, language="python", context_id=cid))
508
533
  except Exception: # noqa: BLE001
509
534
  pass
510
- r = await self._box.on(lambda sb: sb.run_code(code, language="python", context_id=cid))
535
+ r = await self._box.on(
536
+ lambda sb: sb.run_code(
537
+ code,
538
+ language="python",
539
+ context_id=cid,
540
+ **({"on_stdout": out.push} if out else {}),
541
+ **({"on_stderr": err.push} if err else {}),
542
+ )
543
+ )
511
544
  stdout: List[str] = []
512
545
  stderr: List[str] = []
513
546
  items: List[Any] = []
@@ -540,9 +573,9 @@ class AsyncSandbox(_AsyncBase):
540
573
  results = [to_result(it, n == last_text, fig_charts.get(n)) for n, it in enumerate(items)]
541
574
  return Execution(results, Logs(stdout, stderr), to_execution_error(r.error) if r.error is not None else None)
542
575
 
543
- async def _run_bash(self, code: str, envs: Optional[Dict[str, str]] = None) -> Execution:
576
+ async def _run_bash(self, code: str, envs: Optional[Dict[str, str]] = None, out: Optional["_Lines"] = None, err: Optional["_Lines"] = None) -> Execution:
544
577
  try:
545
- r = await self.commands.run(code, timeout=0, envs=envs)
578
+ r = await self.commands.run(code, timeout=0, envs=envs, on_stdout=out.push if out else None, on_stderr=err.push if err else None)
546
579
  return Execution([], Logs([r.stdout] if r.stdout else [], [r.stderr] if r.stderr else []))
547
580
  except CommandExitException as e:
548
581
  return Execution([], Logs([e.stdout] if e.stdout else [], [e.stderr] if e.stderr else []), ExecutionError("CommandExitError", f"exit status {e.exit_code}", e.stderr))
@@ -67,6 +67,15 @@ class GitUpstreamException(SandboxException): ...
67
67
  class TemplateException(SandboxException): ...
68
68
 
69
69
 
70
+ class GuestUnresponsiveException(SandboxException):
71
+ """e2b 2.63+: the sandbox's guest agent did not respond. Raised when the Solari gateway reports ``GuestUnreachable``
72
+ (502): the guest's control channel did not answer while the sandbox started or resumed. Solari has no
73
+ ``on_resume="reboot"``; retry the call (the gateway marks the answer retryable)."""
74
+
75
+ #: E2B's API ``error_code`` for this exception, kept so code that compares it still works.
76
+ code = "sandbox_snapshot_guest_agent_unresponsive"
77
+
78
+
70
79
  class RateLimitException(SandboxException):
71
80
  def __init__(self, *args: object, status_code: Optional[int] = 429) -> None:
72
81
  super().__init__(*args, status_code=status_code)
@@ -156,6 +165,8 @@ def translate(err: BaseException, what: str = "other") -> BaseException:
156
165
  s = err.status
157
166
  if s in (401, 403):
158
167
  return AuthenticationException(msg)
168
+ if getattr(err, "code", None) == "GuestUnreachable":
169
+ return _chain(GuestUnresponsiveException(msg, status_code=s), err)
159
170
  if s == 404:
160
171
  cls = SandboxNotFoundException if what == "sandbox" else FileNotFoundException if what == "file" else NotFoundException
161
172
  return _chain(cls(msg, status_code=s), err)
@@ -1,40 +0,0 @@
1
- """Create sandboxes that run as E2b's default user (commands, code and files default to its home)."""
2
-
3
- from __future__ import annotations
4
-
5
- import re
6
- import warnings
7
- from typing import Any
8
-
9
- from solari_core.errors import GatewayError
10
-
11
- VENDOR_USER = "user"
12
- VENDOR_HOME = "/home/user"
13
-
14
-
15
- def _refuses_user_fields(e: BaseException) -> bool:
16
- return isinstance(e, GatewayError) and e.status == 400 and re.search(r"\b(user|cwd)\b", repr(getattr(e, "body", None)), re.I) is not None
17
-
18
-
19
- def _warn_root() -> None:
20
- warnings.warn(
21
- "solari-e2b-compat: the server or this template's image predates user support, so the sandbox runs as root instead of 'user'. "
22
- "Rebuild templates and snapshots made before user support shipped to get the vendor user.",
23
- RuntimeWarning,
24
- stacklevel=4,
25
- )
26
-
27
-
28
- async def create_as_vendor_user(solari: Any, **opts: Any) -> Any:
29
- """``solari.create(**opts)`` with ``user`` / ``cwd`` set to E2b's defaults. A gateway that predates them (it answers 400
30
- naming them) gets the plain create, and the sandbox runs as root there (COMPAT.md). Restores from a snapshot keep the
31
- snapshot's own user and are sent without them."""
32
- if opts.get("from_snapshot") is not None:
33
- return await solari.create(**opts)
34
- try:
35
- return await solari.create(**opts, user=VENDOR_USER, cwd=VENDOR_HOME)
36
- except GatewayError as e:
37
- if not _refuses_user_fields(e):
38
- raise
39
- _warn_root()
40
- return await solari.create(**opts)