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.

fix(backend/copilot): surface non-zero E2B exits as real results, not sandbox errors (#12904)

Zamil Majdy43b38f69899a
diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
index 1fbf4adc9c..46d1264de5 100644
--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
@@ -18,7 +18,7 @@ import logging
import shlex
from typing import Any
-from e2b import AsyncSandbox
+from e2b import AsyncSandbox, CommandExitException
from e2b.exceptions import TimeoutException
from backend.copilot.context import E2B_WORKDIR, get_current_sandbox
@@ -35,6 +35,28 @@ from .sandbox import get_workspace_dir, has_full_sandbox, run_sandboxed
logger = logging.getLogger(__name__)
+def _build_completion_response(
+ stdout: str | None,
+ stderr: str | None,
+ exit_code: int,
+ secret_values: list[str],
+ session_id: str | None,
+) -> BashExecResponse:
+ out = stdout or ""
+ err = stderr or ""
+ for secret in secret_values:
+ out = out.replace(secret, "[REDACTED]")
+ err = err.replace(secret, "[REDACTED]")
+ return BashExecResponse(
+ message=f"Command executed with status code {exit_code}",
+ stdout=out,
+ stderr=err,
+ exit_code=exit_code,
+ timed_out=False,
+ session_id=session_id,
+ )
+
+
class BashExecTool(BaseTool):
"""Execute Bash commands on E2B or in a bubblewrap sandbox."""
@@ -175,31 +197,27 @@ class BashExecTool(BaseTool):
timeout=timeout,
envs=envs,
)
- stdout = result.stdout or ""
- stderr = result.stderr or ""
- # Scrub injected tokens from command output to prevent exfiltration
- # via `echo $GH_TOKEN`, `env`, `printenv`, etc.
- for secret in secret_values:
- stdout = stdout.replace(secret, "[REDACTED]")
- stderr = stderr.replace(secret, "[REDACTED]")
+ return _build_completion_response(
+ result.stdout,
+ result.stderr,
+ result.exit_code,
+ secret_values,
+ session_id,
+ )
+ except CommandExitException as exc:
+ return _build_completion_response(
+ exc.stdout, exc.stderr, exc.exit_code, secret_values, session_id
+ )
+ except TimeoutException:
return BashExecResponse(
- message=f"Command executed with status code {result.exit_code}",
- stdout=stdout,
- stderr=stderr,
- exit_code=result.exit_code,
- timed_out=False,
+ message="Execution timed out",
+ stdout="",
+ stderr=f"Timed out after {timeout}s",
+ exit_code=-1,
+ timed_out=True,
session_id=session_id,
)
except Exception as exc:
- if isinstance(exc, TimeoutException):
- return BashExecResponse(
- message="Execution timed out",
- stdout="",
- stderr=f"Timed out after {timeout}s",
- exit_code=-1,
- timed_out=True,
- session_id=session_id,
- )
logger.error("[E2B] bash_exec failed: %s", exc, exc_info=True)
return ErrorResponse(
message=f"E2B execution failed: {exc}",
diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py
index 47b0570960..497b6aba08 100644
--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py
@@ -3,6 +3,7 @@
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from e2b import CommandExitException
from ._test_data import make_session
from .bash_exec import BashExecTool
@@ -125,6 +126,47 @@ class TestBashExecE2BTokenInjection:
assert "GIT_AUTHOR_NAME" not in call_kwargs["envs"]
assert "GIT_COMMITTER_EMAIL" not in call_kwargs["envs"]
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_nonzero_exit_returned_as_bash_exec_response(self):
+ """CommandExitException (non-zero exit) must become a BashExecResponse with scrubbed output."""
+ tool = _make_tool()
+ session = make_session(user_id=_USER)
+
+ sandbox = MagicMock()
+ sandbox.commands.run = AsyncMock(
+ side_effect=CommandExitException(
+ stdout="not logged in gh-secret",
+ stderr="oops gh-secret",
+ exit_code=1,
+ error=None,
+ )
+ )
+
+ with (
+ patch(
+ "backend.copilot.tools.bash_exec.get_integration_env_vars",
+ new=AsyncMock(return_value={"GH_TOKEN": "gh-secret"}),
+ ),
+ patch(
+ "backend.copilot.tools.bash_exec.get_github_user_git_identity",
+ new=AsyncMock(return_value=None),
+ ),
+ ):
+ result = await tool._execute_on_e2b(
+ sandbox=sandbox,
+ command="gh auth status 2>&1",
+ timeout=10,
+ session_id=session.session_id,
+ user_id=_USER,
+ )
+
+ assert isinstance(result, BashExecResponse)
+ assert result.exit_code == 1
+ assert result.timed_out is False
+ assert result.stdout == "not logged in [REDACTED]"
+ assert result.stderr == "oops [REDACTED]"
+ assert result.message == "Command executed with status code 1"
+
@pytest.mark.asyncio(loop_scope="session")
async def test_no_token_injection_when_user_id_is_none(self):
"""When user_id is None, get_integration_env_vars must NOT be called."""