solari-e2b-compat 0.2.0__tar.gz → 0.2.1__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.
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/COMPAT.md +18 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/LICENSE +1 -1
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/PKG-INFO +2 -2
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/pyproject.toml +2 -2
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/__init__.py +1 -1
- solari_e2b_compat-0.2.1/solari_e2b/_redact.py +12 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_sandbox.py +18 -5
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_sync.py +38 -2
- solari_e2b_compat-0.2.1/solari_e2b/_vendor_user.py +29 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/code_interpreter.py +134 -8
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/exceptions.py +4 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/.gitignore +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/LICENSE-E2B +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/NOTICE +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/README.md +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_box.py +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_commands.py +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_config.py +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_filesystem.py +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_loop.py +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/_template.py +0 -0
- {solari_e2b_compat-0.2.0 → solari_e2b_compat-0.2.1}/solari_e2b/models.py +0 -0
|
@@ -96,3 +96,21 @@ and the differences that are specific to Python.
|
|
|
96
96
|
- The blocking API runs the async client on one daemon thread. Calling it from one of your own callbacks (which run on that
|
|
97
97
|
thread) raises `RuntimeError`; use `AsyncSandbox` there.
|
|
98
98
|
- Tested on Python 3.14; the code avoids syntax newer than 3.9 but only 3.14 is exercised here.
|
|
99
|
+
|
|
100
|
+
## Default user and home directory (matching E2B)
|
|
101
|
+
**Today's sandboxes run as `root` in `/home/root`. E2B's own run as `user` in `/home/user`; this arrives with a Solari server update, and this package already asks for it** (below).
|
|
102
|
+
|
|
103
|
+
Once the gateway supports it, E2B sandboxes run as `user` in `/home/user`; commands, code and files all start there, and relative paths resolve against it. This package
|
|
104
|
+
asks the gateway for exactly that at create time (`user: "user"`, `cwd: "/home/user"`; the gateway creates the user at first boot with passwordless
|
|
105
|
+
sudo). Restores from a snapshot keep the snapshot's own user.
|
|
106
|
+
- **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
|
|
107
|
+
`/home/root`**, which is what this package did before. Check `whoami` if code depends on it.
|
|
108
|
+
- 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.
|
|
109
|
+
|
|
110
|
+
## Snapshots, results and listing (0.2.1)
|
|
111
|
+
- 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.
|
|
112
|
+
- Blocking API: `Sandbox.list_snapshots()` (no arguments, or `sandbox_id=`) and `sandbox.list_snapshots()` return a paginator you page with `next_items()`;
|
|
113
|
+
`files.watch_dir(path, user=None, request_timeout=None, recursive=False)` has the sync signature (no `on_event`) and returns a handle whose
|
|
114
|
+
`get_new_events()` returns what arrived since the last call and `stop()` ends the watch.
|
|
115
|
+
- `run_code`: `logs.stdout` / `logs.stderr` hold one entry per line; an HTML-only DataFrame result also gets `text`; a PNG figure also gets `chart`
|
|
116
|
+
(same rules as the TypeScript package; the kernel snippets are kept identical by a test). Error messages carry only 8 characters of a sandbox id.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: solari-e2b-compat
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -11,7 +11,7 @@ License-File: NOTICE
|
|
|
11
11
|
Keywords: code-interpreter,compatibility,e2b,sandbox,solari
|
|
12
12
|
Requires-Python: >=3.9
|
|
13
13
|
Requires-Dist: solari-core>=0.4.0
|
|
14
|
-
Requires-Dist: solari-sandbox>=0.
|
|
14
|
+
Requires-Dist: solari-sandbox>=0.6.1
|
|
15
15
|
Provides-Extra: test
|
|
16
16
|
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
|
|
17
17
|
Requires-Dist: pytest>=7; extra == 'test'
|
|
@@ -4,14 +4,14 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "solari-e2b-compat"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.1"
|
|
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"
|
|
11
11
|
license = { text = "MIT" }
|
|
12
12
|
authors = [{ name = "Solari" }]
|
|
13
13
|
keywords = ["solari", "sandbox", "e2b", "code-interpreter", "compatibility"]
|
|
14
|
-
dependencies = ["solari-sandbox>=0.
|
|
14
|
+
dependencies = ["solari-sandbox>=0.6.1", "solari-core>=0.4.0"]
|
|
15
15
|
|
|
16
16
|
[project.optional-dependencies]
|
|
17
17
|
test = ["pytest>=7", "pytest-asyncio>=0.23"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Sandbox ids are `<payload>.<signature>` (base64url, about 195 characters) and work as credentials: error messages
|
|
2
|
+
carry the first 8 characters only (the same rule as the TypeScript packages and core's close() warning)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
_ID_RE = re.compile(r"[A-Za-z0-9_-]{60,}\.[A-Za-z0-9_-]{30,}")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def redact_ids(text: str) -> str:
|
|
12
|
+
return _ID_RE.sub(lambda m: m.group(0)[:8] + "…", text)
|
|
@@ -15,6 +15,7 @@ from ._commands import AsyncCommands, AsyncPty
|
|
|
15
15
|
from ._config import Conn, resolve_conn, split_opts
|
|
16
16
|
from ._filesystem import AsyncFilesystem
|
|
17
17
|
from ._template import resolve_template_id
|
|
18
|
+
from ._vendor_user import create_as_vendor_user
|
|
18
19
|
from .exceptions import (
|
|
19
20
|
InvalidArgumentException,
|
|
20
21
|
SandboxException,
|
|
@@ -197,6 +198,16 @@ class AsyncSnapshotPaginator(_Paginator):
|
|
|
197
198
|
return items
|
|
198
199
|
|
|
199
200
|
|
|
201
|
+
class _ListSnapshots:
|
|
202
|
+
"""E2B's ``Sandbox.list_snapshots(sandbox_id=None, limit=None, next_token=None)`` (every snapshot, or one sandbox's)
|
|
203
|
+
and ``sandbox.list_snapshots(limit=None, next_token=None)``. Neither needs an event loop until a page is fetched."""
|
|
204
|
+
|
|
205
|
+
def __get__(self, obj: Any, owner: Any) -> Callable[..., AsyncSnapshotPaginator]:
|
|
206
|
+
if obj is not None:
|
|
207
|
+
return lambda limit=None, next_token=None, name=None, **opts: AsyncSnapshotPaginator(obj._sandbox_id, name, limit, next_token, **split_opts(opts)[0])
|
|
208
|
+
return lambda sandbox_id=None, limit=None, next_token=None, name=None, **opts: AsyncSnapshotPaginator(sandbox_id, name, limit, next_token, **split_opts(opts)[0])
|
|
209
|
+
|
|
210
|
+
|
|
200
211
|
class AsyncSandbox:
|
|
201
212
|
_default_template = "base"
|
|
202
213
|
|
|
@@ -264,9 +275,13 @@ class AsyncSandbox:
|
|
|
264
275
|
conn = resolve_conn(**split_opts(opts)[0])
|
|
265
276
|
volumes = await _resolve_volumes(conn, volume_mounts) if volume_mounts else None
|
|
266
277
|
try:
|
|
267
|
-
|
|
268
|
-
|
|
278
|
+
# E2B's snapshot docs restore with ``Sandbox.create(snapshot.snapshot_id)``: a snap_ id is a restore, not a template.
|
|
279
|
+
restore = (template or "").startswith("snap_")
|
|
280
|
+
template_id = None if restore else await cls._resolve_template(conn, template or cls._default_template)
|
|
281
|
+
core = await create_as_vendor_user(
|
|
282
|
+
conn.solari,
|
|
269
283
|
template=template_id,
|
|
284
|
+
from_snapshot=template if restore else None,
|
|
270
285
|
envs=envs or None,
|
|
271
286
|
metadata=metadata or None,
|
|
272
287
|
# E2B's timeout is a lifetime; Solari's is a rolling idle window (COMPAT.md).
|
|
@@ -391,9 +406,7 @@ class AsyncSandbox:
|
|
|
391
406
|
sid = await self._box.on(lambda sb: sb.snapshot(name), "sandbox")
|
|
392
407
|
return SnapshotInfo(snapshot_id=sid, names=[name] if name else [])
|
|
393
408
|
|
|
394
|
-
|
|
395
|
-
def list_snapshots(self, limit: Optional[int] = None, next_token: Optional[str] = None, name: Optional[str] = None, **opts: Any) -> AsyncSnapshotPaginator:
|
|
396
|
-
return AsyncSnapshotPaginator(self._sandbox_id, name, limit, next_token, **split_opts(opts)[0])
|
|
409
|
+
list_snapshots = _ListSnapshots()
|
|
397
410
|
|
|
398
411
|
@classmethod
|
|
399
412
|
def list_all_snapshots(cls, limit: Optional[int] = None, next_token: Optional[str] = None, name: Optional[str] = None, **opts: Any) -> AsyncSnapshotPaginator:
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import inspect
|
|
6
|
-
from typing import Any, Callable, Dict, Optional, Tuple
|
|
6
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
7
7
|
|
|
8
8
|
from ._commands import AsyncCommandHandle, AsyncCommandInputHandle, AsyncCommands, AsyncPty
|
|
9
9
|
from ._filesystem import AsyncFilesystem, AsyncWatchHandle
|
|
@@ -40,7 +40,34 @@ class SyncProxy:
|
|
|
40
40
|
raise TypeError(f"{type(self._t).__name__} is not iterable")
|
|
41
41
|
|
|
42
42
|
|
|
43
|
+
class WatchHandle:
|
|
44
|
+
"""E2B's synchronous watch handle: ``get_new_events()`` returns the events that arrived since the last call."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, handle: Any, events: List[Any]) -> None:
|
|
47
|
+
self._h = handle
|
|
48
|
+
self._events = events
|
|
49
|
+
|
|
50
|
+
def stop(self) -> None:
|
|
51
|
+
LOOP.run(self._h.stop())
|
|
52
|
+
|
|
53
|
+
def get_new_events(self) -> List[Any]:
|
|
54
|
+
out, self._events[:] = list(self._events), []
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SyncFilesystem(SyncProxy):
|
|
59
|
+
"""E2B's synchronous ``files``: ``watch_dir(path, user=None, request_timeout=None, recursive=False)`` returns a
|
|
60
|
+
:class:`WatchHandle` to poll (there is no ``on_event`` callback in the sync API)."""
|
|
61
|
+
|
|
62
|
+
def watch_dir(self, path: str, user: Optional[str] = None, request_timeout: Optional[float] = None, recursive: bool = False) -> WatchHandle:
|
|
63
|
+
events: List[Any] = []
|
|
64
|
+
handle = LOOP.run(self._t.watch_dir(path, events.append, None, user, request_timeout, 0, recursive))
|
|
65
|
+
return WatchHandle(handle, events)
|
|
66
|
+
|
|
67
|
+
|
|
43
68
|
def wrap(v: Any) -> Any:
|
|
69
|
+
if isinstance(v, AsyncFilesystem):
|
|
70
|
+
return SyncFilesystem(v)
|
|
44
71
|
if isinstance(v, _WRAPPED):
|
|
45
72
|
return SyncProxy(v)
|
|
46
73
|
if isinstance(v, list):
|
|
@@ -67,6 +94,15 @@ def _blocking(f: Callable[..., Any], owner: Any) -> Callable[..., Any]:
|
|
|
67
94
|
return lambda *a, **k: owner._wrap(f(*a, **k))
|
|
68
95
|
|
|
69
96
|
|
|
97
|
+
class _SyncListSnapshots:
|
|
98
|
+
"""``Sandbox.list_snapshots(sandbox_id=None, limit=None, next_token=None)`` and ``sandbox.list_snapshots(limit=None, next_token=None)``."""
|
|
99
|
+
|
|
100
|
+
def __get__(self, obj: Any, owner: Any) -> Callable[..., Any]:
|
|
101
|
+
if obj is not None:
|
|
102
|
+
return lambda *a, **k: wrap(obj._a.list_snapshots(*a, **k))
|
|
103
|
+
return lambda *a, **k: wrap(owner._async_cls.list_snapshots(*a, **k))
|
|
104
|
+
|
|
105
|
+
|
|
70
106
|
class Sandbox:
|
|
71
107
|
"""E2B's synchronous ``Sandbox``."""
|
|
72
108
|
|
|
@@ -137,7 +173,7 @@ class Sandbox:
|
|
|
137
173
|
get_metrics = _SyncHybrid("get_metrics")
|
|
138
174
|
pause = _SyncHybrid("pause")
|
|
139
175
|
create_snapshot = _SyncHybrid("create_snapshot")
|
|
140
|
-
list_snapshots =
|
|
176
|
+
list_snapshots = _SyncListSnapshots()
|
|
141
177
|
fork = _SyncHybrid("fork")
|
|
142
178
|
update_network = _SyncHybrid("update_network")
|
|
143
179
|
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from solari_core.errors import GatewayError
|
|
9
|
+
|
|
10
|
+
VENDOR_USER = "user"
|
|
11
|
+
VENDOR_HOME = "/home/user"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _refuses_user_fields(e: BaseException) -> bool:
|
|
15
|
+
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
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def create_as_vendor_user(solari: Any, **opts: Any) -> Any:
|
|
19
|
+
"""``solari.create(**opts)`` with ``user`` / ``cwd`` set to E2b's defaults. A gateway that predates them (it answers 400
|
|
20
|
+
naming them) gets the plain create, and the sandbox runs as root there (COMPAT.md). Restores from a snapshot keep the
|
|
21
|
+
snapshot's own user and are sent without them."""
|
|
22
|
+
if opts.get("from_snapshot") is not None:
|
|
23
|
+
return await solari.create(**opts)
|
|
24
|
+
try:
|
|
25
|
+
return await solari.create(**opts, user=VENDOR_USER, cwd=VENDOR_HOME)
|
|
26
|
+
except GatewayError as e:
|
|
27
|
+
if not _refuses_user_fields(e):
|
|
28
|
+
raise
|
|
29
|
+
return await solari.create(**opts)
|
|
@@ -151,6 +151,106 @@ class Context:
|
|
|
151
151
|
return f"Context(id={self.id!r}, language={self.language!r}, cwd={self.cwd!r})"
|
|
152
152
|
|
|
153
153
|
|
|
154
|
+
# --- kernel output shaping (mirrors @solarisdk/e2b-compat) ------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
# The guest kernel sends a drawn figure as a PNG only (and closes it right after the cell), while E2B results also carry a
|
|
157
|
+
# structured ``chart``. This cell wraps matplotlib's PNG rendering so each rendered figure also records its chart; the
|
|
158
|
+
# recording is read back with CHART_READ after the user's code. Installed once per kernel, only for plotting code.
|
|
159
|
+
# (Identical to CHART_HOOK / CHART_READ in packages/e2b-compat/src/code-interpreter.ts; a test keeps them in step.)
|
|
160
|
+
CHART_HOOK = """
|
|
161
|
+
if "__solari_chart_hook_installed" not in globals():
|
|
162
|
+
def __solari_chart_hook():
|
|
163
|
+
import sys
|
|
164
|
+
def axis(ax, which):
|
|
165
|
+
try:
|
|
166
|
+
ticks = [t.item() if hasattr(t, "item") else t for t in getattr(ax, "get_%sticks" % which)()]
|
|
167
|
+
except Exception:
|
|
168
|
+
ticks = []
|
|
169
|
+
return {"label": getattr(ax, "get_%slabel" % which)() or None, "ticks": ticks, "scale": getattr(ax, "get_%sscale" % which)()}
|
|
170
|
+
def one(ax):
|
|
171
|
+
elements, kinds = [], set()
|
|
172
|
+
for line in ax.get_lines():
|
|
173
|
+
label = line.get_label()
|
|
174
|
+
pts = []
|
|
175
|
+
for x, y in zip(line.get_xdata(), line.get_ydata()):
|
|
176
|
+
pts.append([x if isinstance(x, str) else float(x), float(y)])
|
|
177
|
+
elements.append({"label": "" if label.startswith("_") else label, "points": pts})
|
|
178
|
+
kinds.add("line")
|
|
179
|
+
for col in ax.collections:
|
|
180
|
+
if type(col).__name__ == "PathCollection":
|
|
181
|
+
label = col.get_label()
|
|
182
|
+
elements.append({"label": "" if label.startswith("_") else label, "points": [[float(a), float(b)] for a, b in col.get_offsets()]})
|
|
183
|
+
kinds.add("scatter")
|
|
184
|
+
names = [t.get_text() for t in ax.get_xticklabels()]
|
|
185
|
+
for cont in ax.containers:
|
|
186
|
+
if type(cont).__name__ == "BarContainer":
|
|
187
|
+
glabel = cont.get_label()
|
|
188
|
+
for i, patch in enumerate(cont.patches):
|
|
189
|
+
name = names[i] if i < len(names) and names[i] else str(round(patch.get_x() + patch.get_width() / 2, 6))
|
|
190
|
+
elements.append({"label": name, "value": float(patch.get_height()), "group": "" if glabel.startswith("_") else glabel})
|
|
191
|
+
kinds.add("bar")
|
|
192
|
+
return {"type": kinds.pop() if len(kinds) == 1 else "unknown", "title": ax.get_title() or None, "xLabel": ax.get_xlabel() or None, "yLabel": ax.get_ylabel() or None, "x": axis(ax, "x"), "y": axis(ax, "y"), "elements": elements}
|
|
193
|
+
def chart_of(fig):
|
|
194
|
+
axes = [one(ax) for ax in fig.axes]
|
|
195
|
+
if len(axes) == 1:
|
|
196
|
+
return axes[0]
|
|
197
|
+
sup = getattr(fig, "_suptitle", None)
|
|
198
|
+
return {"type": "composite", "title": sup.get_text() if sup else None, "elements": axes}
|
|
199
|
+
try:
|
|
200
|
+
from matplotlib.backend_bases import FigureCanvasBase
|
|
201
|
+
except Exception:
|
|
202
|
+
return
|
|
203
|
+
original = FigureCanvasBase.print_figure
|
|
204
|
+
def print_figure(self, *args, **kwargs):
|
|
205
|
+
fmt = kwargs.get("format")
|
|
206
|
+
if fmt == "png" or (fmt is None and args and not isinstance(args[0], str)):
|
|
207
|
+
try:
|
|
208
|
+
globals().setdefault("__solari_fig_charts", []).append(chart_of(self.figure))
|
|
209
|
+
except Exception:
|
|
210
|
+
pass
|
|
211
|
+
return original(self, *args, **kwargs)
|
|
212
|
+
FigureCanvasBase.print_figure = print_figure
|
|
213
|
+
__solari_chart_hook()
|
|
214
|
+
__solari_chart_hook_installed = True
|
|
215
|
+
"""
|
|
216
|
+
CHART_READ = """
|
|
217
|
+
import json as __solari_json
|
|
218
|
+
print("__SOLARI_CHARTS__" + __solari_json.dumps(globals().pop("__solari_fig_charts", []), default=str))
|
|
219
|
+
del __solari_json
|
|
220
|
+
"""
|
|
221
|
+
_PLOTTING = re.compile(r"matplotlib|pyplot|\bplt\b|seaborn|\bsns\b|\bfigure\b|\.plot\(|\bsubplots?\b")
|
|
222
|
+
_ENTITIES = (("<", "<"), (">", ">"), (""", '"'), ("'", "'"), (" ", " "), ("&", "&"))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def per_line(text: str) -> List[str]:
|
|
226
|
+
"""One entry per line, newline kept, as E2B delivers kernel output (one message per print)."""
|
|
227
|
+
return re.findall(r"[^\n]*\n|[^\n]+$", text)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _unescape(s: str) -> str:
|
|
231
|
+
for a, b in _ENTITIES:
|
|
232
|
+
s = s.replace(a, b)
|
|
233
|
+
return s
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def text_from_html_table(html: str) -> Optional[str]:
|
|
237
|
+
"""Plain text for a result that only has HTML (a pandas DataFrame renders as a <table>): E2B's ``text`` is the DataFrame
|
|
238
|
+
repr and agents read ``execution.text``. Rebuilds a pandas-style aligned table; other HTML returns None."""
|
|
239
|
+
if not re.search(r"<table[\s>]", html, re.I):
|
|
240
|
+
return None
|
|
241
|
+
rows = [
|
|
242
|
+
[_unescape(re.sub(r"<[^>]+>", "", c)).strip() for c in re.findall(r"<t[hd][^>]*>([\s\S]*?)</t[hd]>", r, re.I)]
|
|
243
|
+
for r in re.findall(r"<tr[^>]*>([\s\S]*?)</tr>", html, re.I)
|
|
244
|
+
]
|
|
245
|
+
body = [r for r in rows if r]
|
|
246
|
+
if not body:
|
|
247
|
+
return None
|
|
248
|
+
width = max(len(r) for r in body)
|
|
249
|
+
grid = [r + [""] * (width - len(r)) for r in body]
|
|
250
|
+
w = [max(len(r[i]) for r in grid) for i in range(width)]
|
|
251
|
+
return "\n".join((" ".join(c.ljust(w[i]) if i == 0 else c.rjust(w[i]) for i, c in enumerate(r))).rstrip() for r in grid)
|
|
252
|
+
|
|
253
|
+
|
|
154
254
|
# --- mapping from Solari results --------------------------------------------------------------------------------------
|
|
155
255
|
|
|
156
256
|
_CHART_TYPES = {"line", "scatter", "bar", "pie", "box_and_whisker"}
|
|
@@ -177,11 +277,14 @@ def map_chart(c: Any) -> Chart:
|
|
|
177
277
|
return Chart(type=typ, title=d.get("title") or "", elements=list(d.get("elements") or []), extra=extra)
|
|
178
278
|
|
|
179
279
|
|
|
180
|
-
def to_result(item: Any, is_main: bool) -> Result:
|
|
280
|
+
def to_result(item: Any, is_main: bool, chart: Any = None) -> Result:
|
|
181
281
|
g = (lambda k: item.get(k)) if isinstance(item, dict) else (lambda k: getattr(item, k, None))
|
|
182
|
-
chart = g("chart")
|
|
282
|
+
chart = chart or g("chart")
|
|
283
|
+
text = g("text")
|
|
284
|
+
if text is None and g("html") is not None:
|
|
285
|
+
text = text_from_html_table(g("html"))
|
|
183
286
|
return Result(
|
|
184
|
-
text=
|
|
287
|
+
text=text, html=g("html"), markdown=g("markdown"), svg=g("svg"), png=g("png"), jpeg=g("jpeg"), latex=g("latex"),
|
|
185
288
|
json=g("json"), chart=map_chart(chart) if chart else None, is_main_result=is_main,
|
|
186
289
|
) # fmt: skip
|
|
187
290
|
|
|
@@ -294,21 +397,44 @@ class AsyncSandbox(_AsyncBase):
|
|
|
294
397
|
async def _run_python(self, code: str, language: str, context: Optional[Context]) -> Execution:
|
|
295
398
|
if language not in _PY:
|
|
296
399
|
raise SolariCompatUnsupported(f'run_code language "{language}"', "the Solari guest ships a Python kernel (and bash through language='bash')")
|
|
297
|
-
|
|
400
|
+
cid = context.id if context else None
|
|
401
|
+
plotting = bool(_PLOTTING.search(code))
|
|
402
|
+
if plotting:
|
|
403
|
+
try:
|
|
404
|
+
await self._box.on(lambda sb: sb.run_code(CHART_HOOK, language="python", context_id=cid))
|
|
405
|
+
except Exception: # noqa: BLE001
|
|
406
|
+
pass
|
|
407
|
+
r = await self._box.on(lambda sb: sb.run_code(code, language="python", context_id=cid))
|
|
298
408
|
stdout: List[str] = []
|
|
299
409
|
stderr: List[str] = []
|
|
300
410
|
items: List[Any] = []
|
|
301
411
|
for it in r.results:
|
|
302
412
|
if it.type == "stdout":
|
|
303
413
|
if it.text:
|
|
304
|
-
stdout.
|
|
414
|
+
stdout.extend(per_line(it.text))
|
|
305
415
|
elif it.type == "stderr":
|
|
306
416
|
if it.text:
|
|
307
|
-
stderr.
|
|
417
|
+
stderr.extend(per_line(it.text))
|
|
308
418
|
else:
|
|
309
419
|
items.append(it)
|
|
310
|
-
|
|
311
|
-
|
|
420
|
+
# Figures arrive as a PNG only; E2B also sends the structured chart, which the hook above recorded.
|
|
421
|
+
charts: Dict[int, Any] = {}
|
|
422
|
+
if plotting:
|
|
423
|
+
try:
|
|
424
|
+
c = await self._box.on(lambda sb: sb.run_code(CHART_READ, language="python", context_id=cid))
|
|
425
|
+
line = next((x.text for x in c.results if x.type == "stdout" and x.text and "__SOLARI_CHARTS__" in x.text), "")
|
|
426
|
+
found = json.loads(line[line.index("__SOLARI_CHARTS__") + len("__SOLARI_CHARTS__"):])
|
|
427
|
+
bare = [n for n, i in enumerate(items) if getattr(i, "png", None) is not None and not getattr(i, "chart", None)]
|
|
428
|
+
if len(found) == len(bare):
|
|
429
|
+
charts = dict(zip(bare, found))
|
|
430
|
+
except Exception: # noqa: BLE001 - the PNG alone is still a usable result
|
|
431
|
+
charts = {}
|
|
432
|
+
|
|
433
|
+
def has_text(i: Any) -> bool:
|
|
434
|
+
return i.text is not None or (getattr(i, "html", None) is not None and text_from_html_table(i.html) is not None)
|
|
435
|
+
|
|
436
|
+
last_text = max((n for n, i in enumerate(items) if has_text(i)), default=-1)
|
|
437
|
+
results = [to_result(it, n == last_text, charts.get(n)) for n, it in enumerate(items)]
|
|
312
438
|
return Execution(results, Logs(stdout, stderr), to_execution_error(r.error) if r.error is not None else None)
|
|
313
439
|
|
|
314
440
|
async def _run_bash(self, code: str) -> Execution:
|
|
@@ -7,6 +7,7 @@ import re
|
|
|
7
7
|
from dataclasses import dataclass
|
|
8
8
|
from typing import Any, Optional
|
|
9
9
|
|
|
10
|
+
from ._redact import redact_ids
|
|
10
11
|
from solari_core.errors import (
|
|
11
12
|
ActionError,
|
|
12
13
|
ConnectionError as _SolariConnectionError,
|
|
@@ -19,6 +20,9 @@ from solari_core.errors import (
|
|
|
19
20
|
class SandboxException(Exception):
|
|
20
21
|
"""Base class for sandbox errors."""
|
|
21
22
|
|
|
23
|
+
def __init__(self, *args: object) -> None:
|
|
24
|
+
super().__init__(*(redact_ids(a) if isinstance(a, str) else a for a in args))
|
|
25
|
+
|
|
22
26
|
|
|
23
27
|
class TimeoutException(SandboxException): ...
|
|
24
28
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|