solari-e2b-compat 0.2.10__tar.gz → 0.2.12__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 (32) hide show
  1. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/.gitignore +7 -0
  2. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/COMPAT.md +5 -3
  3. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/PKG-INFO +1 -1
  4. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/pyproject.toml +1 -1
  5. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/__init__.py +1 -1
  6. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_commands.py +48 -1
  7. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_filesystem.py +12 -0
  8. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/__init__.py +52 -14
  9. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/LICENSE +0 -0
  10. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/LICENSE-E2B +0 -0
  11. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/NOTICE +0 -0
  12. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/README.md +0 -0
  13. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_box.py +0 -0
  14. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_config.py +0 -0
  15. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_git.py +0 -0
  16. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_loop.py +0 -0
  17. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_redact.py +0 -0
  18. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_request.py +0 -0
  19. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_sandbox.py +0 -0
  20. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_sync.py +0 -0
  21. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_template.py +0 -0
  22. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_vendor_user.py +0 -0
  23. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/_volume.py +0 -0
  24. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/charts.py +0 -0
  25. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/client.py +0 -0
  26. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/code_interpreter_async.py +0 -0
  27. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/code_interpreter_sync.py +0 -0
  28. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/constants.py +0 -0
  29. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/exceptions.py +0 -0
  30. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/code_interpreter/models.py +0 -0
  31. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/exceptions.py +0 -0
  32. {solari_e2b_compat-0.2.10 → solari_e2b_compat-0.2.12}/solari_e2b/models.py +0 -0
@@ -70,3 +70,10 @@ infra/terraform/snapshots-volumes/.build/
70
70
  # (ASIA... + X-Amz-Security-Token). Never commit. Also stale PHASE_* here makes
71
71
  # a bare re-run skip bake+verify and exit 0 with zero assertions.
72
72
  infra/.deploy-e2e/
73
+
74
+ # Local Cloud Hypervisor fork checkout (patch series lives in patches/cloud-hypervisor-v43)
75
+ third_party/cloud-hypervisor/
76
+
77
+ # Build outputs accidentally committed on perf branches (excluded by staging/bare-metal-int)
78
+ /host-agent/host-agent
79
+ /bench/step-park/microbench
@@ -76,6 +76,7 @@ and the differences that are specific to Python.
76
76
  |---|---|---|
77
77
  | `read(path, format='text' \| 'bytes' \| 'stream')` | OK, live | Relative paths resolve against the guest's `$HOME` and every path is normalised (no `.`, `..` or doubled slashes; `files.list('.')` entries are `/home/user/x`, not `/home/user/./x`). `bytes` returns a `bytearray`. `stream` returns a reader with one chunk: async-iterable in the async API, a plain iterator of `bytes` in the blocking API. A missing file raises `FileNotFoundException`. |
78
78
  | `write(path, data)`, `write_files(entries)` | OK, live | `str`, `bytes` or a file-like object. Parent directories are created. `metadata=`: NO. `gzip`, `use_octet_stream`: how E2B encodes the HTTP upload; Solari writes over its control channel, so they change nothing (the file is the same). Likewise `read(gzip=, stream_idle_timeout=)`. |
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`). |
79
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). |
80
81
  | `exists`, `make_dir`, `rename`, `remove` | OK, live | |
81
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()`. |
@@ -88,12 +89,13 @@ and the differences that are specific to Python.
88
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. |
89
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. |
90
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). |
91
- | `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. |
92
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`. |
93
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). |
94
96
  | `envs=` per run | NO | |
