### LocalDeployment Usage Example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Demonstrates starting a deployment, creating a session, running commands, and stopping the deployment. ```python import asyncio from swerex.deployment.local import LocalDeployment from swerex.runtime.abstract import BashAction, Command, CreateBashSessionRequest async def main() -> None: deployment = LocalDeployment() await deployment.start() assert await deployment.is_alive() runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) await runtime.run_in_session(BashAction(command="export MYVAR='test'")) obs = await runtime.run_in_session(BashAction(command="echo $MYVAR")) print(obs.output) # test result = await runtime.execute(Command(command=["echo", "Hello, world!"])) print(result.stdout) # Hello, world! await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### Usage example for DaytonaDeployment Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/daytona-deployment.md Usage example showing how to create a DaytonaDeployment, start it, run a bash command in a session, and stop it. ```python import asyncio from swerex.deployment.daytona import DaytonaDeployment from swerex.runtime.abstract import BashAction, CreateBashSessionRequest async def main() -> None: deployment = DaytonaDeployment( api_key="", target="us", image="python:3.11", ) await deployment.start() try: runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) obs = await runtime.run_in_session(BashAction(command="echo hello-daytona")) print(obs.output) finally: await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### Hello world with LocalDeployment Source: https://github.com/swe-agent/swe-rex/blob/main/docs/usage.md Runs a local SWE-ReX deployment without sandboxing. The example starts the deployment, issues one-off commands, creates a bash session, and runs commands in that session to show persistent environment state. Note that this runs commands on your local machine without any sandboxing, so avoid destructive commands like `rm -rf /`. ```python import asyncio from swerex.deployment.local import LocalDeployment from swerex.runtime.abstract import CreateBashSessionRequest, BashAction, Command deployment = LocalDeployment() async def run_some_stuff(deployment): """Spoiler: This function will work with any deployment.""" await deployment.start() # (1)! runtime = deployment.runtime # Issue a few one-off commands, similar to `subprocess.run()` print(await runtime.execute(Command(command=["echo", "Hello, world!"]))) # Create a bash session await runtime.create_session(CreateBashSessionRequest()) # Run a command in the session # The difference to the one-off commands is that environment state persists! print(await runtime.run_in_session(BashAction(command="export MYVAR='test'"))) print(await runtime.run_in_session(BashAction(command="echo $MYVAR"))) await deployment.stop() # (2)! asyncio.run(run_some_stuff(deployment)) # (3)! ``` -------------------------------- ### Error-handling example for DaytonaDeployment Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/daytona-deployment.md Error-handling example showing how to catch exceptions during start, such as authentication failures or runtime errors. ```python async def demo() -> None: dep = DaytonaDeployment(api_key="", image="python:3.11") try: await dep.start() except Exception as e: # e.g. daytona-sdk authentication failures, or # RuntimeError("Failed to start SWE Rex server: ...") print("start failed:", e) ``` -------------------------------- ### ModalDeployment usage example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/modal-deployment.md Shows how to create and start a ModalDeployment with a specified image, then run a bash command in a session. It uses asyncio and imports from swerex.deployment.modal and swerex.runtime.abstract. ```python import asyncio from swerex.deployment.modal import ModalDeployment from swerex.runtime.abstract import BashAction, CreateBashSessionRequest async def main() -> None: deployment = ModalDeployment( image="python:3.12", startup_timeout=60, deployment_timeout=3600, install_pipx=True, ) await deployment.start() try: print("logs:", await deployment.get_modal_log_url()) runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) obs = await runtime.run_in_session(BashAction(command="python --version")) print(obs.output) finally: await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### Usage example for DummyDeployment with mocked outputs Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-deployment.md Usage example for DummyDeployment. It creates a deployment, starts it, primes a mocked BashObservation, creates a session, runs a command, and prints the mocked output and exit code. The output is 'mocked 0'. ```python import asyncio from swerex.deployment.dummy import DummyDeployment from swerex.runtime.abstract import BashAction, BashObservation, CreateBashSessionRequest async def main() -> None: deployment = DummyDeployment() await deployment.start() assert deployment.runtime is not None # Prime predefined outputs through the runtime deployment.runtime.run_in_session_outputs = BashObservation(output="mocked", exit_code=0) await deployment.runtime.create_session(CreateBashSessionRequest()) obs = await deployment.runtime.run_in_session(BashAction(command="anything")) print(obs.output, obs.exit_code) # mocked 0 await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### start method signature and internal command Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/modal-deployment.md Starts the deployment if not already started. Generates auth token and creates Modal sandbox with the inner command. Displays the modal.Sandbox.create.aio call and the _start_swerex_cmd template. ```python async def start(self): ``` ```python modal.Sandbox.create.aio( "/usr/bin/env", "bash", "-c", self._start_swerex_cmd(token), image=self._image, timeout=int(self._deployment_timeout), unencrypted_ports=[self._port], app=self._app, **self._modal_kwargs, ) ``` ```python swerex-remote --port 8880 --auth-token TOKEN || pipx run swe-rex --port 8880 --auth-token TOKEN ``` -------------------------------- ### LocalDeployment Error-handling Example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Shows how to handle DeploymentNotStartedError when accessing the runtime before starting, and the behavior of is_alive before start. ```python from swerex.exceptions import DeploymentNotStartedError async def demo() -> None: deployment = LocalDeployment() try: _ = deployment.runtime except DeploymentNotStartedError: print("runtime requires start()") # is_alive before start does NOT raise: alive = await deployment.is_alive() print("alive?", alive.is_alive, "-", alive.message) # False Runtime is None. ``` -------------------------------- ### DaytonaDeployment.start method Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/daytona-deployment.md Starts the deployment: initializes Daytona, creates a sandbox, starts swerex-remote in a session, and waits for the runtime to become alive. ```python async def start(self): ``` -------------------------------- ### start Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/daytona-deployment.md Starts the SWE-ReX server in a Daytona sandbox and waits for it to become alive. ```APIDOC ```python async def start(self): ``` ### Description Initializes the Daytona client, creates a sandbox, starts a persistent session, runs `swerex-remote` (or fallback installs), retrieves the preview link, and waits for the runtime to become alive. ### Raises - `RuntimeError` if the server fails to start (exit_code != 0). ``` -------------------------------- ### FargateDeployment usage example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/fargate-deployment.md Shows how to start a Fargate deployment, create a session, run a bash command, and stop the deployment. The deployment is configured with a Python 3.11 image, a cluster name, and a port. The runtime is accessed after start and used to create a session and run a command, printing the output. ```python import asyncio from swerex.deployment.fargate import FargateDeployment from swerex.runtime.abstract import BashAction, CreateBashSessionRequest async def main() -> None: deployment = FargateDeployment( image="python:3.11", cluster_name="my-swe-rex-cluster", port=8880, ) await deployment.start() try: runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) obs = await runtime.run_in_session(BashAction(command="echo hello-fargate")) print(obs.output) finally: await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### LocalDeployment.start Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Starts the deployment by creating a LocalRuntime instance. ```APIDOC ## LocalDeployment.start ### Description Starts the deployment by setting self._runtime to a new LocalRuntime instance. ### Method async start ### Signature ```python async def start(self): n``` n ### Source `src/swerex/deployment/local.py:54` ``` -------------------------------- ### AbstractDeployment start Method Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/abstract-deployment.md Starts the environment and blocks until the runtime is reachable. Returns an AbstractRuntime upon success. ```python @abstractmethod async def start(self, *args, **kwargs): ``` -------------------------------- ### DummyDeployment.start Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-deployment.md Starts the deployment. This is a no-op for DummyDeployment. ```APIDOC ## Method: start ### Description Starts the deployment. This is a no-op for DummyDeployment. ### Method start ``` -------------------------------- ### ModalDeployment.start Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/modal-deployment.md Starts the Modal sandbox and runtime. No-op with a warning if already started. ```APIDOC ## Method `start` ### Description Starts the Modal sandbox and runtime. If already started, logs a warning and does nothing. Otherwise creates a sandbox, acquires a tunnel, builds a `RemoteRuntime`, and waits for the runtime to become alive. ### Signature ```python async def start(self): ``` ### Behavior 1. Generates an auth token and calls `modal.Sandbox.create.aio` with command `/usr/bin/env bash -c "swerex-remote --port 8880 --auth-token TOKEN || pipx run swe-rex --port 8880 --auth-token TOKEN"`. 2. Acquires the tunnel for port `8880`. 3. Builds `RemoteRuntime(host=tunnel.url, timeout=self._runtime_timeout, auth_token=token, logger=...)`. 4. Waits `remaining_startup_timeout = max(0, startup_timeout - sandbox_creation_elapsed)` seconds for the runtime to become alive. ### Errors - **Warning** - If already started: "Deployment is already started. Ignoring duplicate start() call." ### Source `src/swerex/deployment/modal.py:208`. ``` -------------------------------- ### Usage example: connect to a running swerex-remote server Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/remote-deployment.md Shows how to create a RemoteDeployment, start it, check aliveness, create a session, run a command, and stop. Requires a swerex-remote server already running at the specified host and port. ```python import asyncio from swerex.deployment.remote import RemoteDeployment from swerex.runtime.abstract import BashAction, CreateBashSessionRequest async def main() -> None: # Connect to a swerex-remote server that is already running deployment = RemoteDeployment( auth_token="my-token", host="http://127.0.0.1", port=8000, timeout=1.0, ) await deployment.start() alive = await deployment.is_alive() if not alive: print("server unreachable:", alive.message) await deployment.stop() return runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) obs = await runtime.run_in_session(BashAction(command="echo connected")) print(obs.output) await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### Initialize and run a Docker deployment Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/docker-deployment.md Demonstrates how to configure a DockerDeployment, start it, create a bash session, and execute commands. ```python import asyncio from swerex.deployment.docker import DockerDeployment from swerex.runtime.abstract import BashAction, Command, CreateBashSessionRequest async def main() -> None: deployment = DockerDeployment( image="python:3.12", startup_timeout=300, pull="missing", container_runtime="docker", docker_args=["--shm-size=2g"], ) await deployment.start() try: runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) obs = await runtime.run_in_session(BashAction(command="uname -a && ls")) print(obs.output) finally: await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### Install development version from source Source: https://github.com/swe-agent/swe-rex/blob/main/docs/installation.md Clone the repository and install the latest development version in editable mode with dev dependencies. ```bash git clone https://github.com/SWE-agent/swe-rex cd swe-rex pip install -e '.[dev]' ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/swe-agent/swe-rex/blob/main/docs/installation.md Install pre-commit hooks for contributing to the project. ```bash pre-commit install ``` -------------------------------- ### FargateDeployment error handling example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/fargate-deployment.md Demonstrates handling errors when using FargateDeployment. Accessing is_alive before start raises DeploymentNotStartedError, and accessing runtime before start raises RuntimeError with message 'Runtime not started'. Startup failures (e.g., missing AWS credentials, port conflicts) surface as ConnectionErrors or TimeoutError from helpers or _wait_until_alive during start(). ```python from swerex.exceptions import DeploymentNotStartedError async def demo() -> None: dep = FargateDeployment(image="python:3.11") try: await dep.is_alive() except DeploymentNotStartedError: print("not started") try: _ = dep.runtime except RuntimeError as e: # implemented as RuntimeError("Runtime not started") print(e) # Startup failures (missing AWS credentials, port conflicts, etc.) # surface as ConnectionErrors / TimeoutError from the helpers or # from _wait_until_alive during start(). ``` -------------------------------- ### Error-handling example with DeploymentNotStartedError and is_alive() Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/abstract-deployment.md Shows error handling for AbstractDeployment: accessing runtime before start() raises DeploymentNotStartedError, and is_alive() returns a status with a message when the deployment is not ready. ```python from swerex.exceptions import DeploymentNotStartedError async def guard(deployment) -> None: # Accessing the runtime before start() raises try: _ = deployment.runtime except DeploymentNotStartedError: print("not started yet") alive = await deployment.is_alive() if not alive: print("deployment not ready:", alive.message) ``` -------------------------------- ### LocalDeployment start Method Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Initializes the internal LocalRuntime instance. ```python async def start(self): ``` -------------------------------- ### start method Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/docker-deployment.md Executes the container startup sequence including image pulling, optional build, port assignment, and runtime initialization. ```python async def start(self): ``` ```text {runtime} run [--rm] -p {port}:8000 [--platform ...] [docker_args...] --name {container_name} {image} {exec_shell...} '' ``` -------------------------------- ### LocalRuntime usage example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/abstract-runtime.md Demonstrates initializing a LocalRuntime, creating a session, executing bash commands, and running direct commands. ```python import asyncio from swerex.runtime.local import LocalRuntime from swerex.runtime.abstract import ( BashAction, CreateBashSessionRequest, Command, ) async def main() -> None: runtime = LocalRuntime() await runtime.is_alive() await runtime.create_session(CreateBashSessionRequest(session="shell")) obs = await runtime.run_in_session( BashAction(command="export MSG='hello' && echo $MSG", session="shell") ) print(obs.output, obs.exit_code) # hello 0 cmd = await runtime.execute(Command(command=["echo", "hi"], shell=False)) print(cmd.stdout, cmd.exit_code) await runtime.close_session(CreateBashSessionRequest(session="shell")) await runtime.close() asyncio.run(main()) ``` -------------------------------- ### Initialize and start ModalDeployment Source: https://github.com/swe-agent/swe-rex/blob/main/docs/usage.md Configures a ModalDeployment with a specific Python image and timeouts, then starts the deployment and verifies its status. ```python from swerex.deployment.modal import ModalDeployment async def run_modal_deployment(): deployment = ModalDeployment( image="python:3.12", startup_timeout=60, # wait 1 minute for deployment to start deployment_timeout=3600, # kill deployment after 1 hour ) await deployment.start() await deployment.is_alive() return deployment deployment = asyncio.run(run_modal_deployment()) asyncio.run(run_some_stuff(deployment)) ``` -------------------------------- ### Usage example (interface-level) with AbstractDeployment Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/abstract-deployment.md Shows the interface-level usage of AbstractDeployment: start the deployment, create a bash session, run commands, and stop in a finally block. Uses DockerDeployment with image python:3.12 as the concrete implementation. ```python import asyncio from swerex.deployment.docker import DockerDeployment from swerex.deployment.abstract import AbstractDeployment from swerex.runtime.abstract import BashAction, CreateBashSessionRequest, Command async def agent_loop(deployment: AbstractDeployment) -> None: await deployment.start() try: runtime = deployment.runtime await runtime.create_session(CreateBashSessionRequest()) for command in ["ls -la", "pwd"]: obs = await runtime.run_in_session(BashAction(command=command)) print(obs.output) finally: await deployment.stop() asyncio.run(agent_loop(DockerDeployment(image="python:3.12"))) ``` -------------------------------- ### Error-handling example: DeploymentNotStartedError on stop Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/remote-deployment.md Shows that calling stop() before start() raises DeploymentNotStartedError, which can be caught and handled. ```python from swerex.exceptions import DeploymentNotStartedError async def demo() -> None: deployment = RemoteDeployment(auth_token="x") try: await deployment.stop() except DeploymentNotStartedError as e: print("cannot stop before start:", e) ``` -------------------------------- ### DummyRuntime usage example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-runtime.md Demonstrates how to use DummyRuntime with a single canned response and with a queue of responses. The example creates a runtime, sets run_in_session_outputs, creates a session, and runs commands, printing outputs and exit codes. ```python import asyncio from swerex.runtime.dummy import DummyRuntime from swerex.runtime.abstract import BashAction, BashObservation, CreateBashSessionRequest async def main() -> None: runtime = DummyRuntime() # Case 1: a single canned response returned every time runtime.run_in_session_outputs = BashObservation(output="fake", exit_code=0) await runtime.create_session(CreateBashSessionRequest()) obs = await runtime.run_in_session(BashAction(command="echo hi")) print(obs.output, obs.exit_code) # fake 0 # Case 2: a queue of responses, consumed in order runtime.run_in_session_outputs = [ BashObservation(output="first", exit_code=0), BashObservation(output="second", exit_code=1), ] print((await runtime.run_in_session(BashAction(command="a"))).output) # first print((await runtime.run_in_session(BashAction(command="b"))).exit_code) # 1 asyncio.run(main()) ``` -------------------------------- ### Usage example: config-driven deployment construction Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/deployment-config.md Config-driven construction example: creates a Docker deployment with a Python 3.12 image, a 300-second startup timeout, always pulling, and removing images after use. ```python from swerex.deployment.config import DockerDeploymentConfig, get_deployment deployment = get_deployment( DockerDeploymentConfig( image="python:3.12", startup_timeout=300.0, pull="always", remove_images=True, ) ) # `deployment` is a DockerDeployment ``` -------------------------------- ### Create DockerDeploymentConfig and get deployment Source: https://github.com/swe-agent/swe-rex/blob/main/docs/api/deployments/config.md Creates a Docker deployment configuration with a Python 3.11 image and obtains the deployment object. Use this as a starting point for configuring deployments with the swerex library. ```python from swerex.deployment.config import DockerDeploymentConfig config = DockerDeploymentConfig(image="python:3.11") deployment = config.get_deployment() ``` -------------------------------- ### Handle ModalDeployment errors and lifecycle Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/modal-deployment.md Demonstrates how to handle DeploymentNotStartedError when accessing the runtime before starting, and how the start method handles duplicate calls. ```python from swerex.exceptions import DeploymentNotStartedError async def demo() -> None: deployment = ModalDeployment(image="python:3.12") try: _ = deployment.runtime except DeploymentNotStartedError: print("start() first") try: await deployment.start() await deployment.start() # duplicate start is tolerated except Exception as e: print("startup failed (e.g. Modal auth):", e) ``` -------------------------------- ### FargateDeployment.start Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/fargate-deployment.md Starts the Fargate deployment by provisioning AWS resources and launching the task. ```APIDOC ## FargateDeployment.start ### Description Starts the deployment. Performs AWS initialization: creates/reuses ECS cluster, IAM role, task definition, VPC/subnet, security group, and container name. Then runs the Fargate task and waits for it to become alive. ### Method Async Method ### Signature ```python async def start(self): ``` ### Steps 1. get_cluster_arn(cluster_name) - create or reuse ECS cluster. 2. get_execution_role_arn(execution_role_prefix) - create/reuse IAM role. 3. get_task_definition(image_name, port, execution_role_arn, task_definition_prefix, log_group) - register/reuse task definition. 4. get_default_vpc_and_subnet() - find default VPC and first subnet. 5. get_security_group(vpc_id, port, security_group_prefix) - create/reuse security group. 6. get_container_name(image). Then builds command and runs Fargate task, waits for RUNNING, gets public IP, creates RemoteRuntime, and waits for runtime to become alive. ### Source `src/swerex/deployment/fargate.py:123` ``` -------------------------------- ### Raw End-to-End Server Interaction Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/endpoints.md Demonstrates starting the server with authentication and performing basic operations including checking status, creating a session, and running a command. ```bash # Start the server with auth swerex-remote --host 0.0.0.0 --port 8000 --auth-token my-secret # In another shell: curl -s http://127.0.0.1:8000/is_alive -H "X-API-Key: my-secret" # {"is_alive":true,"message":""} curl -s -X POST http://127.0.0.1:8000/create_session \ -H "X-API-Key: my-secret" -H "Content-Type: application/json" \ -d '{"session": "default", "session_type": "bash"}' # {"output":"","session_type":"bash"} curl -s -X POST http://127.0.0.1:8000/run_in_session \ -H "X-API-Key: my-secret" -H "Content-Type: application/json" \ -d '{"command": "echo hi", "action_type": "bash", "check": "silent"}' # {"output":"hi\n","exit_code":0,"failure_reason":"","expect_string":"SHELLPS1PREFIX","session_type":"bash"} ``` -------------------------------- ### Install SWE-ReX with pip Source: https://github.com/swe-agent/swe-rex/blob/main/README.md Install SWE-ReX with pip. Optional extras include modal, fargate, daytona (WIP), and dev for all optional dependencies. ```bash pip install swe-rex # With modal support pip install 'swe-rex[modal]' # With fargate support pip install 'swe-rex[fargate]' # With daytona support (WIP) pip install 'swe-rex[daytona]' # Development setup (all optional dependencies) pip install 'swe-rex[dev]' ``` -------------------------------- ### LocalRuntime usage example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-runtime.md Demonstrates initializing a local runtime, executing persistent bash commands, and performing file read/write operations. ```python import asyncio from swerex.runtime.local import LocalRuntime from swerex.runtime.abstract import ( BashAction, Command, CreateBashSessionRequest, ReadFileRequest, WriteFileRequest, ) async def main() -> None: runtime = LocalRuntime() await runtime.create_session(CreateBashSessionRequest(startup_timeout=2.0)) # State persists between run_in_session calls obs1 = await runtime.run_in_session(BashAction(command="echo 1 >> /tmp/out")) obs2 = await runtime.run_in_session(BashAction(command="cat /tmp/out")) print(obs2.output) # "1" # README-style file round-trip await runtime.write_file(WriteFileRequest(content="abc", path="/tmp/f.txt")) content = await runtime.read_file(ReadFileRequest(path="/tmp/f.txt")) print(content.content) # "abc" await runtime.close() asyncio.run(main()) ``` -------------------------------- ### BashSession start Method Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-runtime.md Spawns the bash process, sources startup files, and resets prompt variables. Returns the startup output. ```python async def start(self) -> CreateBashSessionResponse: ``` -------------------------------- ### DeploymentHook Usage Example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/deployment-hooks.md Demonstrates creating a custom hook by subclassing DeploymentHook and registering it with a DockerDeployment. ```python import asyncio from swerex.deployment.docker import DockerDeployment from swerex.deployment.hooks.abstract import DeploymentHook class PrintingHook(DeploymentHook): def on_custom_step(self, message: str): print(f"[progress] {message}") async def main() -> None: deployment = DockerDeployment(image="python:3.12") deployment.add_hook(PrintingHook()) await deployment.start() # prints [progress] Pulling container image, [progress] Starting runtime await deployment.stop() asyncio.run(main()) ``` -------------------------------- ### Usage example with RemoteRuntimeConfig and get_runtime Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/runtime-config.md Shows how to create a remote runtime via get_runtime with a RemoteRuntimeConfig. The resulting runtime is ready for await runtime.is_alive(). ```python from swerex.runtime.config import RemoteRuntimeConfig, get_runtime runtime = get_runtime( RemoteRuntimeConfig( host="http://1.2.3.4", port=8000, auth_token="my-token", timeout=1.0, ) ) # runtime is now a RemoteRuntime, ready for await runtime.is_alive() ``` -------------------------------- ### LocalDeployment.runtime (property) Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Returns the LocalRuntime instance, raising DeploymentNotStartedError if not started. ```APIDOC ## LocalDeployment.runtime (property) ### Description Returns the LocalRuntime instance. Raises DeploymentNotStartedError if the deployment has not been started. ### Method property ### Signature ```python @property def runtime(self) -> LocalRuntime: ``` n ### Returns - **LocalRuntime** - The underlying runtime. ### Raises - **DeploymentNotStartedError** - If runtime is not started. ### Source `src/swerex/deployment/local.py:64` ``` -------------------------------- ### Usage example (find_free_port + get_logger) Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/utils.md Shows how to obtain a free port and create a logger with an emoji prefix. The logger is configured with the name "my-app" and the emoji "🦖". The debug message uses the port value returned by find_free_port. ```python from swerex.utils.free_port import find_free_port from swerex.utils.log import get_logger logger = get_logger("my-app", emoji="🦖") port = find_free_port() logger.debug("using port %d", port) ``` -------------------------------- ### Runtime error-handling example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/abstract-runtime.md Shows how to handle session errors, silence non-zero exit code exceptions, and catch specific NonZeroExitCodeError exceptions. ```python from swerex.exceptions import NonZeroExitCodeError, SessionDoesNotExistError async def probe(runtime) -> None: # 1. Non-zero exit with the default check="raise" try: await runtime.run_in_session(BashAction(command="false; true", session="missing")) except SessionDoesNotExistError: print("session does not exist") # 2. Silence the factory by using check="silent" — you still get exit_code obs = await runtime.run_in_session(BashAction(command="false", check="silent")) print(obs.exit_code) # 1 # 3. NonZeroExitCodeError is what check="raise" produces await runtime.create_session(CreateBashSessionRequest()) try: await runtime.run_in_session(BashAction(command="exit 3")) except NonZeroExitCodeError as e: print(f"failed: {e}") ``` -------------------------------- ### DummyDeployment.runtime property Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-deployment.md Gets or sets the DummyRuntime instance. The setter allows injecting a pre-configured runtime. ```APIDOC ## Property: runtime ### Description Gets or sets the `DummyRuntime` instance. The setter allows injecting a pre-configured runtime (e.g., one with `run_in_session_outputs` primed). ### Getter ```python @property def runtime(self) -> DummyRuntime: return self._runtime ``` ### Setter ```python @runtime.setter def runtime(self, runtime: DummyRuntime): self._runtime = runtime ``` ### Source `src/swerex/deployment/dummy.py:43` and `:48` ``` -------------------------------- ### GET / Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/endpoints.md Liveness and hello endpoint that returns a simple JSON message. Authentication is optional unless an auth token is configured. ```APIDOC ## GET / ### Description Liveness/hello endpoint that returns a simple JSON message. ### Method GET ### Endpoint / ### Authentication Optional (unless `AUTH_TOKEN` set) ### Response #### Success Response (200) - **message** (string) - Always set to "hello world". #### Response Example { "message": "hello world" } ``` -------------------------------- ### Run SWE-ReX with DockerDeployment Source: https://github.com/swe-agent/swe-rex/blob/main/docs/usage.md Use this snippet to run the same run_some_stuff function with a DockerDeployment instead of a LocalDeployment. It pulls the python:3.12 image, starts a container, and runs swerex-remote inside it via pipx. The output shows the container startup logs and the results of the commands executed. ```python from swerex.deployment.docker import DockerDeployment deployment = DockerDeployment(image="python:3.12") asyncio.run(run_some_stuff(deployment)) ``` ```text 🦖 DEBUG Ensuring deployment is stopped because object is deleted 🦖 INFO Pulling image 'python:3.12' 🦖 DEBUG Found free port 59647 🦖 INFO Starting container python3.12-608e9964-2a5e-409b-a7b7-52b520034068 with image python:3.12 serving on port 59647 🦖 DEBUG Command: "docker run --rm -p 59647:8000 --name python3.12-608e9964-2a5e-409b-a7b7-52b520034068 python:3.12 /bin/sh -c 'swerex-remote --auth-token 1d87776a-1ab2-422e-bd80-fc34d810633f || (python3 -m pip install pipx && python3 -m pipx ensurepath && pipx run 0fdb5604 --auth-token 1d87776a-1ab2-422e-bd80-fc34d810633f)'" 🦖 INFO Starting runtime at 59647 🦖 INFO Runtime started in 18.78s stdout='Hello, world!\n' stderr='' exit_code=0 output='' exit_code=0 failure_reason='' expect_string='SHELLPS1PREFIX' session_type='bash' output='test' exit_code=0 failure_reason='' expect_string='SHELLPS1PREFIX' session_type='bash' ``` -------------------------------- ### LocalRuntime error-handling example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-runtime.md Shows how to catch specific exceptions like SessionExistsError, CommandTimeoutError, and BashIncorrectSyntaxError when interacting with the runtime. ```python from swerex.exceptions import ( BashIncorrectSyntaxError, CommandTimeoutError, SessionExistsError, ) async def demonstrate_errors(runtime) -> None: await runtime.create_session(CreateBashSessionRequest()) try: await runtime.create_session(CreateBashSessionRequest()) # duplicate except SessionExistsError: print("duplicate session rejected") try: # pexpect never sees the PS1 for a command that sleeps past the timeout await runtime.run_in_session(BashAction(command="sleep 100", timeout=1.0)) except CommandTimeoutError: print("command timed out") # Syntax check runs before execution: an unterminated quote is rejected try: await runtime.run_in_session(BashAction(command="echo 'unterminated")) except BashIncorrectSyntaxError as e: print("syntax error:", e.extra_info) # {"bash_stdout": ..., "bash_stderr": ...} ``` -------------------------------- ### Embedded ASGI app usage example Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/server.md Shows how to embed the SWE-ReX ASGI app in-process and test it with httpx. Sets AUTH_TOKEN before making requests and calls /is_alive with the X-API-Key header. The response is printed as {"is_alive": true, "message": ""}. ```python import httpx from swerex.server import app, AUTH_TOKEN # Determine the token before making requests AUTH_TOKEN = "my-token" async def demo() -> None: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: r = await client.get("/is_alive", headers={"X-API-Key": "my-token"}) print(r.json()) # {"is_alive": true, "message": ""} ``` -------------------------------- ### CLI main() for SWE-ReX server Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/server.md Defines the CLI entry point for the SWE-ReX server. Requires --auth-token, defaults host to 0.0.0.0 and port to 8000. Also supports -v/--version, which errors with "Error: --version cannot be combined with other arguments" and exit code 1 when combined with other arguments. Runs uvicorn.run(app, host=..., port=...) with AUTH_TOKEN set from --auth-token. ```python def main(): parser = argparse.ArgumentParser(description="Run the SWE-ReX server") parser.add_argument("--host", default="0.0.0.0", help="Host to bind the server to") parser.add_argument("--port", type=int, default=8000, help="Port to run the server on") parser.add_argument("--auth-token", default="", help="token to authenticate requests", required=True) ``` -------------------------------- ### LocalDeployment is_alive Method Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Checks if the runtime is active. Returns False before start() is called and delegates to the runtime after start(). ```python async def is_alive(self, *, timeout: float | None = None) -> IsAliveResponse: ``` -------------------------------- ### LocalDeployment.is_alive Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/local-deployment.md Checks if the deployment is alive. Before start, returns is_alive=False with a message. After start, delegates to the runtime's is_alive method. ```APIDOC ## LocalDeployment.is_alive ### Description Checks if the deployment is alive. Before start(), returns IsAliveResponse(is_alive=False, message="Runtime is None.") without raising. After start(), delegates to LocalRuntime.is_alive which always returns is_alive=True. ### Method async is_alive ### Signature ```python async def is_alive(self, *, timeout: float | None = None) -> IsAliveResponse: ``` n ### Parameters - **timeout** (float | None) - Optional - Timeout for the check. ### Returns - **IsAliveResponse** - Response indicating aliveness status. ### Source `src/swerex/deployment/local.py:43` ``` -------------------------------- ### GET /is_alive Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/remote-runtime.md Checks whether the remote runtime is alive. Sends a GET request to /is_alive with a configurable timeout and parses the response into an IsAliveResponse, handling various status codes and errors. ```APIDOC ## GET /is_alive ### Description Checks if the remote runtime is alive. Returns an IsAliveResponse indicating status. ### Method GET ### Endpoint /is_alive ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **IsAliveResponse** - Parsed response body. #### Response Example { "is_alive": true, "message": "" } #### Error Response (511) Re-raises the transferred server exception. #### Error Response (other status) - **is_alive** (boolean) - false - **message** (string) - "Status code ... Message: {detail}" #### Error Response (client error or exception) - **is_alive** (boolean) - false - **message** (string) - Full traceback string. ``` -------------------------------- ### Error-handling example for DummyOutputsExhaustedError Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-deployment.md Error-handling example showing how to catch DummyOutputsExhaustedError when the runtime's output queue is empty. It sets run_in_session_outputs to an empty list and attempts a run_in_session call, printing the exception message. ```python from swerex.runtime.abstract import BashAction from swerex.exceptions import DummyOutputsExhaustedError async def demo() -> None: deployment = DummyDeployment() # Inject a runtime that will exhaust its queue deployment.runtime.run_in_session_outputs = [] try: await deployment.runtime.run_in_session(BashAction(command="echo hi")) except DummyOutputsExhaustedError as e: print("exhausted:", e) ``` -------------------------------- ### DummyDeployment.__init__ Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-deployment.md Constructor for DummyDeployment. Accepts an optional logger and keyword arguments forwarded to DummyDeploymentConfig. ```APIDOC ## Constructor: DummyDeployment.__init__ ### Description Initializes a DummyDeployment instance. The runtime is created eagerly. Optional logger and configuration keyword arguments are accepted. ### Method Constructor ### Signature ```python def __init__(self, *, logger: logging.Logger | None = None, **kwargs: Any): ``` ### Parameters - **logger** (`logging.Logger | None`) - Optional - Falls back to `get_logger("rex-deploy")`. - **kwargs** (`Any`) - Optional - Forwarded to `DummyDeploymentConfig(**kwargs)` (only `type` is allowed). ### Source `src/swerex/deployment/dummy.py:14` ``` -------------------------------- ### DummyRuntime.__init__ Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-runtime.md Constructor for DummyRuntime. Initializes the runtime with an optional logger and forwards additional keyword arguments to DummyRuntimeConfig. ```APIDOC ## DummyRuntime.__init__ ### Description Constructor for DummyRuntime. Initializes the runtime with an optional logger and forwards additional keyword arguments to DummyRuntimeConfig. ### Method Constructor ### Signature python def __init__( self, *, logger: logging.Logger | None = None, **kwargs: Any, ): ### Parameters - **logger** (`logging.Logger | None`) - Optional - Falls back to `get_logger("rex-runtime")`. - **kwargs** (`Any`) - Optional - Forwarded to `DummyRuntimeConfig(**kwargs)`. ### Source `src/swerex/runtime/dummy.py:33` ``` -------------------------------- ### runtime Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/daytona-deployment.md Property that returns the RemoteRuntime instance, raising if not started. ```APIDOC ```python @property def runtime(self) -> RemoteRuntime: ``` ### Description Provides access to the underlying RemoteRuntime object. Raises `RuntimeError` if the runtime has not been started. ### Returns - `RemoteRuntime` - The runtime instance. ### Raises - `RuntimeError("Runtime not started")` if `_runtime` is `None`. ``` -------------------------------- ### ModalDeployment.__init__ Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/modal-deployment.md Constructor for ModalDeployment. Initializes a deployment that runs the SWE-ReX server in a Modal sandbox, with configurable image, timeouts, and sandbox options. ```APIDOC ## ModalDeployment.__init__ ### Description Constructor for ModalDeployment. Initializes a deployment that runs the SWE-ReX server in a Modal sandbox, with configurable image, timeouts, and sandbox options. ### Method Constructor ### Signature ```python def __init__( self, *, logger: logging.Logger | None = None, image: str | modal.Image | PurePath, startup_timeout: float = 0.4, runtime_timeout: float = 3600.0, modal_sandbox_kwargs: dict[str, Any] | None = None, install_pipx: bool = True, deployment_timeout: float = 3600.0, ): ``` ### Parameters - **logger** (logging.Logger | None) - Optional - Falls back to `get_logger("rex-deploy")`. - **image** (str | modal.Image | PurePath) - Required - One of: a `modal.Image`; a path to a Dockerfile; a Docker Hub image name; an ECR image name (contains `amazonaws.com`). - **startup_timeout** (float) - Optional - Seconds to wait for the runtime to become alive (after sandbox creation); note that `ModalDeploymentConfig.startup_timeout` defaults to `180.0` and overrides this when constructed via `from_config`. - **runtime_timeout** (float) - Optional - Timeout for runtime requests; config default is `60.0`. - **modal_sandbox_kwargs** (dict[str, Any] | None) - Optional - Extra kwargs for `modal.Sandbox.create`. - **install_pipx** (bool) - Optional - Install `pipx` via apt so the `pipx run swe-rex` fallback works in the sandbox. - **deployment_timeout** (float) - Optional - Kill-switch: sandbox is created with this as its timeout. ### Notes - The class constructor defaults (`startup_timeout=0.4`, `runtime_timeout=3600.0`) differ from `ModalDeploymentConfig` defaults (`startup_timeout=180.0`, `runtime_timeout=60.0`, both with `deployment_timeout=3600.0`). `from_config` passes the config values through explicitly, so constructing via `get_deployment(config)` uses the config defaults, while `ModalDeployment(image="...")` uses the constructor defaults. ``` -------------------------------- ### runtime property Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/docker-deployment.md Returns the RemoteRuntime instance or raises DeploymentNotStartedError if not started. ```python @property def runtime(self) -> RemoteRuntime: ``` -------------------------------- ### container_name property Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/docker-deployment.md Returns the generated container name or None before start(). ```python @property def container_name(self) -> str | None: ``` -------------------------------- ### DaytonaDeployment.runtime property Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/daytona-deployment.md Property that returns the RemoteRuntime, raising RuntimeError if not started. ```python @property def runtime(self) -> RemoteRuntime: ``` -------------------------------- ### DockerDeployment.__init__ Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/docker-deployment.md Initializes a DockerDeployment instance. Accepts an optional logger and keyword arguments that are forwarded to DockerDeploymentConfig. ```APIDOC ## DockerDeployment.__init__ ### Description Initializes a DockerDeployment instance. Accepts an optional logger and keyword arguments that are forwarded to DockerDeploymentConfig. ### Method Constructor ### Signature ```python def __init__( self, *, logger: logging.Logger | None = None, **kwargs: Any, ): ``` ### Parameters - **logger** (logging.Logger | None) - Optional - Falls back to get_logger("rex-deploy"). - **kwargs** (Any) - Optional - Forwarded to DockerDeploymentConfig(**kwargs). ``` -------------------------------- ### get_logger Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/utils.md Function to get a configured logger with emoji-styled rich handler. ```APIDOC ## get_logger(name: str, *, emoji: str = "🦖") -> logging.Logger ### Description Returns a configured `logging.Logger` with a `_RichHandlerWithEmoji` handler, `propagate=False`, and honoring environment variables. Idempotent: loggers that already have handlers are returned as-is. ### Parameters - `name` (str) - Required - Logger name; in non-main threads the name is suffixed with the thread name. - `emoji` (str) - Optional - Emoji prefix for the rich stream handler. Default: `"🦖"`. ### Environment Variables - `SWE_REX_LOG_STREAM_LEVEL` - Stream handler level: numeric or a level name (e.g. `DEBUG`, `WARNING`); default is `logging.DEBUG` (10). - `SWE_AGENT_LOG_TIME` - When truthy, shows per-record timestamps (`show_time=True`). ### Returns A configured `logging.Logger` instance. ``` -------------------------------- ### DummyDeployment.from_config Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-deployment.md Classmethod that builds a DummyDeployment from a DummyDeploymentConfig instance. ```APIDOC ## Classmethod: DummyDeployment.from_config ### Description Builds a DummyDeployment from a DummyDeploymentConfig. ### Method Classmethod ### Signature ```python @classmethod def from_config(cls, config: DummyDeploymentConfig) -> Self: ``` ### Parameters - **config** (`DummyDeploymentConfig`) - Required - The configuration object used to build the deployment. ``` -------------------------------- ### DummyRuntime.from_config classmethod Source: https://github.com/swe-agent/swe-rex/blob/main/_autodocs/api-reference/dummy-runtime.md Builds a DummyRuntime from a DummyRuntimeConfig instance by passing the config's model_dump() as keyword arguments to the constructor. ```python @classmethod def from_config(cls, config: DummyRuntimeConfig) -> Self: ```