Have you ever wondered how to run AI-generated code in production safely? In this post, we'll walk you through how we built a secure runtime environment for OpenHands using Daytona sandboxes, creating a practical solution for AI-driven development.
Whether you're building AI assistants or automated code generation tools, understanding how to securely execute AI-generated code is crucial for modern development workflows.
Understanding OpenHands Runtimes
OpenHands runtimes are special environments where AI agents can edit files and execute commands. Think of them as controlled sandboxes where the AI can safely interact with code and system resources. While OpenHands typically uses Docker by default, it's designed to work with different types of runtimes, including remote options that make it easier to scale and secure your operations.
A runtime in OpenHands needs to provide:
A secure environment for code execution
File system operations capabilities
Session management for running commands
Integration with the OpenHands agent system
Why Daytona Sandboxes?
Daytona sandboxes are perfect for running AI-generated code safely. The key advantage? They let you offload all code execution to Daytona's cloud infrastructure. What makes them special is that they're stateful environments that can live as long as you need them to. This means your AI-generated code can maintain its state, store data, and run persistent services. Plus, with built-in application preview capabilities, you can instantly see the output of any web applications your AI creates.
Here's what makes Daytona sandboxes perfect for running AI-generated code:
Cloud Execution: All compute-heavy tasks run in Daytona's cloud, not on your local machine. This means you can run multiple AI agents simultaneously without performance bottlenecks.
Isolation: Each sandbox runs in its own bubble in the cloud, keeping your systems safe from any unexpected AI-generated code behavior.
Stateful Nature: Unlike typical sandboxes that reset after each use, Daytona sandboxes maintain their state between sessions. Your AI can save files, keep configurations, and run long-term processes.
Long-Living Sessions: Sandboxes can stay alive indefinitely - perfect for running AI-generated services or applications that need to persist.
Live Preview: Built-in preview functionality lets you instantly see AI-generated web applications in action, making testing and iteration a breeze.
Resource Management: You can control exactly how much CPU, memory, and storage each sandbox uses. You can scale up or down based on your needs without managing infrastructure.
Built-in Security: Comes with all the security features you need, from process isolation to resource limits. Your AI agents can run code safely without affecting each other or your main systems.
Building the Daytona Runtime
We used the Daytona SDK to create a new runtime for OpenHands. Let's look at how the pieces fit together:
Core Components
The DaytonaRuntime class handles all the sandbox creation and management:
1class DaytonaRuntime(ActionExecutionClient):2 def __init__(self, config: AppConfig, event_stream: EventStream, ...):3 # Set up Daytona configuration4 daytona_config = DaytonaConfig(5 api_key=config.daytona_api_key.get_secret_value(),6 server_url=config.daytona_api_url,7 target=config.daytona_target,8 )9 self.daytona = Daytona(daytona_config)
Sandbox Creation
Each OpenHands session gets its own isolated sandbox:
1def _create_sandbox(self) -> Sandbox:2 sandbox_params = CreateSandboxParams(3 id=self.sandbox_id,4 language='python',5 image=self.config.sandbox.runtime_container_image,6 public=True,7 env_vars=self._get_creation_env_vars(),8 )9 return self.daytona.create(sandbox_params)
Session Management
Here's how we handle running commands in the sandbox:
1def _start_action_execution_server(self) -> None:2 exec_session_id = 'action-execution-server'3 self.sandbox.process.create_session(exec_session_id)4 # Run commands within the session5 self.sandbox.process.execute_session_command(6 exec_session_id,7 SessionExecuteRequest(command=start_command_str, var_async=True),8 )
Cool Features We've Built In
Smart Resource Management: The runtime handles sandbox creation and cleanup automatically - no manual work needed.
Safe Command Execution: All commands run in isolated sessions, so there's no risk of affecting other parts of your system.
VSCode Integration: You can use VSCode to interact with your environment:
1@property2def vscode_url(self) -> str | None:3 if self._vscode_url is not None:4 return self._vscode_url5 token = super().get_vscode_token()6 # Create VSCode URL with access token7 self._vscode_url = self._construct_api_url(self._vscode_port) + f'/?tkn={token}'8 return self._vscode_url
Smart Error Handling: The runtime knows how to handle hiccups and retry when needed:
1@tenacity.retry(2 stop=tenacity.stop_after_delay(120) | stop_if_should_exit(),3 wait=tenacity.wait_fixed(1),4 reraise=(ConnectionRefusedError,),5)6def _wait_until_alive(self):7 super().check_if_alive()
Why Use Daytona Runtime in OpenHands?
Rock-Solid Security: All code runs in isolated sandboxes, so your system stays safe.
Easy Scaling: Run multiple sessions at once without breaking a sweat.
Developer-Friendly: Use VSCode just like you normally would.
Resource-Smart: Automatically cleans up after itself to keep your system running smoothly.
Local-Like Development: Even though code runs in the cloud, you can preview applications on your local machine ports. This means you can access AI-generated web apps at localhost:3000 just like you would with local development - no complicated tunneling or port forwarding needed.
Getting Started with OpenHands and Daytona
1. Set Your API Key as an Environment Variable:
Run the following command in your terminal, replacing <your-api-key> with the actual key you copied:
1export DAYTONA_API_KEY="<your-api-key>"
2. Run OpenHands Locally Using Docker:
To start the latest version of OpenHands on your machine, execute the following command in your terminal:
1bash -i <(curl -sL https://get.daytona.io/openhands)
Daytona for Openhands Has Got Your Back
By combining Daytona sandboxes with OpenHands, we've created a secure and practical environment for AI-driven development. Our implementation makes it easy to work with AI-generated code while keeping your systems safe and performing well.
This is just the beginning—we're excited to see how developers will use this setup to build even cooler AI-powered tools and workflows. Whether you're working on AI coding assistants or automated code generation, the Daytona runtime for OpenHands has got your back.