95
97
  | `timeout=` | DIFF | Stops waiting and raises `TimeoutException`; the kernel keeps running the code. No default timeout (E2B's is 300 s). |
96
- | `create_code_context(cwd, language)` | OK, live | Python only. |
98
+ | `create_code_context(cwd, language)` | OK, live | Python only. A `cwd` that cannot be entered raises `InvalidArgumentException` (it used to leave the context in `$HOME` silently). |
97
99
  | `list_code_contexts`, `remove_code_context`, `restart_code_context` | DIFF, live | Solari cannot list or destroy kernels. `list` returns contexts created by this process; `remove` forgets the context (the kernel stays until the sandbox ends); `restart` clears the context's variables and working directory without restarting the process. |
98
100
  | Default template | DIFF | `code-interpreter-v2` is built into your org on first `Sandbox.create()` without a template: about 90 seconds (two timed builds on 2026-11-07 took 92 s and 95 s), billed as a template build, and two processes that both find it missing each start a build. `build_code_interpreter_template()` (async) / `build_code_interpreter_template_sync()` prebuild it. |
99
101
 
@@ -131,7 +133,7 @@ sudo). Restores from a snapshot keep the snapshot's own user.
131
133
  - **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
132
134
  `/home/root`**, which is what this package did before. Check `whoami` if code depends on it.
133
135
  - **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.
134
- - 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.
136
+ - 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.
135
137
 
136
138
  ## Snapshots, results and listing (0.2.1)
137
139
  - 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.10
3
+ Version: 0.2.12
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.10"
7
+ version = "0.2.12"
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"
@@ -76,4 +76,4 @@ class _UnsupportedModule:
76
76
 
77
77
  client = _UnsupportedModule()
78
78
 
79
- __version__ = "0.2.10"
79
+ __version__ = "0.2.12"
@@ -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.
@@ -8,6 +8,8 @@ import io
8
8
  from datetime import datetime, timezone
9
9
  from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Union
10
10
 
11
+ from solari_core.handle import MAX_SINGLE_CALL_BYTES
12
+
11
13
  from ._box import Box, fire
12
14
  from ._request import bounded
13
15
  from .exceptions import FileNotFoundException, InvalidArgumentException, SolariCompatUnsupported
@@ -44,6 +46,13 @@ exit 0
44
46
  """
45
47
 
46
48
 
49
+ def too_large_message(n: int) -> str:
50
+ return (
51
+ f"file too large for one files.write call ({n} bytes, max {MAX_SINGLE_CALL_BYTES}): "
52
+ "get a signed URL with sandbox.upload_url(path) and PUT the bytes to it, or write the file in parts"
53
+ )
54
+
55
+
47
56
  class _Meta:
48
57
  """What the shell helper learned about one path."""
49
58
 
@@ -206,6 +215,9 @@ class AsyncFilesystem:
206
215
  _reject(user, "files.write", metadata)
207
216
  abs_ = await self._box.abs(path)
208
217
  raw = _to_bytes(data)
218
+ # Core's own message points at files.upload(), which the E2B API does not have; E2B callers have upload_url().
219
+ if len(raw) > MAX_SINGLE_CALL_BYTES:
220
+ raise InvalidArgumentException(too_large_message(len(raw)))
209
221
 
210
222
  async def _w(sb: Any) -> None:
211
223
  # E2B creates missing parent directories.
@@ -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))
@@ -555,7 +588,12 @@ class AsyncSandbox(_AsyncBase):
555
588
  async def make() -> Context:
556
589
  cid = await self._box.on(lambda sb: sb.create_code_context("python"))
557
590
  if cwd:
558
- await self._box.on(lambda sb: sb.run_code(f"import os\nos.chdir({json.dumps(cwd)})\n", language="python", context_id=cid))
591
+ # run_code reports a failed chdir in ``error`` (it does not raise); without this check a bad cwd silently left the context in $HOME.
592
+ r = await self._box.on(lambda sb: sb.run_code(f"import os\nos.chdir({json.dumps(cwd)})\n", language="python", context_id=cid))
593
+ if r.error:
594
+ msg = r.error if isinstance(r.error, str) else getattr(r.error, "message", None) or getattr(r.error, "name", None) or str(r.error)
595
+ msg = ([ln for ln in str(msg).splitlines() if ln.strip()] or [str(msg)])[-1].strip() # a traceback: its last line names the error
596
+ raise InvalidArgumentException(f"create_code_context: cwd {json.dumps(cwd)} cannot be used: {msg}")
559
597
  ctx = Context(cid, "python", cwd or await self._box.home())
560
598
  _ctx_of(self.sandbox_id)[cid] = ctx
561
599
  return ctx