Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(copilot): E2B sandbox auto-pause between turns to eliminate idle billing (#12330)

Zamil Majdyaef5f6d66627
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 1310622b87..10279e1a76 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -28,6 +28,7 @@ from backend.copilot.model import (
update_session_title,
)
from backend.copilot.response_model import StreamError, StreamFinish, StreamHeartbeat
+from backend.copilot.tools.e2b_sandbox import kill_sandbox
from backend.copilot.tools.models import (
AgentDetailsResponse,
AgentOutputResponse,
@@ -265,12 +266,12 @@ async def delete_session(
)
# Best-effort cleanup of the E2B sandbox (if any).
- config = ChatConfig()
- if config.use_e2b_sandbox and config.e2b_api_key:
- from backend.copilot.tools.e2b_sandbox import kill_sandbox
-
+ # sandbox_id is in Redis; kill_sandbox() fetches it from there.
+ e2b_cfg = ChatConfig()
+ if e2b_cfg.e2b_active:
+ assert e2b_cfg.e2b_api_key # guaranteed by e2b_active check
try:
- await kill_sandbox(session_id, config.e2b_api_key)
+ await kill_sandbox(session_id, e2b_cfg.e2b_api_key)
except Exception:
logger.warning(
"[E2B] Failed to kill sandbox for session %s", session_id[:12]
diff --git a/autogpt_platform/backend/backend/blocks/code_executor.py b/autogpt_platform/backend/backend/blocks/code_executor.py
index 26bf9acd4f..3230a30996 100644
--- a/autogpt_platform/backend/backend/blocks/code_executor.py
+++ b/autogpt_platform/backend/backend/blocks/code_executor.py
@@ -142,7 +142,7 @@ class BaseE2BExecutorMixin:
start_timestamp = ts_result.stdout.strip() if ts_result.stdout else None
# Execute the code
- execution = await sandbox.run_code(
+ execution = await sandbox.run_code( # type: ignore[attr-defined]
code,
language=language.value,
on_error=lambda e: sandbox.kill(), # Kill the sandbox on error
diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.py
index 401875be2d..d4b0df2d59 100644
--- a/autogpt_platform/backend/backend/copilot/config.py
+++ b/autogpt_platform/backend/backend/copilot/config.py
@@ -1,6 +1,7 @@
"""Configuration management for chat system."""
import os
+from typing import Literal
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings
@@ -112,9 +113,37 @@ class ChatConfig(BaseSettings):
description="E2B sandbox template to use for copilot sessions.",
)
e2b_sandbox_timeout: int = Field(
- default=43200, # 12 hours — same as session_ttl
- description="E2B sandbox keepalive timeout in seconds.",
+ default=10800, # 3 hours — wall-clock timeout, not idle; explicit pause is primary
+ description="E2B sandbox running-time timeout (seconds). "
+ "E2B timeout is wall-clock (not idle). Explicit per-turn pause is the primary "
+ "mechanism; this is the safety net.",
)
+ e2b_sandbox_on_timeout: Literal["kill", "pause"] = Field(
+ default="pause",
+ description="E2B lifecycle action on timeout: 'pause' (default, free) or 'kill'.",
+ )
+
+ @property
+ def e2b_active(self) -> bool:
+ """True when E2B is enabled and the API key is present.
+
+ Single source of truth for "should we use E2B right now?".
+ Prefer this over combining ``use_e2b_sandbox`` and ``e2b_api_key``
+ separately at call sites.
+ """
+ return self.use_e2b_sandbox and bool(self.e2b_api_key)
+
+ @property
+ def active_e2b_api_key(self) -> str | None:
+ """Return the E2B API key when E2B is enabled and configured, else None.
+
+ Combines the ``use_e2b_sandbox`` flag check and key presence into one.
+ Use in callers::
+
+ if api_key := config.active_e2b_api_key:
+ # E2B is active; api_key is narrowed to str
+ """
+ return self.e2b_api_key if self.e2b_active else None
@field_validator("use_e2b_sandbox", mode="before")
@classmethod
diff --git a/autogpt_platform/backend/backend/copilot/config_test.py b/autogpt_platform/backend/backend/copilot/config_test.py
new file mode 100644
index 0000000000..2f52c5329c
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/config_test.py
@@ -0,0 +1,22 @@
+"""Unit tests for ChatConfig."""
+
+from .config import ChatConfig
+
+
+class TestE2BActive:
+ """Tests for the e2b_active property — single source of truth for E2B usage."""
+
+ def test_both_enabled_and_key_present_returns_true(self):
+ """e2b_active is True when use_e2b_sandbox=True and e2b_api_key is set."""
+ cfg = ChatConfig(use_e2b_sandbox=True, e2b_api_key="test-key")
+ assert cfg.e2b_active is True
+
+ def test_enabled_but_missing_key_returns_false(self):
+ """e2b_active is False when use_e2b_sandbox=True but e2b_api_key is absent."""
+ cfg = ChatConfig(use_e2b_sandbox=True, e2b_api_key=None)
+ assert cfg.e2b_active is False
+
+ def test_disabled_returns_false(self):
+ """e2b_active is False when use_e2b_sandbox=False regardless of key."""
+ cfg = ChatConfig(use_e2b_sandbox=False, e2b_api_key="test-key")
+ assert cfg.e2b_active is False
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index cf4326c9ab..bfd2262ee2 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -60,7 +60,7 @@ from ..service import (
_generate_session_title,
_is_langfuse_configured,
)
-from ..tools.e2b_sandbox import get_or_create_sandbox
+from ..tools.e2b_sandbox import get_or_create_sandbox, pause_sandbox_direct
from ..tools.sandbox import WORKSPACE_PREFIX, make_session_path
from ..tools.workspace_files import get_manager
from ..tracking import track_user_message
@@ -784,28 +784,29 @@ async def stream_chat_completion_sdk(
async def _setup_e2b():
"""Set up E2B sandbox if configured, return sandbox or None."""
- if config.use_e2b_sandbox and not config.e2b_api_key:
- logger.warning(
- "[E2B] [%s] E2B sandbox enabled but no API key configured "
- "(CHAT_E2B_API_KEY / E2B_API_KEY) — falling back to bubblewrap",
- session_id[:12],
- )
- return None
- if config.use_e2b_sandbox and config.e2b_api_key:
- try:
- return await get_or_create_sandbox(
- session_id,
- api_key=config.e2b_api_key,
- template=config.e2b_sandbox_template,
- timeout=config.e2b_sandbox_timeout,
- )
- except Exception as e2b_err:
- logger.error(
- "[E2B] [%s] Setup failed: %s",
+ if not (e2b_api_key := config.active_e2b_api_key):
+ if config.use_e2b_sandbox:
+ logger.warning(
+ "[E2B] [%s] E2B sandbox enabled but no API key configured "
+ "(CHAT_E2B_API_KEY / E2B_API_KEY) — falling back to bubblewrap",
session_id[:12],
- e2b_err,
- exc_info=True,
)
+ return None
+ try:
+ return await get_or_create_sandbox(
+ session_id,
+ api_key=e2b_api_key,
+ template=config.e2b_sandbox_template,
+ timeout=config.e2b_sandbox_timeout,
+ on_timeout=config.e2b_sandbox_on_timeout,
+ )
+ except Exception as e2b_err:
+ logger.error(
+ "[E2B] [%s] Setup failed: %s",
+ session_id[:12],
+ e2b_err,
+ exc_info=True,
+ )
return None
async def _fetch_transcript():
@@ -1416,6 +1417,17 @@ async def stream_chat_completion_sdk(
exc_info=True,
)
+ # --- Pause E2B sandbox to stop billing between turns ---
+ # Fire-and-forget: pausing is best-effort and must not block the
+ # response or the transcript upload. The task is anchored to
+ # _background_tasks to prevent garbage collection.
+ # Use pause_sandbox_direct to skip the Redis lookup and reconnect
+ # round-trip — e2b_sandbox is the live object from this turn.
+ if e2b_sandbox is not None:
+ task = asyncio.create_task(pause_sandbox_direct(e2b_sandbox, session_id))
+ _background_tasks.add(task)
+ task.add_done_callback(_background_tasks.discard)
+
# --- Upload transcript for next-turn --resume ---
# This MUST run in finally so the transcript is uploaded even when
# the streaming loop raises an exception.
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
index a0cda8aeab..143687b274 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
@@ -1,9 +1,10 @@
"""Tests for SDK service helpers."""
+import asyncio
import base64
import os
from dataclasses import dataclass
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -231,6 +232,48 @@ class TestPromptSupplement:
f"`{tool_name}`" in docs
), f"Tool '{tool_name}' missing from baseline supplement"
+ def test_pause_task_scheduled_before_transcript_upload(self):
+ """Pause is scheduled as a background task before transcript upload begins.
+
+ The finally block in stream_response_sdk does:
+ (1) asyncio.create_task(pause_sandbox_direct(...)) — fire-and-forget
+ (2) await asyncio.shield(upload_transcript(...)) — awaited
+
+ Scheduling pause via create_task before awaiting upload ensures:
+ - Pause never blocks transcript upload (billing stops concurrently)
+ - On E2B timeout, pause silently fails; upload proceeds unaffected
+ """
+ call_order: list[str] = []
+
+ async def _mock_pause(sandbox, session_id):
+ call_order.append("pause")
+
+ async def _mock_upload(**kwargs):
+ call_order.append("upload")
+
+ async def _simulate_teardown():
+ """Mirror the service.py finally block teardown sequence."""
+ sandbox = MagicMock()
+
+ # (1) Schedule pause — mirrors lines ~1427-1429 in service.py
+ task = asyncio.create_task(_mock_pause(sandbox, "test-sess"))
+
+ # (2) Await transcript upload — mirrors lines ~1460-1468 in service.py
+ # Yielding to the event loop here lets the pause task start concurrently.
+ await _mock_upload(
+ user_id="u", session_id="test-sess", content="x", message_count=1
+ )
+ await task
+
+ asyncio.run(_simulate_teardown())
+
+ # Both must run; pause is scheduled before upload starts
+ assert "pause" in call_order
+ assert "upload" in call_order
+ # create_task schedules pause, then upload is awaited — pause runs
+ # concurrently during upload's first yield. The ordering guarantee is
+ # that create_task is CALLED before upload is AWAITED (see source order).
+
def test_baseline_supplement_no_duplicate_tools(self):
"""No tool should appear multiple times in baseline supplement."""
from backend.copilot.prompting import get_baseline_supplement
diff --git a/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py b/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py
index b57b962b84..383a0dabf9 100644
--- a/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py
+++ b/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py
@@ -10,13 +10,34 @@ Lifecycle
---------
1. **Turn start** – connect to the existing sandbox (sandbox_id in Redis) or
create a new one via ``get_or_create_sandbox()``.
+ ``connect()`` in e2b v2 auto-resumes paused sandboxes.
2. **Execution** – ``bash_exec`` and MCP file tools operate directly on the
sandbox's ``/home/user`` filesystem.
-3. **Session expiry** – E2B sandbox is killed by its own timeout (session_ttl).
+3. **Turn end** – the sandbox is paused via ``pause_sandbox()`` (fire-and-forget)
+ so idle time between turns costs nothing. Paused sandboxes have no compute
+ cost.
+4. **Session delete** – ``kill_sandbox()`` fully terminates the sandbox.
+
+Cost control
+------------
+Sandboxes are created with a configurable ``on_timeout`` lifecycle action
+(default: ``"pause"``). The explicit per-turn ``pause_sandbox()`` call is the
+primary mechanism; the lifecycle setting is a safety net. Paused sandboxes are
+free.
+
+The sandbox_id is stored in Redis. The same key doubles as a creation lock:
+a ``"creating"`` sentinel value is written with a short TTL while a new sandbox
+is being provisioned, preventing duplicate creation under concurrent requests.
+
+E2B project-level "paused sandbox lifetime" should be set to match
+``_SANDBOX_ID_TTL`` (48 h) so orphaned paused sandboxes are auto-killed before
+the Redis key expires.
"""
import asyncio
+import contextlib
import logging
+from typing import Any, Awaitable, Callable, Literal
from e2b import AsyncSandbox
@@ -24,147 +45,246 @@ from backend.data.redis_client import get_redis_async
logger = logging.getLogger(__name__)
-_SANDBOX_REDIS_PREFIX = "copilot:e2b:sandbox:"
+_SANDBOX_KEY_PREFIX = "copilot:e2b:sandbox:"
+_CREATING_SENTINEL = "creating"
E2B_WORKDIR = "/home/user"
-_CREATING = "__creating__"
-_CREATION_LOCK_TTL = 60
-_MAX_WAIT_ATTEMPTS = 20 # 20 * 0.5s = 10s max wait
+
+# Short TTL for the "creating" sentinel — if the process dies mid-creation the
+# lock auto-expires so other callers are not blocked forever.
+_CREATION_LOCK_TTL = 60 # seconds
+
+_MAX_WAIT_ATTEMPTS = 20 # 20 × 0.5 s = 10 s max wait
+
+# Timeout for E2B API calls (pause/kill) — short because these are control-plane
+# operations; if the sandbox is unreachable, fail fast and retry on the next turn.
+_E2B_API_TIMEOUT_SECONDS = 10
+
+# Redis TTL for the sandbox key. Must be ≥ the E2B project "paused sandbox
+# lifetime" setting (recommended: set both to 48 h).
+_SANDBOX_ID_TTL = 48 * 3600 # 48 hours
+
+
+def _sandbox_key(session_id: str) -> str:
+ return f"{_SANDBOX_KEY_PREFIX}{session_id}"
+
+
+async def _get_stored_sandbox_id(session_id: str) -> str | None:
+ redis = await get_redis_async()
+ raw = await redis.get(_sandbox_key(session_id))
+ value = raw.decode() if isinstance(raw, bytes) else raw
+ return None if value == _CREATING_SENTINEL else value
+
+
+async def _set_stored_sandbox_id(session_id: str, sandbox_id: str) -> None:
+ redis = await get_redis_async()
+ await redis.set(_sandbox_key(session_id), sandbox_id, ex=_SANDBOX_ID_TTL)
+
+
+async def _clear_stored_sandbox_id(session_id: str) -> None:
+ redis = await get_redis_async()
+ await redis.delete(_sandbox_key(session_id))
async def _try_reconnect(
- sandbox_id: str, api_key: str, redis_key: str, timeout: int
+ sandbox_id: str, session_id: str, api_key: str
) -> "AsyncSandbox | None":
"""Try to reconnect to an existing sandbox. Returns None on failure."""
try:
sandbox = await AsyncSandbox.connect(sandbox_id, api_key=api_key)
if await sandbox.is_running():
- redis = await get_redis_async()
- await redis.expire(redis_key, timeout)
+ # Refresh TTL so an active session cannot lose its sandbox_id at expiry.
+ await _set_stored_sandbox_id(session_id, sandbox_id)
return sandbox
except Exception as exc:
logger.warning("[E2B] Reconnect to %.12s failed: %s", sandbox_id, exc)
- # Stale — clear Redis so a new sandbox can be created.
- redis = await get_redis_async()
- await redis.delete(redis_key)
+ # Stale — clear the sandbox_id from Redis so a new one can be created.
+ await _clear_stored_sandbox_id(session_id)
return None
async def get_or_create_sandbox(
session_id: str,
api_key: str,
+ timeout: int,
template: str = "base",
- timeout: int = 43200,
+ on_timeout: Literal["kill", "pause"] = "pause",
) -> AsyncSandbox:
"""Return the existing E2B sandbox for *session_id* or create a new one.
- The sandbox_id is persisted in Redis so the same sandbox is reused
- across turns. Concurrent calls for the same session are serialised
- via a Redis ``SET NX`` creation lock.
+ The sandbox key in Redis serves a dual purpose: it stores the sandbox_id
+ and acts as a creation lock via a ``"creating"`` sentinel value. This
+ removes the need for a separate lock key.
+
+ *timeout* controls how long the e2b sandbox may run continuously before
+ the ``on_timeout`` lifecycle rule fires (default: 3 h).
+ *on_timeout* controls what happens on timeout: ``"pause"`` (default, free)
+ or ``"kill"``.
"""
redis = await get_redis_async()
- redis_key = f"{_SANDBOX_REDIS_PREFIX}{session_id}"
-
- # 1. Try reconnecting to an existing sandbox.
- raw = await redis.get(redis_key)
- if raw:
- sandbox_id = raw if isinstance(raw, str) else raw.decode()
- if sandbox_id != _CREATING:
- sandbox = await _try_reconnect(sandbox_id, api_key, redis_key, timeout)
+ key = _sandbox_key(session_id)
+
+ for _ in range(_MAX_WAIT_ATTEMPTS):
+ raw = await redis.get(key)
+ value = raw.decode() if isinstance(raw, bytes) else raw
+
+ if value and value != _CREATING_SENTINEL:
+ # Existing sandbox ID — try to reconnect (auto-resumes if paused).
+ sandbox = await _try_reconnect(value, session_id, api_key)
if sandbox:
logger.info(
"[E2B] Reconnected to %.12s for session %.12s",
- sandbox_id,
+ value,
session_id,
)
return sandbox
+ # _try_reconnect cleared the key — loop to create a new sandbox.
+ continue
- # 2. Claim creation lock. If another request holds it, wait for the result.
- claimed = await redis.set(redis_key, _CREATING, nx=True, ex=_CREATION_LOCK_TTL)
- if not claimed:
- for _ in range(_MAX_WAIT_ATTEMPTS):
+ if value == _CREATING_SENTINEL:
+ # Another coroutine is creating — wait for it to finish.
await asyncio.sleep(0.5)
- raw = await redis.get(redis_key)
- if not raw:
- break # Lock expired — fall through to retry creation
- sandbox_id = raw if isinstance(raw, str) else raw.decode()
- if sandbox_id != _CREATING:
- sandbox = await _try_reconnect(sandbox_id, api_key, redis_key, timeout)
- if sandbox:
- return sandbox
- break # Stale sandbox cleared — fall through to create
-
- # Try to claim creation lock again after waiting.
- claimed = await redis.set(redis_key, _CREATING, nx=True, ex=_CREATION_LOCK_TTL)
+ continue
+
+ # No sandbox and no active creation — atomically claim the creation slot.
+ claimed = await redis.set(
+ key, _CREATING_SENTINEL, nx=True, ex=_CREATION_LOCK_TTL
+ )
if not claimed:
- # Another process may have created a sandbox — try to use it.
- raw = await redis.get(redis_key)
- if raw:
- sandbox_id = raw if isinstance(raw, str) else raw.decode()
- if sandbox_id != _CREATING:
- sandbox = await _try_reconnect(
- sandbox_id, api_key, redis_key, timeout
- )
- if sandbox:
- return sandbox
- raise RuntimeError(
- f"Could not acquire E2B creation lock for session {session_id[:12]}"
+ # Race lost — another coroutine just claimed it.
+ await asyncio.sleep(0.1)
+ continue
+
+ # We hold the slot — create the sandbox.
+ try:
+ sandbox = await AsyncSandbox.create(
+ template=template,
+ api_key=api_key,
+ timeout=timeout,
+ lifecycle={"on_timeout": on_timeout},
)
+ try:
+ await _set_stored_sandbox_id(session_id, sandbox.sandbox_id)
+ except Exception:
+ # Redis save failed — kill the sandbox to avoid leaking it.
+ with contextlib.suppress(Exception):
+ await sandbox.kill()
+ raise
+ except Exception:
+ # Release the creation slot so other callers can proceed.
+ await redis.delete(key)
+ raise
- # 3. Create a new sandbox.
- try:
- sandbox = await AsyncSandbox.create(
- template=template, api_key=api_key, timeout=timeout
+ logger.info(
+ "[E2B] Created sandbox %.12s for session %.12s",
+ sandbox.sandbox_id,
+ session_id,
)
- except Exception:
- await redis.delete(redis_key)
- raise
-
- await redis.setex(redis_key, timeout, sandbox.sandbox_id)
- logger.info(
- "[E2B] Created sandbox %.12s for session %.12s",
- sandbox.sandbox_id,
- session_id,
- )
- return sandbox
+ return sandbox
+ raise RuntimeError(f"Could not acquire E2B sandbox for session {session_id[:12]}")
-async def kill_sandbox(session_id: str, api_key: str) -> bool:
- """Kill the E2B sandbox for *session_id* and clean up its Redis entry.
- Returns ``True`` if a sandbox was found and killed, ``False`` otherwise.
- Safe to call even when no sandbox exists for the session.
+async def _act_on_sandbox(
+ session_id: str,
+ api_key: str,
+ action: str,
+ fn: Callable[[AsyncSandbox], Awaitable[Any]],
+ *,
+ clear_stored_id: bool = False,
+) -> bool:
+ """Connect to the sandbox for *session_id* and run *fn* on it.
+
+ Shared by ``pause_sandbox`` and ``kill_sandbox``. Returns ``True`` on
+ success, ``False`` when no sandbox is found or the action fails.
+ If *clear_stored_id* is ``True``, the sandbox_id is removed from Redis
+ only after the action succeeds so a failed kill can be retried.
"""
- redis = await get_redis_async()
- redis_key = f"{_SANDBOX_REDIS_PREFIX}{session_id}"
- raw = await redis.get(redis_key)
- if not raw:
+ sandbox_id = await _get_stored_sandbox_id(session_id)
+ if not sandbox_id:
return False
- sandbox_id = raw if isinstance(raw, str) else raw.decode()
- await redis.delete(redis_key)
+ async def _run() -> None:
+ await fn(await AsyncSandbox.connect(sandbox_id, api_key=api_key))
- if sandbox_id == _CREATING:
+ try:
+ await asyncio.wait_for(_run(), timeout=_E2B_API_TIMEOUT_SECONDS)
+ if clear_stored_id:
+ await _clear_stored_sandbox_id(session_id)
+ logger.info(
+ "[E2B] %s sandbox %.12s for session %.12s",
+ action.capitalize(),
+ sandbox_id,
+ session_id,
+ )
+ return True
+ except Exception as exc:
+ logger.warning(
+ "[E2B] Failed to %s sandbox %.12s for session %.12s: %s",
+ action,
+ sandbox_id,
+ session_id,
+ exc,
+ )
return False
- try:
- async def _connect_and_kill():
- sandbox = await AsyncSandbox.connect(sandbox_id, api_key=api_key)
- await sandbox.kill()
+async def pause_sandbox(session_id: str, api_key: str) -> bool:
+ """Pause the E2B sandbox for *session_id* to stop billing between turns.
+
+ Paused sandboxes cost nothing and are resumed automatically by
+ ``get_or_create_sandbox()`` on the next turn (via ``AsyncSandbox.connect()``).
+ The sandbox_id is kept in Redis so reconnection works seamlessly.
+
+ Prefer ``pause_sandbox_direct()`` when the sandbox object is already in
+ scope — it skips the Redis lookup and reconnect round-trip.
+
+ Returns ``True`` if the sandbox was found and paused, ``False`` otherwise.
+ Safe to call even when no sandbox exists for the session.
+ """
+ return await _act_on_sandbox(session_id, api_key, "pause", lambda sb: sb.pause())
- await asyncio.wait_for(_connect_and_kill(), timeout=10)
+
+async def pause_sandbox_direct(sandbox: "AsyncSandbox", session_id: str) -> bool:
+ """Pause an already-connected sandbox without a reconnect round-trip.
+
+ Use this in callers that already hold the live sandbox object (e.g. turn
+ teardown in ``service.py``). Saves the Redis lookup and
+ ``AsyncSandbox.connect()`` call that ``pause_sandbox()`` would make.
+
+ Returns ``True`` on success, ``False`` on failure or timeout.
+ """
+ try:
+ await asyncio.wait_for(sandbox.pause(), timeout=_E2B_API_TIMEOUT_SECONDS)
logger.info(
- "[E2B] Killed sandbox %.12s for session %.12s",
- sandbox_id,
+ "[E2B] Paused sandbox %.12s for session %.12s",
+ sandbox.sandbox_id,
session_id,
)
return True
except Exception as exc:
logger.warning(
- "[E2B] Failed to kill sandbox %.12s for session %.12s: %s",
- sandbox_id,
+ "[E2B] Failed to pause sandbox %.12s for session %.12s: %s",
+ sandbox.sandbox_id,
session_id,
exc,
)
return False
+
+
+async def kill_sandbox(
+ session_id: str,
+ api_key: str,
+) -> bool:
+ """Kill the E2B sandbox for *session_id* and clear its Redis entry.
+
+ Returns ``True`` if a sandbox was found and killed, ``False`` otherwise.
+ Safe to call even when no sandbox exists for the session.
+ """
+ return await _act_on_sandbox(
+ session_id,
+ api_key,
+ "kill",
+ lambda sb: sb.kill(),
+ clear_stored_id=True,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox_test.py b/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox_test.py
index 31af1fe385..51874193a4 100644
--- a/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox_test.py
@@ -1,6 +1,12 @@
"""Tests for e2b_sandbox: get_or_create_sandbox, _try_reconnect, kill_sandbox.
-Uses mock Redis and mock AsyncSandbox — no external dependencies.
+sandbox_id is stored in Redis under _SANDBOX_KEY_PREFIX + session_id.
+The same key doubles as a creation lock via a "creating" sentinel value.
+
+Tests mock:
+- ``get_redis_async`` (sandbox key storage + creation lock sentinel)
+- ``AsyncSandbox`` (E2B SDK)
+
Tests are synchronous (using asyncio.run) to avoid conflicts with the
session-scoped event loop in conftest.py.
"""
@@ -11,36 +17,50 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from .e2b_sandbox import (
- _CREATING,
- _SANDBOX_REDIS_PREFIX,
+ _CREATING_SENTINEL,
_try_reconnect,
get_or_create_sandbox,
kill_sandbox,
+ pause_sandbox,
+ pause_sandbox_direct,
)
-_KEY = f"{_SANDBOX_REDIS_PREFIX}sess-123"
+_SESSION_ID = "sess-123"
_API_KEY = "test-api-key"
+_SANDBOX_ID = "sb-abc"
_TIMEOUT = 300
-def _mock_sandbox(sandbox_id: str = "sb-abc", running: bool = True) -> MagicMock:
+def _mock_sandbox(sandbox_id: str = _SANDBOX_ID, running: bool = True) -> MagicMock:
sb = MagicMock()
sb.sandbox_id = sandbox_id
sb.is_running = AsyncMock(return_value=running)
+ sb.pause = AsyncMock()
+ sb.kill = AsyncMock()
return sb
-def _mock_redis(get_val: str | bytes | None = None, set_nx_result: bool = True):
+def _mock_redis(
+ set_nx_result: bool = True,
+ stored_sandbox_id: str | None = None,
+) -> AsyncMock:
+ """Create a mock redis client.
+
+ *stored_sandbox_id* is returned by ``get()`` calls (simulates the sandbox_id
+ stored under the ``_SANDBOX_KEY_PREFIX`` key). ``set_nx_result`` controls
+ whether the creation-slot ``SET NX`` succeeds.
+
+ If *stored_sandbox_id* is None the key is absent (no sandbox, no lock).
+ """
r = AsyncMock()
- r.get = AsyncMock(return_value=get_val)
+ raw = stored_sandbox_id.encode() if stored_sandbox_id else None
+ r.get = AsyncMock(return_value=raw)
r.set = AsyncMock(return_value=set_nx_result)
- r.setex = AsyncMock()
r.delete = AsyncMock()
- r.expire = AsyncMock()
return r
-def _patch_redis(redis):
+def _patch_redis(redis: AsyncMock):
return patch(
"backend.copilot.tools.e2b_sandbox.get_redis_async",
new_callable=AsyncMock,
@@ -55,6 +75,7 @@ def _patch_redis(redis):
class TestTryReconnect:
def test_reconnect_success(self):
+ """Returns the sandbox when it connects and is running; refreshes Redis TTL."""
sb = _mock_sandbox()
redis = _mock_redis()
with (
@@ -62,36 +83,39 @@ class TestTryReconnect:
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(return_value=sb)
- result = asyncio.run(_try_reconnect("sb-abc", _API_KEY, _KEY, _TIMEOUT))
+ result = asyncio.run(_try_reconnect(_SANDBOX_ID, _SESSION_ID, _API_KEY))
assert result is sb
- redis.expire.assert_awaited_once_with(_KEY, _TIMEOUT)
redis.delete.assert_not_awaited()
+ # TTL must be refreshed so an active session cannot lose its key at expiry.
+ redis.set.assert_awaited_once()
- def test_reconnect_not_running_clears_key(self):
+ def test_reconnect_not_running_clears_redis(self):
+ """Clears sandbox_id in Redis when the sandbox is no longer running."""
sb = _mock_sandbox(running=False)
- redis = _mock_redis()
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(return_value=sb)
- result = asyncio.run(_try_reconnect("sb-abc", _API_KEY, _KEY, _TIMEOUT))
+ result = asyncio.run(_try_reconnect(_SANDBOX_ID, _SESSION_ID, _API_KEY))
assert result is None
- redis.delete.assert_awaited_once_with(_KEY)
+ redis.delete.assert_awaited_once()
- def test_reconnect_exception_clears_key(self):
- redis = _mock_redis()
+ def test_reconnect_exception_clears_redis(self):
+ """Clears sandbox_id in Redis when connect raises an exception."""
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(side_effect=ConnectionError("gone"))
- result = asyncio.run(_try_reconnect("sb-abc", _API_KEY, _KEY, _TIMEOUT))
+ result = asyncio.run(_try_reconnect(_SANDBOX_ID, _SESSION_ID, _API_KEY))
assert result is None
- redis.delete.assert_awaited_once_with(_KEY)
+ redis.delete.assert_awaited_once()
# ---------------------------------------------------------------------------
@@ -103,38 +127,63 @@ class TestGetOrCreateSandbox:
def test_reconnect_existing(self):
"""When Redis has a valid sandbox_id, reconnect to it."""
sb = _mock_sandbox()
- redis = _mock_redis(get_val="sb-abc")
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(return_value=sb)
result = asyncio.run(
- get_or_create_sandbox("sess-123", _API_KEY, timeout=_TIMEOUT)
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
)
assert result is sb
mock_cls.create.assert_not_called()
+ # redis.set called once to refresh TTL, not to claim a creation slot
+ redis.set.assert_awaited_once()
- def test_create_new_when_no_key(self):
- """When Redis is empty, claim lock and create a new sandbox."""
- sb = _mock_sandbox("sb-new")
- redis = _mock_redis(get_val=None, set_nx_result=True)
+ def test_create_new_when_no_stored_id(self):
+ """When Redis has no sandbox_id, claim slot and create a new sandbox."""
+ new_sb = _mock_sandbox("sb-new")
+ redis = _mock_redis(set_nx_result=True, stored_sandbox_id=None)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
- mock_cls.create = AsyncMock(return_value=sb)
+ mock_cls.create = AsyncMock(return_value=new_sb)
result = asyncio.run(
- get_or_create_sandbox("sess-123", _API_KEY, timeout=_TIMEOUT)
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
)
- assert result is sb
- redis.setex.assert_awaited_once_with(_KEY, _TIMEOUT, "sb-new")
+ assert result is new_sb
+ mock_cls.create.assert_awaited_once()
+ # Verify lifecycle param is set
+ _, kwargs = mock_cls.create.call_args
+ assert kwargs.get("lifecycle") == {"on_timeout": "pause"}
+ # sandbox_id should be saved to Redis
+ redis.set.assert_awaited()
+
+ def test_create_with_on_timeout_kill(self):
+ """on_timeout='kill' is passed through to AsyncSandbox.create."""
+ new_sb = _mock_sandbox("sb-new")
+ redis = _mock_redis(set_nx_result=True, stored_sandbox_id=None)
+ with (
+ patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
+ _patch_redis(redis),
+ ):
+ mock_cls.create = AsyncMock(return_value=new_sb)
+ asyncio.run(
+ get_or_create_sandbox(
+ _SESSION_ID, _API_KEY, timeout=_TIMEOUT, on_timeout="kill"
+ )
+ )
- def test_create_failure_clears_lock(self):
- """If sandbox creation fails, the Redis lock is deleted."""
- redis = _mock_redis(get_val=None, set_nx_result=True)
+ _, kwargs = mock_cls.create.call_args
+ assert kwargs.get("lifecycle") == {"on_timeout": "kill"}
+
+ def test_create_failure_releases_slot(self):
+ """If sandbox creation fails, the Redis creation slot is deleted."""
+ redis = _mock_redis(set_nx_result=True, stored_sandbox_id=None)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
@@ -142,17 +191,53 @@ class TestGetOrCreateSandbox:
mock_cls.create = AsyncMock(side_effect=RuntimeError("quota"))
with pytest.raises(RuntimeError, match="quota"):
asyncio.run(
- get_or_create_sandbox("sess-123", _API_KEY, timeout=_TIMEOUT)
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
)
- redis.delete.assert_awaited_once_with(_KEY)
+ redis.delete.assert_awaited_once()
+
+ def test_redis_save_failure_kills_sandbox_and_releases_slot(self):
+ """If Redis save fails after creation, sandbox is killed and slot released."""
+ new_sb = _mock_sandbox("sb-new")
+ redis = _mock_redis(set_nx_result=True, stored_sandbox_id=None)
+ # First set() call = creation slot SET NX (returns True).
+ # Second set() call = sandbox_id save (raises).
+ call_count = 0
+
+ async def _set_side_effect(*args, **kwargs):
+ nonlocal call_count
+ call_count += 1
+ if call_count == 1:
+ return True # creation slot claimed
+ raise RuntimeError("redis error")
+
+ redis.set = AsyncMock(side_effect=_set_side_effect)
+
+ with (
+ patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
+ _patch_redis(redis),
+ ):
+ mock_cls.create = AsyncMock(return_value=new_sb)
+ with pytest.raises(RuntimeError, match="redis error"):
+ asyncio.run(
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
+ )
- def test_wait_for_lock_then_reconnect(self):
- """When another process holds the lock, wait and reconnect."""
+ # Sandbox must be killed to avoid leaking it
+ new_sb.kill.assert_awaited_once()
+ # Creation slot must always be released
+ redis.delete.assert_awaited_once()
+
+ def test_wait_for_creating_sentinel_then_reconnect(self):
+ """When the key holds the 'creating' sentinel, wait then reconnect."""
sb = _mock_sandbox("sb-other")
- redis = _mock_redis()
- redis.get = AsyncMock(side_effect=[_CREATING, "sb-other"])
+ # First get() returns the sentinel; second returns the real ID.
+ redis = AsyncMock()
+ creating_raw = _CREATING_SENTINEL.encode()
+ redis.get = AsyncMock(side_effect=[creating_raw, b"sb-other"])
redis.set = AsyncMock(return_value=False)
+ redis.delete = AsyncMock()
+
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
@@ -163,16 +248,21 @@ class TestGetOrCreateSandbox:
):
mock_cls.connect = AsyncMock(return_value=sb)
result = asyncio.run(
- get_or_create_sandbox("sess-123", _API_KEY, timeout=_TIMEOUT)
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
)
assert result is sb
def test_stale_reconnect_clears_and_creates(self):
- """When stored sandbox is stale, clear key and create a new one."""
+ """When stored sandbox is stale (not running), clear it and create a new one."""
stale_sb = _mock_sandbox("sb-stale", running=False)
new_sb = _mock_sandbox("sb-fresh")
- redis = _mock_redis(get_val="sb-stale", set_nx_result=True)
+ # First get() returns stale id (for reconnect check), then None (after clear).
+ redis = AsyncMock()
+ redis.get = AsyncMock(side_effect=[b"sb-stale", None])
+ redis.set = AsyncMock(return_value=True)
+ redis.delete = AsyncMock()
+
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
@@ -180,10 +270,11 @@ class TestGetOrCreateSandbox:
mock_cls.connect = AsyncMock(return_value=stale_sb)
mock_cls.create = AsyncMock(return_value=new_sb)
result = asyncio.run(
- get_or_create_sandbox("sess-123", _API_KEY, timeout=_TIMEOUT)
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
)
assert result is new_sb
+ # Redis delete called at least once to clear stale id
redis.delete.assert_awaited()
@@ -194,70 +285,123 @@ class TestGetOrCreateSandbox:
class TestKillSandbox:
def test_kill_existing_sandbox(self):
- """Kill a running sandbox and clean up Redis."""
+ """Kill a running sandbox and clear its Redis entry."""
sb = _mock_sandbox()
- sb.kill = AsyncMock()
- redis = _mock_redis(get_val="sb-abc")
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(return_value=sb)
- result = asyncio.run(kill_sandbox("sess-123", _API_KEY))
+ result = asyncio.run(kill_sandbox(_SESSION_ID, _API_KEY))
assert result is True
- redis.delete.assert_awaited_once_with(_KEY)
sb.kill.assert_awaited_once()
+ # Redis key cleared after successful kill
+ redis.delete.assert_awaited_once()
def test_kill_no_sandbox(self):
- """No-op when no sandbox exists in Redis."""
- redis = _mock_redis(get_val=None)
+ """No-op when Redis has no sandbox_id."""
+ redis = _mock_redis(stored_sandbox_id=None)
with _patch_redis(redis):
- result = asyncio.run(kill_sandbox("sess-123", _API_KEY))
+ result = asyncio.run(kill_sandbox(_SESSION_ID, _API_KEY))
assert result is False
- redis.delete.assert_not_awaited()
-
- def test_kill_creating_state(self):
- """Clears Redis key but returns False when sandbox is still being created."""
- redis = _mock_redis(get_val=_CREATING)
- with _patch_redis(redis):
- result = asyncio.run(kill_sandbox("sess-123", _API_KEY))
- assert result is False
- redis.delete.assert_awaited_once_with(_KEY)
+ def test_kill_connect_failure_keeps_redis(self):
+ """Returns False and leaves Redis entry intact when connect/kill fails.
- def test_kill_connect_failure(self):
- """Returns False and cleans Redis if connect/kill fails."""
- redis = _mock_redis(get_val="sb-abc")
+ Keeping the sandbox_id in Redis allows the kill to be retried.
+ """
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(side_effect=ConnectionError("gone"))
- result = asyncio.run(kill_sandbox("sess-123", _API_KEY))
+ result = asyncio.run(kill_sandbox(_SESSION_ID, _API_KEY))
assert result is False
- redis.delete.assert_awaited_once_with(_KEY)
+ redis.delete.assert_not_awaited()
- def test_kill_with_bytes_redis_value(self):
- """Redis may return bytes — kill_sandbox should decode correctly."""
+ def test_kill_timeout_keeps_redis(self):
+ """Returns False and leaves Redis entry intact when the E2B call times out."""
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
+ with (
+ _patch_redis(redis),
+ patch(
+ "backend.copilot.tools.e2b_sandbox.asyncio.wait_for",
+ new_callable=AsyncMock,
+ side_effect=asyncio.TimeoutError,
+ ),
+ ):
+ result = asyncio.run(kill_sandbox(_SESSION_ID, _API_KEY))
+
+ assert result is False
+ redis.delete.assert_not_awaited()
+
+ def test_kill_creating_sentinel_returns_false(self):
+ """No-op when the key holds the 'creating' sentinel (no real sandbox yet)."""
+ redis = _mock_redis(stored_sandbox_id=_CREATING_SENTINEL)
+ with _patch_redis(redis):
+ result = asyncio.run(kill_sandbox(_SESSION_ID, _API_KEY))
+
+ assert result is False
+
+
+# ---------------------------------------------------------------------------
+# pause_sandbox
+# ---------------------------------------------------------------------------
+
+
+class TestPauseSandbox:
+ def test_pause_existing_sandbox(self):
+ """Pause a running sandbox; Redis sandbox_id is preserved."""
sb = _mock_sandbox()
- sb.kill = AsyncMock()
- redis = _mock_redis(get_val=b"sb-abc")
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
_patch_redis(redis),
):
mock_cls.connect = AsyncMock(return_value=sb)
- result = asyncio.run(kill_sandbox("sess-123", _API_KEY))
+ result = asyncio.run(pause_sandbox(_SESSION_ID, _API_KEY))
assert result is True
- sb.kill.assert_awaited_once()
+ sb.pause.assert_awaited_once()
+ # sandbox_id should remain in Redis (not cleared on pause)
+ redis.delete.assert_not_awaited()
+
+ def test_pause_no_sandbox(self):
+ """No-op when Redis has no sandbox_id."""
+ redis = _mock_redis(stored_sandbox_id=None)
+ with _patch_redis(redis):
+ result = asyncio.run(pause_sandbox(_SESSION_ID, _API_KEY))
- def test_kill_timeout_returns_false(self):
- """Returns False when E2B API calls exceed the 10s timeout."""
- redis = _mock_redis(get_val="sb-abc")
+ assert result is False
+
+ def test_pause_connect_failure(self):
+ """Returns False if connect fails."""
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
+ with (
+ patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
+ _patch_redis(redis),
+ ):
+ mock_cls.connect = AsyncMock(side_effect=ConnectionError("gone"))
+ result = asyncio.run(pause_sandbox(_SESSION_ID, _API_KEY))
+
+ assert result is False
+
+ def test_pause_creating_sentinel_returns_false(self):
+ """No-op when the key holds the 'creating' sentinel (no real sandbox yet)."""
+ redis = _mock_redis(stored_sandbox_id=_CREATING_SENTINEL)
+ with _patch_redis(redis):
+ result = asyncio.run(pause_sandbox(_SESSION_ID, _API_KEY))
+
+ assert result is False
+
+ def test_pause_timeout_returns_false(self):
+ """Returns False and preserves Redis entry when the E2B API call times out."""
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
with (
_patch_redis(redis),
patch(
@@ -266,7 +410,71 @@ class TestKillSandbox:
side_effect=asyncio.TimeoutError,
),
):
- result = asyncio.run(kill_sandbox("sess-123", _API_KEY))
+ result = asyncio.run(pause_sandbox(_SESSION_ID, _API_KEY))
+
+ assert result is False
+ # sandbox_id must remain in Redis so the next turn can reconnect
+ redis.delete.assert_not_awaited()
+
+ def test_pause_then_reconnect_reuses_sandbox(self):
+ """After pause, get_or_create_sandbox reconnects the same sandbox.
+
+ Covers the pause->reconnect cycle: connect() auto-resumes a paused
+ sandbox, and is_running() returns True once resume completes, so the
+ same sandbox_id is reused rather than a new one being created.
+ """
+ sb = _mock_sandbox(_SANDBOX_ID)
+ redis = _mock_redis(stored_sandbox_id=_SANDBOX_ID)
+ with (
+ patch("backend.copilot.tools.e2b_sandbox.AsyncSandbox") as mock_cls,
+ _patch_redis(redis),
+ ):
+ mock_cls.connect = AsyncMock(return_value=sb)
+
+ # Step 1: pause the sandbox
+ paused = asyncio.run(pause_sandbox(_SESSION_ID, _API_KEY))
+ assert paused is True
+ sb.pause.assert_awaited_once()
+
+ # Step 2: reconnect on next turn -- same sandbox should be returned
+ result = asyncio.run(
+ get_or_create_sandbox(_SESSION_ID, _API_KEY, timeout=_TIMEOUT)
+ )
+
+ assert result is sb
+ mock_cls.create.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# pause_sandbox_direct
+# ---------------------------------------------------------------------------
+
+
+class TestPauseSandboxDirect:
+ def test_pause_direct_success(self):
+ """Pauses the sandbox directly without a Redis lookup or reconnect."""
+ sb = _mock_sandbox()
+ result = asyncio.run(pause_sandbox_direct(sb, _SESSION_ID))
+
+ assert result is True
+ sb.pause.assert_awaited_once()
+
+ def test_pause_direct_failure_returns_false(self):
+ """Returns False when sandbox.pause() raises."""
+ sb = _mock_sandbox()
+ sb.pause = AsyncMock(side_effect=RuntimeError("e2b error"))
+ result = asyncio.run(pause_sandbox_direct(sb, _SESSION_ID))
+
+ assert result is False
+
+ def test_pause_direct_timeout_returns_false(self):
+ """Returns False when sandbox.pause() exceeds the 10s timeout."""
+ sb = _mock_sandbox()
+ with patch(
+ "backend.copilot.tools.e2b_sandbox.asyncio.wait_for",
+ new_callable=AsyncMock,
+ side_effect=asyncio.TimeoutError,
+ ):
+ result = asyncio.run(pause_sandbox_direct(sb, _SESSION_ID))
assert result is False
- redis.delete.assert_awaited_once_with(_KEY)
diff --git a/autogpt_platform/backend/poetry.lock b/autogpt_platform/backend/poetry.lock
index def758736a..2f061fcba1 100644
--- a/autogpt_platform/backend/poetry.lock
+++ b/autogpt_platform/backend/poetry.lock
@@ -563,6 +563,18 @@ webencodings = "*"
[package.extras]
css = ["tinycss2 (>=1.1.0,<1.5)"]
+[[package]]
+name = "bracex"
+version = "2.6"
+description = "Bash style brace expander."
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+files = [
+ {file = "bracex-2.6-py3-none-any.whl", hash = "sha256:0b0049264e7340b3ec782b5cb99beb325f36c3782a32e36e876452fd49a09952"},
+ {file = "bracex-2.6.tar.gz", hash = "sha256:98f1347cd77e22ee8d967a30ad4e310b233f7754dbf31ff3fceb76145ba47dc7"},
+]
+
[[package]]
name = "browserbase"
version = "1.4.0"
@@ -1172,6 +1184,18 @@ idna = ["idna (>=3.10)"]
trio = ["trio (>=0.30)"]
wmi = ["wmi (>=1.5.1) ; platform_system == \"Windows\""]
+[[package]]
+name = "dockerfile-parse"
+version = "2.0.1"
+description = "Python library for Dockerfile manipulation"
+optional = false
+python-versions = ">=3.6"
+groups = ["main"]
+files = [
+ {file = "dockerfile-parse-2.0.1.tar.gz", hash = "sha256:3184ccdc513221983e503ac00e1aa504a2aa8f84e5de673c46b0b6eee99ec7bc"},
+ {file = "dockerfile_parse-2.0.1-py2.py3-none-any.whl", hash = "sha256:bdffd126d2eb26acf1066acb54cb2e336682e1d72b974a40894fac76a4df17f6"},
+]
+
[[package]]
name = "docstring-parser"
version = "0.17.0"
@@ -1258,40 +1282,43 @@ pgp = ["gpg"]
[[package]]
name = "e2b"
-version = "1.11.1"
+version = "2.15.1"
description = "E2B SDK that give agents cloud environments"
optional = false
-python-versions = "<4.0,>=3.9"
+python-versions = "<4.0,>=3.10"
groups = ["main"]
files = [
- {file = "e2b-1.11.1-py3-none-any.whl", hash = "sha256:1ecb123873788472731c101939a494ab852cbcce0f913df6f7ecb194ae932130"},
- {file = "e2b-1.11.1.tar.gz", hash = "sha256:7f7b6f238208d0a23353bb0da01f91a924321b57c61b176506862cbc1493ce8c"},
+ {file = "e2b-2.15.1-py3-none-any.whl", hash = "sha256:a3bc4e004eab51fb05bae44e9ee4fe821e4637260f4ce3064c8f7c6ed7f5a2a0"},
+ {file = "e2b-2.15.1.tar.gz", hash = "sha256:a4f1bbc8b5180a8a1098079257fcb73e42503ed546098f676f722f11f0d68c09"},
]
[package.dependencies]
attrs = ">=23.2.0"
+dockerfile-parse = ">=2.0.1,<3.0.0"
httpcore = ">=1.0.5,<2.0.0"
httpx = ">=0.27.0,<1.0.0"
packaging = ">=24.1"
protobuf = ">=4.21.0"
python-dateutil = ">=2.8.2"
+rich = ">=14.0.0"
typing-extensions = ">=4.1.0"
+wcmatch = ">=10.1,<11.0"
[[package]]
name = "e2b-code-interpreter"
-version = "1.5.2"
+version = "2.4.1"
description = "E2B Code Interpreter - Stateful code execution"
optional = false
python-versions = "<4.0,>=3.9"
groups = ["main"]
files = [
- {file = "e2b_code_interpreter-1.5.2-py3-none-any.whl", hash = "sha256:5c3188d8f25226b28fef4b255447cc6a4c36afb748bdd5180b45be486d5169f3"},
- {file = "e2b_code_interpreter-1.5.2.tar.gz", hash = "sha256:3bd6ea70596290e85aaf0a2f19f28bf37a5e73d13086f5e6a0080bb591c5a547"},
+ {file = "e2b_code_interpreter-2.4.1-py3-none-any.whl", hash = "sha256:15d35f025b4a15033e119f2e12e7ac65657ad2b5a013fa9149e74581fbee778a"},
+ {file = "e2b_code_interpreter-2.4.1.tar.gz", hash = "sha256:4b15014ee0d0dfcdc3072e1f409cbb87ca48f48d53d75629b7257e5513b9e7dd"},
]
[package.dependencies]
attrs = ">=21.3.0"
-e2b = ">=1.5.4,<2.0.0"
+e2b = ">=2.7.0,<3.0.0"
httpx = ">=0.20.0,<1.0.0"
[[package]]
@@ -8091,6 +8118,21 @@ files = [
[package.dependencies]
anyio = ">=3.0.0"
+[[package]]
+name = "wcmatch"
+version = "10.1"
+description = "Wildcard/glob file name matcher."
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+files = [
+ {file = "wcmatch-10.1-py3-none-any.whl", hash = "sha256:5848ace7dbb0476e5e55ab63c6bbd529745089343427caa5537f230cc01beb8a"},
+ {file = "wcmatch-10.1.tar.gz", hash = "sha256:f11f94208c8c8484a16f4f48638a85d771d9513f4ab3f37595978801cb9465af"},
+]
+
+[package.dependencies]
+bracex = ">=2.1.1"
+
[[package]]
name = "webencodings"
version = "0.5.1"
@@ -8840,4 +8882,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.14"
-content-hash = "7189c9725ca42dfe6672632fe801c61248d87d3dd1259747b0ed9579b19fe088"
+content-hash = "618d61b0586ab82fec1e28d1feb549a198e0b5c9d152e808862e55efc00a65b9"
diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.toml
index c1beecfdce..64297f7b00 100644
--- a/autogpt_platform/backend/pyproject.toml
+++ b/autogpt_platform/backend/pyproject.toml
@@ -20,7 +20,8 @@ claude-agent-sdk = "0.1.45" # see copilot/sdk/sdk_compat_test.py for capability
click = "^8.2.0"
cryptography = "^46.0"
discord-py = "^2.5.2"
-e2b-code-interpreter = "^1.5.2"
+e2b = "^2.0"
+e2b-code-interpreter = "^2.0"
elevenlabs = "^1.50.0"
fastapi = "^0.128.6"
feedparser = "^6.0.11"
@@ -154,3 +155,4 @@ filterwarnings = [
[tool.ruff]
target-version = "py310"
+