{"id":2301,"library":"swe-rex","title":"Sandboxed Code Execution for AI Agents","description":"SWE-ReX (SWE-agent Remote Execution Framework) is a Python library designed for sandboxed code execution for AI agents. It provides a flexible runtime interface for interacting with shell environments, supporting execution locally or remotely across various platforms like Docker containers, AWS Fargate, Modal, and Daytona. This enables massively parallel agent runs and disentangles agent logic from infrastructure concerns, making it a core component for projects like SWE-agent. Currently at version 1.4.0, SWE-ReX maintains an active development cycle with regular updates enhancing backend support and overall stability.","status":"active","version":"1.4.0","language":"en","source_language":"en","source_url":"https://github.com/SWE-agent/SWE-rex","tags":["ai-agents","sandbox","code-execution","docker","cloud","swe-agent","developer-tools","asyncio"],"install":[{"cmd":"pip install swe-rex","lang":"bash","label":"Base installation"},{"cmd":"pip install 'swe-rex[modal]'","lang":"bash","label":"With Modal support"},{"cmd":"pip install 'swe-rex[fargate]'","lang":"bash","label":"With AWS Fargate support"},{"cmd":"pip install 'swe-rex[daytona]'","lang":"bash","label":"With Daytona support"},{"cmd":"pip install 'swe-rex[dev]'","lang":"bash","label":"All optional dependencies for development"}],"dependencies":[{"reason":"Core dependency for interacting with child processes.","package":"pexpect"},{"reason":"Used for configuration and data validation.","package":"pydantic"},{"reason":"Dependency for web server functionality.","package":"python-multipart"},{"reason":"For rich text and progress bar displays.","package":"rich"},{"reason":"ASGI server for running the remote runtime.","package":"uvicorn"},{"reason":"Web framework for the remote runtime server.","package":"fastapi"},{"reason":"For parsing bash commands.","package":"bashlex"},{"reason":"For making HTTP requests.","package":"requests"},{"reason":"Optional, required for Modal deployments.","package":"modal-client","optional":true},{"reason":"Optional, required for Daytona deployments.","package":"daytona-sdk","optional":true},{"reason":"Optional, required for AWS Fargate deployments (implied by 'fargate' extra).","package":"boto3","optional":true}],"imports":[{"symbol":"LocalDeployment","correct":"from swerex.deployment.local import LocalDeployment"},{"symbol":"DockerDeployment","correct":"from swerex.deployment.docker import DockerDeployment"},{"symbol":"CreateBashSessionRequest","correct":"from swerex.runtime.abstract import CreateBashSessionRequest"},{"symbol":"BashAction","correct":"from swerex.runtime.abstract import BashAction"},{"symbol":"Command","correct":"from swerex.runtime.abstract import Command"}],"quickstart":{"code":"import asyncio\nfrom swerex.deployment.local import LocalDeployment\nfrom swerex.deployment.docker import DockerDeployment\nfrom swerex.runtime.abstract import CreateBashSessionRequest, BashAction, Command\nimport os\n\nasync def run_code_with_deployment(deployment_type: str):\n    if deployment_type == \"local\":\n        # LocalDeployment runs on your machine WITHOUT sandboxing. Be cautious.\n        deployment = LocalDeployment()\n        print(\"Running locally (no sandboxing by default). Be careful with commands!\")\n    elif deployment_type == \"docker\":\n        # DockerDeployment provides sandboxing\n        # Ensure Docker is running. You might need to pull the image first if not cached.\n        deployment = DockerDeployment(image=\"python:3.12\")\n        print(\"Running in a Docker sandbox...\")\n    else:\n        raise ValueError(\"Invalid deployment type\")\n\n    try:\n        await deployment.start()\n        runtime = deployment.runtime\n\n        # Execute one-off commands\n        print(f\"Executing: echo Hello, world! from {deployment_type}\")\n        result = await runtime.execute(Command(command=[\"echo\", f\"Hello, world! from {deployment_type}\"]))\n        print(f\"Output: {result.stdout.strip()}\\n\")\n\n        # Create a bash session for persistent state\n        await runtime.create_session(CreateBashSessionRequest())\n\n        print(f\"Running in session: export MYVAR='test_{deployment_type}'\")\n        await runtime.run_in_session(BashAction(command=f\"export MYVAR='test_{deployment_type}'\"))\n\n        print(f\"Running in session: echo $MYVAR\")\n        result_session = await runtime.run_in_session(BashAction(command=\"echo $MYVAR\"))\n        print(f\"Output from session: {result_session.stdout.strip()}\\n\")\n\n    finally:\n        await deployment.stop()\n\nasync def main():\n    print(\"--- Local Deployment Example ---\")\n    await run_code_with_deployment(\"local\")\n\n    print(\"\\n--- Docker Deployment Example ---\")\n    await run_code_with_deployment(\"docker\")\n\nif __name__ == \"__main__\":\n    # os.environ['MODAL_TOKEN_ID'] = os.environ.get('MODAL_TOKEN_ID', '') # For ModalDeployment\n    # os.environ['MODAL_TOKEN_SECRET'] = os.environ.get('MODAL_TOKEN_SECRET', '') # For ModalDeployment\n    # ... similarly for AWS or Daytona credentials if used ...\n    asyncio.run(main())\n","lang":"python","description":"This quickstart demonstrates how to set up `swe-rex` with both local and Docker deployments. It shows how to execute single commands and interact with a persistent bash session. Remember that `LocalDeployment` executes commands directly on your machine without sandboxing. For sandboxed environments, `DockerDeployment` (or cloud deployments like Modal/Fargate/Daytona) are recommended."},"warnings":[{"fix":"For sandboxed execution, use `DockerDeployment`, `ModalDeployment`, `FargateDeployment`, or `DaytonaDeployment`. Review commands thoroughly before execution in local mode.","message":"When using `LocalDeployment`, commands are executed directly on your host machine without any sandboxing. Exercise extreme caution, especially with administrative commands.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Upgrade to `swe-rex` version 1.2.1 or newer.","message":"Versions prior to v1.2.1 could experience `TemporaryDirectory` cleanup issues on Windows, potentially leaving temporary files or directories behind.","severity":"gotcha","affected_versions":"<1.2.1"},{"fix":"Ensure that the `PATH` environment variable inside your Docker container explicitly includes the `pipx` installation directory (e.g., `ENV PATH=\"$PATH:/root/.local/bin/\"`) after running `pipx ensurepath`.","message":"In some Docker environments, particularly when integrating with tools like SWE-agent, the `swe-rex` server installed via `pipx` might not be correctly added to the system's `PATH` variable.","severity":"gotcha","affected_versions":"All versions, especially in custom Docker images"},{"fix":"Upgrade to `swe-rex` v1.4.0 or newer. This version includes a fix for the hardcoded Python runtime value, improving Docker build stability.","message":"Older versions (prior to v1.4.0) had a hardcoded Python runtime value which could lead to Docker build failures when running in default configurations or with specific projects like SWE-agent.","severity":"gotcha","affected_versions":"<1.4.0"},{"fix":"Check for available ports, increase `startup_timeout` in your deployment configuration (e.g., `DockerDeploymentConfig(startup_timeout=300.0)`), and ensure Docker/container runtime is properly configured and accessible within the environment.","message":"Users might encounter 'Runtime did not start within timeout' errors, especially in CI/CD environments like GitHub Actions. This often indicates issues with port allocation or insufficient startup time.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}