Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Dockerfile+26-22
- README.md+85-38
- __init__.pyAdded+12
- client.pyAdded+56
- envs/coding_env/README.mdAdded+163
- envs/coding_env/__init__.pyAdded+12
- envs/coding_env/client.pyAdded+56
- envs/coding_env/models.pyAdded+34
- envs/coding_env/openenv.yamlAdded+5
- envs/coding_env/pyproject.tomlAdded+35
- envs/coding_env/server/DockerfileAdded+35
- envs/coding_env/server/Dockerfile.backupAdded+25
- envs/coding_env/server/README.mdAdded+51
- envs/coding_env/server/__init__.pyAdded+11
- envs/coding_env/server/app.pyAdded+47
- envs/coding_env/server/python_codeact_env.pyAdded+117
- envs/coding_env/server/python_executor.pyAdded+157
- envs/coding_env/server/transforms.pyAdded+94
- models.pyAdded+34
- openenv.yamlAdded+5
- pyproject.tomlAdded+35
- server/DockerfileAdded+35
- server/Dockerfile.backupAdded+25
- server/README.mdAdded+51
- server/__init__.pyAdded+11
- server/app.pyAdded+47
- server/python_codeact_env.pyAdded+117
- server/python_executor.pyAdded+157
- server/transforms.pyAdded+94
- src/__init__.pyAdded+7
- src/core/README.md+53-21
- src/core/__init__.py+70-8
- src/core/client_types.py+3-2
- src/core/containers/__init__.py+1-1
- src/core/containers/images/Dockerfile+29-11
- src/core/containers/images/README.md+8-8
- src/core/containers/runtime/__init__.py+12-2
- src/core/containers/runtime/daytona_provider.pyAdded+572
- src/core/containers/runtime/providers.py+383-7
- src/core/containers/runtime/uv_provider.pyAdded+224
- src/core/containers/test_local_docker_provider.py+8-6
- src/core/env_client.pyAdded+484
- src/core/env_server/__init__.py+118-3
- src/core/env_server/base_transforms.py+1-1
- src/core/env_server/exceptions.pyAdded+105
- src/core/env_server/gradio_theme.pyAdded+128
- src/core/env_server/gradio_ui.pyAdded+240
- src/core/env_server/http_server.py+1263-105
- src/core/env_server/interfaces.py+189-10
- src/core/env_server/mcp_environment.pyAdded+624
12345678910111213141516171819202122232425262728293031# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.# Use the standard openenv base image# Built from: docker build -t openenv-base:latest -f src/core/containers/images/Dockerfile .# In GitHub Actions, this is overridden to use the GHCR base imageARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ghcr.io/meta-pytorch/openenv-base:latest# Install dependenciesCOPY src/envs/coding_env/server/requirements.txt /tmp/requirements.txtRUN pip install --no-cache-dir -r /tmp/requirements.txt && rm /tmp/requirements.txt# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY src/envs/coding_env/ /app/src/envs/coding_env/# Copy README for web interface documentationCOPY src/envs/coding_env/README.md /app/README.md# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD curl -f http://localhost:8000/health || exit 1# Run the FastAPI serverENV ENABLE_WEB_INTERFACE=trueCMD ["uvicorn", "envs.coding_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]1234567891011121314151617181920212223242526272829303132333435# Dockerfile for Coding Environment# Build from repo root:# docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .FROM python:3.11-slim# Set working directoryWORKDIR /app# Install system dependenciesRUN apt-get update && apt-get install -y \git \curl \&& rm -rf /var/lib/apt/lists/*# Copy coding_env packageCOPY envs/coding_env/ ./envs/coding_env/# Install openenv-core first from PyPI, then coding_envRUN pip install --no-cache-dir "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git@main" && \pip install --no-cache-dir ./envs/coding_env/# Environment variablesENV PYTHONUNBUFFERED=1ENV ENABLE_WEB_INTERFACE=true# Expose portEXPOSE 8000# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD curl -f http://localhost:8000/health || exit 1# Run the serverCMD ["uvicorn", "coding_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657581 unmodified line6061626364656621 unmodified lines888990919293949596979899100101102103104105106107108109110111112113---title: Coding Environment Serveremoji: 💻colorFrom: graycolorTo: indigosdk: dockerpinned: falseapp_port: 8000base_path: /webtags:- openenv---# Coding EnvironmentA Python code execution environment that runs arbitrary Python code and returns results. Perfect for testing code execution infrastructure and demonstrating environment usage patterns.## Quick StartThe simplest way to use the Coding environment is through the `CodingEnv` class:```pythonfrom envs.coding_env import CodeAction, CodingEnvtry:# Create environment from Docker imagecoding_env = CodingEnv.from_docker_image("coding-env:latest")# Resetresult = coding_env.reset()print(f"Reset complete: exit_code={result.observation.exit_code}")# Execute Python codecode_samples = ["print('Hello, World!')","x = 5 + 3\nprint(f'Result: {x}')","import math\nprint(math.pi)"]for code in code_samples:result = coding_env.step(CodeAction(code=code))print(f"Code: {code}")print(f" → stdout: {result.observation.stdout.strip()}")print(f" → exit_code: {result.observation.exit_code}")finally:# Always clean upcoding_env.close()```That's it! The `CodingEnv.from_docker_image()` method handles:- Starting the Docker container- Waiting for the server to be ready- Connecting to the environment- Container cleanup when you call `close()`## Building the Docker Image1 unmodified line```bash# From project rootdocker build -t coding-env:latest -f src/envs/coding_env/server/Dockerfile .```## Environment Details21 unmodified linesIf you already have a Coding environment server running, you can connect directly:```pythonfrom envs.coding_env import CodingEnv# Connect to existing servercoding_env = CodingEnv(base_url="<ENV_HTTP_URL_HERE>")# Use as normalresult = coding_env.reset()result = coding_env.step(CodeAction(code="print('Hello!')"))```Note: When connecting to an existing server, `coding_env.close()` will NOT stop the server.## Development & Testing### Running the Full ExampleRun the complete example that demonstrates the full workflow:```bashpython3 src/envs/coding_env/client/example_usage.py```This example shows:12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line8889909192939421 unmodified lines116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160---title: Coding Environment Serveremoji: 💻colorFrom: bluecolorTo: greensdk: dockerpinned: falseapp_port: 8000base_path: /webtags:- openenv-main- openenv---## Hugging Face Space DeploymentThis Space is built from OpenEnv environment `coding_env`.- Space URL: `https://huggingface.co/spaces/openenv/coding_env`- OpenEnv pinned ref: `main`- Hub tag: `openenv`### Connecting from Code```pythonfrom envs.coding_env import CodingEnvenv = CodingEnv(base_url="https://huggingface.co/spaces/openenv/coding_env")```# Coding EnvironmentA Python code execution environment that runs arbitrary Python code and returns results. Perfect for testing code execution infrastructure and demonstrating environment usage patterns.## Quick StartThe simplest way to use the Coding environment is through the `CodingEnv` class. The client is **async by default**:```pythonimport asynciofrom coding_env import CodeAction, CodingEnvasync def main():# Create environment from Docker imageclient = await CodingEnv.from_docker_image("coding-env:latest")async with client:# Resetresult = await client.reset()print(f"Reset complete: exit_code={result.observation.exit_code}")# Execute Python codecode_samples = ["print('Hello, World!')","x = 5 + 3\nprint(f'Result: {x}')","import math\nprint(math.pi)"]for code in code_samples:result = await client.step(CodeAction(code=code))print(f"Code: {code}")print(f" → stdout: {result.observation.stdout.strip()}")print(f" → exit_code: {result.observation.exit_code}")asyncio.run(main())```For **synchronous usage**, use the `.sync()` wrapper:```pythonfrom coding_env import CodeAction, CodingEnvwith CodingEnv(base_url="http://localhost:8000").sync() as client:result = client.reset()result = client.step(CodeAction(code="print('Hello!')"))print(result.observation.stdout)```The `CodingEnv.from_docker_image()` method handles:- Starting the Docker container- Waiting for the server to be ready- Connecting to the environment- Container cleanup when the context manager exits## Building the Docker Image1 unmodified line```bash# From project rootdocker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .```## Environment Details21 unmodified linesIf you already have a Coding environment server running, you can connect directly:```pythonfrom coding_env import CodeAction, CodingEnv# Async usageasync with CodingEnv(base_url="http://localhost:8000") as client:result = await client.reset()result = await client.step(CodeAction(code="print('Hello!')"))# Sync usagewith CodingEnv(base_url="http://localhost:8000").sync() as client:result = client.reset()result = client.step(CodeAction(code="print('Hello!')"))```Note: When connecting to an existing server, closing the client will NOT stop the server.## Development & Testing### Running TestsInstall the coding_env package with dev dependencies and run the tests from the repo root:```bash# Install coding_env with dev dependencies (includes smolagents and pytest)uv pip install -e "envs/coding_env[dev]"# Run unit tests (no Docker required)uv run pytest tests/envs/test_python_codeact_reset.py tests/envs/test_python_codeact_rewards.py -v# Run integration tests (requires Docker image to be built)docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .SKIP_DOCKER_TESTS=0 uv run pytest tests/envs/test_coding_env_integration.py -v```### Running the Full ExampleRun the complete example that demonstrates the full workflow:```bashpython3 envs/coding_env/client/example_usage.py```This example shows:
123456789101112# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Coding Environment - A Python code execution environment."""
from .client import CodingEnvfrom .models import CodeAction, CodeObservation, CodeState
__all__ = ["CodingEnv", "CodeAction", "CodeObservation", "CodeState"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""CodingEnv---------Client-side wrapper for the Coding environment server.
This client maintains a persistent WebSocket connection to the environmentserver, enabling efficient multi-step interactions with lower latency.
- users instantiate CodingEnv with a base_url provided by the higher-level vector/orchestration layer.- Environment authors ship the Docker image that serves the API.
(Seeds, episode IDs, request IDs, capabilities can be added later in the payloads.)"""
from __future__ import annotations
from openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClient
from .models import CodeAction, CodeObservation, CodeState
class CodingEnv(EnvClient[CodeAction, CodeObservation, CodeState]): # --- HTTPEnvClient abstract hooks ---
def _step_payload(self, action: CodeAction) -> dict: # Shape expected by the server's /step endpoint under "action" return { "code": action.code, }
def _parse_result(self, payload: dict) -> StepResult[CodeObservation]: # Expecting: { "observation": {...}, "reward": <float|null>, "done": <bool>, "info": {...} } obs = CodeObservation(**payload["observation"]) return StepResult( observation=obs, reward=payload.get("reward"), done=bool(payload.get("done", False)), )
def _parse_state(self, payload: dict) -> CodeState: """ Parse server response into CodeState object.
Args: payload: JSON response from /state endpoint
Returns: CodeState object with episode_id, step_count, and last_exit_code """ return CodeState( episode_id=payload.get("episode_id"), step_count=payload.get("step_count", 0), last_exit_code=payload.get("last_exit_code", 0), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163---title: Coding Environment Serveremoji: 💻colorFrom: bluecolorTo: bluesdk: dockerpinned: falseapp_port: 8000base_path: /webtags: - openenv---
# Coding Environment
A Python code execution environment that runs arbitrary Python code and returns results. Perfect for testing code execution infrastructure and demonstrating environment usage patterns.
## Quick Start
The simplest way to use the Coding environment is through the `CodingEnv` class. The client is **async by default**:
```pythonimport asynciofrom coding_env import CodeAction, CodingEnv
async def main(): # Create environment from Docker image client = await CodingEnv.from_docker_image("coding-env:latest")
async with client: # Reset result = await client.reset() print(f"Reset complete: exit_code={result.observation.exit_code}")
# Execute Python code code_samples = [ "print('Hello, World!')", "x = 5 + 3\nprint(f'Result: {x}')", "import math\nprint(math.pi)" ]
for code in code_samples: result = await client.step(CodeAction(code=code)) print(f"Code: {code}") print(f" → stdout: {result.observation.stdout.strip()}") print(f" → exit_code: {result.observation.exit_code}")
asyncio.run(main())```
For **synchronous usage**, use the `.sync()` wrapper:
```pythonfrom coding_env import CodeAction, CodingEnv
with CodingEnv(base_url="http://localhost:8000").sync() as client: result = client.reset() result = client.step(CodeAction(code="print('Hello!')")) print(result.observation.stdout)```
The `CodingEnv.from_docker_image()` method handles:- Starting the Docker container- Waiting for the server to be ready- Connecting to the environment- Container cleanup when the context manager exits
## Building the Docker Image
Before using the environment, you need to build the Docker image:
```bash# From project rootdocker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .```
## Environment Details
### Action**CodeAction**: Contains a single field- `code` (str) - The Python code to execute
### Observation**CodeObservation**: Contains the execution results- `stdout` (str) - Standard output from code execution- `stderr` (str) - Standard error from code execution- `exit_code` (int) - Exit code (0 for success, non-zero for errors)
### State**CodeState**: Tracks execution state- `episode_id` (str) - Unique identifier for the episode- `step_count` (int) - Number of steps taken- `last_exit_code` (int) - Exit code from the last execution
## Advanced Usage
### Connecting to an Existing Server
If you already have a Coding environment server running, you can connect directly:
```pythonfrom coding_env import CodeAction, CodingEnv
# Async usageasync with CodingEnv(base_url="http://localhost:8000") as client: result = await client.reset() result = await client.step(CodeAction(code="print('Hello!')"))
# Sync usagewith CodingEnv(base_url="http://localhost:8000").sync() as client: result = client.reset() result = client.step(CodeAction(code="print('Hello!')"))```
Note: When connecting to an existing server, closing the client will NOT stop the server.
## Development & Testing
### Running Tests
Install the coding_env package with dev dependencies and run the tests from the repo root:
```bash# Install coding_env with dev dependencies (includes smolagents and pytest)uv pip install -e "envs/coding_env[dev]"
# Run unit tests (no Docker required)uv run pytest tests/envs/test_python_codeact_reset.py tests/envs/test_python_codeact_rewards.py -v
# Run integration tests (requires Docker image to be built)docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .SKIP_DOCKER_TESTS=0 uv run pytest tests/envs/test_coding_env_integration.py -v```
### Running the Full Example
Run the complete example that demonstrates the full workflow:
```bashpython3 envs/coding_env/client/example_usage.py```
This example shows:- Creating an environment from a Docker image- Resetting and executing code through the environment- Automatic cleanup with `close()`
## Project Structure
```coding_env/├── README.md # This file├── models.py # Action, Observation, and State models├── client/│ ├── coding_env_client.py # CodingEnv client implementation│ └── example_usage.py # Usage examples└── server/ ├── python_codeact_env.py # Core environment logic ├── app.py # FastAPI application ├── transforms.py # Observation transforms ├── Dockerfile # Container image definition └── README.md # Server-specific documentation```123456789101112# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Coding Environment - A Python code execution environment."""
from .client import CodingEnvfrom .models import CodeAction, CodeObservation, CodeState
__all__ = ["CodingEnv", "CodeAction", "CodeObservation", "CodeState"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""CodingEnv---------Client-side wrapper for the Coding environment server.
This client maintains a persistent WebSocket connection to the environmentserver, enabling efficient multi-step interactions with lower latency.
- users instantiate CodingEnv with a base_url provided by the higher-level vector/orchestration layer.- Environment authors ship the Docker image that serves the API.
(Seeds, episode IDs, request IDs, capabilities can be added later in the payloads.)"""
from __future__ import annotations
from openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClient
from .models import CodeAction, CodeObservation, CodeState
class CodingEnv(EnvClient[CodeAction, CodeObservation, CodeState]): # --- HTTPEnvClient abstract hooks ---
def _step_payload(self, action: CodeAction) -> dict: # Shape expected by the server's /step endpoint under "action" return { "code": action.code, }
def _parse_result(self, payload: dict) -> StepResult[CodeObservation]: # Expecting: { "observation": {...}, "reward": <float|null>, "done": <bool>, "info": {...} } obs = CodeObservation(**payload["observation"]) return StepResult( observation=obs, reward=payload.get("reward"), done=bool(payload.get("done", False)), )
def _parse_state(self, payload: dict) -> CodeState: """ Parse server response into CodeState object.
Args: payload: JSON response from /state endpoint
Returns: CodeState object with episode_id, step_count, and last_exit_code """ return CodeState( episode_id=payload.get("episode_id"), step_count=payload.get("step_count", 0), last_exit_code=payload.get("last_exit_code", 0), )12345678910111213141516171819202122232425262728293031323334"""envs/coding_env/models.py--------------------------------Action/Observation types for the Coding environment."""
from __future__ import annotations
from openenv.core.env_server.interfaces import Action, Observation, State
class CodeAction(Action): """ Represents a single code execution request. """
code: str # Optional: future fields like 'lint': bool, 'timeout_s': float, etc.
class CodeObservation(Observation): """ Result of executing code in the environment. """
stdout: str = "" stderr: str = "" exit_code: int = 0
class CodeState(State): """State for CodeAct environment with persistent execution context."""
last_exit_code: int = 012345name: coding_envversion: "0.1.0"description: "Coding environment for OpenEnv"action: CodeActionobservation: CodeObservation1234567891011121314151617181920212223242526272829303132333435[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "openenv-coding_env"version = "0.1.0"description = "Coding Environment for OpenEnv"requires-python = ">=3.10"dependencies = [ "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git@main", "fastapi>=0.115.0", "pydantic>=2.0.0", "uvicorn[standard]>=0.24.0", "requests>=2.31.0", "smolagents>=1.22.0,<2",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "pytest-cov>=4.0.0", "ipykernel>=6.29.5",]
[project.scripts]server = "coding_env.server.app:main"
[tool.setuptools]packages = ["coding_env", "coding_env.server"]package-dir = { "coding_env" = ".", "coding_env.server" = "server" }
[tool.setuptools.package-data]coding_env = ["**/*.yaml", "**/*.yml"]1234567891011121314151617181920212223242526272829303132333435# Dockerfile for Coding Environment# Build from repo root:# docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .
FROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ git \ curl \ && rm -rf /var/lib/apt/lists/*
# Copy coding_env packageCOPY envs/coding_env/ ./envs/coding_env/
# Install openenv-core first from PyPI, then coding_envRUN pip install --no-cache-dir "openenv-core[core]>=0.2.1" && \ pip install --no-cache-dir ./envs/coding_env/
# Environment variablesENV PYTHONUNBUFFERED=1ENV ENABLE_WEB_INTERFACE=true
# Expose portEXPOSE 8000
# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:8000/health || exit 1
# Run the serverCMD ["uvicorn", "coding_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]12345678910111213141516171819202122232425# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
# Use the standard openenv base image# Built from: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# In GitHub Actions, this is overridden to use the GHCR base imageARG BASE_IMAGE=openenv-base:latestFROM ${BASE_IMAGE}
# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY envs/coding_env/ /app/envs/coding_env/
# Copy README for web interface documentationCOPY envs/coding_env/README.md /app/README.md
# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:8000/health || exit 1
# Run the FastAPI serverCMD ["uvicorn", "envs.coding_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# CodingEnv HTTP Server
This directory contains the HTTP server implementation for the CodingEnvironment.
## Running Locally
### Prerequisites```bashpip install fastapi uvicorn```
### Start the server```bash# From the project root (/Users/pankit/git/envtorch)cd srcuvicorn envs.coding_env.server.app:app --reload --host 0.0.0.0 --port 8000```
The server will be available at `http://localhost:8000`
### API Endpoints
- `POST /reset` - Reset the environment- `POST /step` - Execute a code action- `GET /state` - Get current environment state- `GET /health` - Health check
### Test with curl
```bash# Health checkcurl http://localhost:8000/health
# Resetcurl -X POST http://localhost:8000/reset \ -H "Content-Type: application/json" \ -d '{}'
# Execute codecurl -X POST http://localhost:8000/step \ -H "Content-Type: application/json" \ -d '{ "action": { "code": "print(\"Hello from HTTP!\")" }, "timeout_s": 15 }'
# Get statecurl http://localhost:8000/state```1234567891011# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Coding environment server components."""
from .python_codeact_env import PythonCodeActEnv
__all__ = ["PythonCodeActEnv"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""FastAPI application for the Coding Environment.
This module creates an HTTP server that exposes the PythonCodeActEnvover HTTP and WebSocket endpoints, compatible with EnvClient.
Usage: # Development (with auto-reload): uvicorn envs.coding_env.server.app:app --reload --host 0.0.0.0 --port 8000
# Production: uvicorn envs.coding_env.server.app:app --host 0.0.0.0 --port 8000 --workers 4
# Or run directly: python -m envs.coding_env.server.app"""
from coding_env.models import CodeAction, CodeObservationfrom coding_env.server.python_codeact_env import PythonCodeActEnvfrom openenv.core.env_server import create_app
# Create the app with web interface and README integration# Pass the class (factory) instead of an instance for WebSocket session supportapp = create_app(PythonCodeActEnv, CodeAction, CodeObservation, env_name="coding_env")
if __name__ == "__main__": import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
def main(): """Main entry point for running the server.""" import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Python Code Action Environment.
This module provides a server-side environment implementation for executingPython code actions using PyExecutor."""
import uuid
from openenv.core.env_server.interfaces import Action, Environment, Observation
from ..models import CodeAction, CodeObservation, CodeStatefrom .python_executor import PyExecutorfrom .transforms import create_safe_coding_transform
class PythonCodeActEnv(Environment): """ Python Code Action Environment for executing code and tracking state.
This environment executes Python code submitted as CodeAction during step, maintains the last exit code in its state, and returns results wrapped in CodeObservation.
Args: transform: Optional transform to apply to observations additional_imports: List of additional module imports to authorize (e.g., ["numpy", "pandas", "matplotlib"])
Example: >>> env = PythonCodeActEnv() >>> obs = env.reset() >>> action = CodeAction(code="print('Hello, World!')") >>> obs = env.step(action) >>> print(obs.stdout) # "Hello, World!\n" >>> print(obs.exit_code) # 0 >>> print(env.state.last_exit_code) # 0 """
def __init__( self, ): self.transform = create_safe_coding_transform() self._executor = PyExecutor() self._state = CodeState()
def reset(self) -> Observation: """ Reset environment and start fresh execution session.
Returns: Initial observation with empty stdout/stderr and exit_code=0 """ # Initialize fresh state self._state = CodeState(episode_id=str(uuid.uuid4()), step_count=0) # Add last_exit_code to state self._state.last_exit_code = 0
# Reset executor to clear any previously defined variables/functions self._executor = PyExecutor()
# Reset transform to clear any accumulated state self.transform = create_safe_coding_transform()
# Return initial observation observation = CodeObservation( stdout="", stderr="", exit_code=0, )
return self._apply_transform(observation)
def step(self, action: Action) -> Observation: """ Execute code action and return observation.
Args: action: CodeAction containing the code to execute
Returns: CodeObservation with execution results (stdout, stderr, exit_code)
Raises: ValueError: If action is not a CodeAction instance """ if not isinstance(action, CodeAction): raise ValueError(f"Expected CodeAction, got {type(action)}")
# Execute the code using PyExecutor result = self._executor.run(action.code)
# Update state self._state.step_count += 1 self._state.last_exit_code = result.exit_code
# Create observation from execution result # Include code in metadata for transform reward calculation observation = CodeObservation( stdout=result.stdout, stderr=result.stderr, exit_code=result.exit_code, metadata={"last_code": action.code}, )
return self._apply_transform(observation)
@property def state(self) -> CodeState: """Get current environment state including last exit code.""" return self._state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Local Python Executor (enhanced).
This module provides a safer wrapper around smolagents.LocalPythonExecutorwith improved exception handling and a few helpful tools registered withthe executor to make debugging executed code easier.
Key improvements:- Register a few helper utilities via send_tools so user code can use them for reporting (e.g. `format_exc`).- More robust extraction of stdout/stderr/exit codes from the executor result object, tolerant to different versions of smolagents.- Detailed stderr on unexpected exceptions including full traceback.- Structured logging for operational visibility."""
from __future__ import annotations
import jsonimport loggingimport traceback
from openenv.core.env_server.types import CodeExecResultfrom smolagents import LocalPythonExecutor
logger = logging.getLogger(__name__)logger.addHandler(logging.NullHandler())
class PyExecutor: """Wrapper around smolagents LocalPythonExecutor.
The wrapper registers a few non-privileged helper tools to the LocalPythonExecutor that can be used by the executed code to format exceptions and to safely stringify results for improved error reporting. """
def __init__(self, additional_imports: list[str] | None = None): if additional_imports is None: additional_imports = []
self._executor = LocalPythonExecutor( additional_authorized_imports=additional_imports )
# Register helpful utilities exposed to the execution environment. # These are intentionally small, read-only helpers. tools = { # Provide a small helper to format the current exception in the # executed context. This is a *string formatting* helper only. "format_exc": traceback.format_exc, # Safe JSON dumps with a fallback for non-serializable objects. "safe_json_dumps": lambda obj: json.dumps(obj, default=lambda o: repr(o)), }
# `send_tools` is the public API on LocalPythonExecutor to make # helper callables available to the sandboxed runtime. We don't # provide any builtins that could change the environment. try: self._executor.send_tools(tools) except Exception: # If the LocalPythonExecutor implementation doesn't support # send_tools or fails, log and continue — the executor is still usable. logger.debug( "LocalPythonExecutor.send_tools failed; continuing without extra tools", exc_info=True, )
def run(self, code: str) -> CodeExecResult: """Execute Python code and return a CodeExecResult.
This method is intentionally defensive: it attempts to extract meaningful stdout/stderr/exit_code information from a variety of possible return shapes that different versions of smolagents may provide. """ try: exec_result = self._executor(code)
# Default values stdout_parts: list[str] = [] stderr_parts: list[str] = [] exit_code = 0
# Extract logs/prints try: logs = getattr(exec_result, "logs", None) if logs: stdout_parts.append(str(logs)) except Exception: logger.debug("Failed to read exec_result.logs", exc_info=True)
# Extract the result / output value try: if hasattr(exec_result, "output"): out_val = exec_result.output # If the output is not None, stringify it in a safe way if out_val is not None: # Prefer JSON if possible, otherwise repr try: stdout_parts.append(json.dumps(out_val)) except Exception: stdout_parts.append(repr(out_val)) except Exception: logger.debug("Failed to read exec_result.output", exc_info=True)
# Some runtime implementations may put errors on `error` or `exception` try: err = getattr(exec_result, "error", None) if err: stderr_parts.append(str(err)) except Exception: logger.debug("Failed to read exec_result.error", exc_info=True)
try: ex = getattr(exec_result, "exception", None) if ex: stderr_parts.append(str(ex)) except Exception: logger.debug("Failed to read exec_result.exception", exc_info=True)
# Determine exit code if provided try: if hasattr(exec_result, "exit_code"): exit_code = ( int(exec_result.exit_code) if exec_result.exit_code is not None else 0 ) elif hasattr(exec_result, "success"): # Some versions use `success` boolean exit_code = 0 if exec_result.success else 1 else: # Fallback: if there were any stderr parts, treat as non-zero exit_code = 1 if stderr_parts else 0 except Exception: logger.debug("Failed to determine exec_result exit code", exc_info=True) exit_code = 1 if stderr_parts else 0
# Compose the final stdout/stderr strings stdout = "\n".join(part for part in stdout_parts if part is not None) stderr = "\n".join(part for part in stderr_parts if part is not None)
return CodeExecResult(stdout=stdout, stderr=stderr, exit_code=exit_code)
except Exception as e: # Any unexpected exception from the LocalPythonExecutor is # returned with a full traceback to make debugging easier. tb = traceback.format_exc() logger.exception("LocalPythonExecutor raised an exception during run") return CodeExecResult(stdout="", stderr=tb, exit_code=1)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Transforms specific to coding environments."""
import astimport re
from openenv.core.env_server.base_transforms import CompositeTransformfrom openenv.core.env_server.interfaces import Transformfrom openenv.core.env_server.types import Observation
from ..models import CodeObservation
class CodeSafetyTransform(Transform): """Evaluates code safety and assigns penalties for dangerous patterns."""
def __init__(self, penalty: float = -1.0): self.penalty = penalty self.dangerous_patterns = [ r"import\s+os", r"import\s+subprocess", r"eval\(", r"exec\(", r"__import__", r"open\(", ]
def __call__(self, observation: Observation) -> Observation: if not isinstance(observation, CodeObservation): return observation
if "last_code" in observation.metadata: code = observation.metadata["last_code"] for pattern in self.dangerous_patterns: if re.search(pattern, code): observation.reward = self.penalty observation.metadata["safety_violation"] = pattern break else: if observation.reward is None: observation.reward = 0.0
return observation
class CodeQualityTransform(Transform): """Evaluates and rewards code quality metrics."""
def __init__( self, concise_bonus: float = 0.1, max_length_threshold: int = 100, syntax_penalty: float = -0.2, ): self.concise_bonus = concise_bonus self.max_length_threshold = max_length_threshold self.syntax_penalty = syntax_penalty
def __call__(self, observation: Observation) -> Observation: if not isinstance(observation, CodeObservation): return observation
quality_score = 0.0
if "last_code" in observation.metadata: code = observation.metadata["last_code"]
# Reward concise code if len(code.strip()) <= self.max_length_threshold: quality_score += self.concise_bonus
# Check syntax (redundant but useful for quality assessment) try: ast.parse(code) except SyntaxError: quality_score += self.syntax_penalty
# Add to existing reward if observation.reward is None: observation.reward = quality_score else: observation.reward += quality_score
return observation
def create_safe_coding_transform() -> CompositeTransform: """Create a transform focused on safe coding practices and quality.""" return CompositeTransform([CodeSafetyTransform(), CodeQualityTransform()])12345678910111213141516171819202122232425262728293031323334"""envs/coding_env/models.py--------------------------------Action/Observation types for the Coding environment."""
from __future__ import annotations
from openenv.core.env_server.interfaces import Action, Observation, State
class CodeAction(Action): """ Represents a single code execution request. """
code: str # Optional: future fields like 'lint': bool, 'timeout_s': float, etc.
class CodeObservation(Observation): """ Result of executing code in the environment. """
stdout: str = "" stderr: str = "" exit_code: int = 0
class CodeState(State): """State for CodeAct environment with persistent execution context."""
last_exit_code: int = 012345name: coding_envversion: "0.1.0"description: "Coding environment for OpenEnv"action: CodeActionobservation: CodeObservation1234567891011121314151617181920212223242526272829303132333435[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "openenv-coding_env"version = "0.1.0"description = "Coding Environment for OpenEnv"requires-python = ">=3.10"dependencies = [ "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git@main", "fastapi>=0.115.0", "pydantic>=2.0.0", "uvicorn[standard]>=0.24.0", "requests>=2.31.0", "smolagents>=1.22.0,<2",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "pytest-cov>=4.0.0", "ipykernel>=6.29.5",]
[project.scripts]server = "coding_env.server.app:main"
[tool.setuptools]packages = ["coding_env", "coding_env.server"]package-dir = { "coding_env" = ".", "coding_env.server" = "server" }
[tool.setuptools.package-data]coding_env = ["**/*.yaml", "**/*.yml"]1234567891011121314151617181920212223242526272829303132333435# Dockerfile for Coding Environment# Build from repo root:# docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .
FROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ git \ curl \ && rm -rf /var/lib/apt/lists/*
# Copy coding_env packageCOPY envs/coding_env/ ./envs/coding_env/
# Install openenv-core first from PyPI, then coding_envRUN pip install --no-cache-dir "openenv-core[core]>=0.2.1" && \ pip install --no-cache-dir ./envs/coding_env/
# Environment variablesENV PYTHONUNBUFFERED=1ENV ENABLE_WEB_INTERFACE=true
# Expose portEXPOSE 8000
# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:8000/health || exit 1
# Run the serverCMD ["uvicorn", "coding_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]12345678910111213141516171819202122232425# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
# Use the standard openenv base image# Built from: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# In GitHub Actions, this is overridden to use the GHCR base imageARG BASE_IMAGE=openenv-base:latestFROM ${BASE_IMAGE}
# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY envs/coding_env/ /app/envs/coding_env/
# Copy README for web interface documentationCOPY envs/coding_env/README.md /app/README.md
# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:8000/health || exit 1
# Run the FastAPI serverCMD ["uvicorn", "envs.coding_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# CodingEnv HTTP Server
This directory contains the HTTP server implementation for the CodingEnvironment.
## Running Locally
### Prerequisites```bashpip install fastapi uvicorn```
### Start the server```bash# From the project root (/Users/pankit/git/envtorch)cd srcuvicorn envs.coding_env.server.app:app --reload --host 0.0.0.0 --port 8000```
The server will be available at `http://localhost:8000`
### API Endpoints
- `POST /reset` - Reset the environment- `POST /step` - Execute a code action- `GET /state` - Get current environment state- `GET /health` - Health check
### Test with curl
```bash# Health checkcurl http://localhost:8000/health
# Resetcurl -X POST http://localhost:8000/reset \ -H "Content-Type: application/json" \ -d '{}'
# Execute codecurl -X POST http://localhost:8000/step \ -H "Content-Type: application/json" \ -d '{ "action": { "code": "print(\"Hello from HTTP!\")" }, "timeout_s": 15 }'
# Get statecurl http://localhost:8000/state```1234567891011# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Coding environment server components."""
from .python_codeact_env import PythonCodeActEnv
__all__ = ["PythonCodeActEnv"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""FastAPI application for the Coding Environment.
This module creates an HTTP server that exposes the PythonCodeActEnvover HTTP and WebSocket endpoints, compatible with EnvClient.
Usage: # Development (with auto-reload): uvicorn envs.coding_env.server.app:app --reload --host 0.0.0.0 --port 8000
# Production: uvicorn envs.coding_env.server.app:app --host 0.0.0.0 --port 8000 --workers 4
# Or run directly: python -m envs.coding_env.server.app"""
from coding_env.models import CodeAction, CodeObservationfrom coding_env.server.python_codeact_env import PythonCodeActEnvfrom openenv.core.env_server import create_app
# Create the app with web interface and README integration# Pass the class (factory) instead of an instance for WebSocket session supportapp = create_app(PythonCodeActEnv, CodeAction, CodeObservation, env_name="coding_env")
if __name__ == "__main__": import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
def main(): """Main entry point for running the server.""" import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Python Code Action Environment.
This module provides a server-side environment implementation for executingPython code actions using PyExecutor."""
import uuid
from openenv.core.env_server.interfaces import Action, Environment, Observation
from ..models import CodeAction, CodeObservation, CodeStatefrom .python_executor import PyExecutorfrom .transforms import create_safe_coding_transform
class PythonCodeActEnv(Environment): """ Python Code Action Environment for executing code and tracking state.
This environment executes Python code submitted as CodeAction during step, maintains the last exit code in its state, and returns results wrapped in CodeObservation.
Args: transform: Optional transform to apply to observations additional_imports: List of additional module imports to authorize (e.g., ["numpy", "pandas", "matplotlib"])
Example: >>> env = PythonCodeActEnv() >>> obs = env.reset() >>> action = CodeAction(code="print('Hello, World!')") >>> obs = env.step(action) >>> print(obs.stdout) # "Hello, World!\n" >>> print(obs.exit_code) # 0 >>> print(env.state.last_exit_code) # 0 """
def __init__( self, ): self.transform = create_safe_coding_transform() self._executor = PyExecutor() self._state = CodeState()
def reset(self) -> Observation: """ Reset environment and start fresh execution session.
Returns: Initial observation with empty stdout/stderr and exit_code=0 """ # Initialize fresh state self._state = CodeState(episode_id=str(uuid.uuid4()), step_count=0) # Add last_exit_code to state self._state.last_exit_code = 0
# Reset executor to clear any previously defined variables/functions self._executor = PyExecutor()
# Reset transform to clear any accumulated state self.transform = create_safe_coding_transform()
# Return initial observation observation = CodeObservation( stdout="", stderr="", exit_code=0, )
return self._apply_transform(observation)
def step(self, action: Action) -> Observation: """ Execute code action and return observation.
Args: action: CodeAction containing the code to execute
Returns: CodeObservation with execution results (stdout, stderr, exit_code)
Raises: ValueError: If action is not a CodeAction instance """ if not isinstance(action, CodeAction): raise ValueError(f"Expected CodeAction, got {type(action)}")
# Execute the code using PyExecutor result = self._executor.run(action.code)
# Update state self._state.step_count += 1 self._state.last_exit_code = result.exit_code
# Create observation from execution result # Include code in metadata for transform reward calculation observation = CodeObservation( stdout=result.stdout, stderr=result.stderr, exit_code=result.exit_code, metadata={"last_code": action.code}, )
return self._apply_transform(observation)
@property def state(self) -> CodeState: """Get current environment state including last exit code.""" return self._state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Local Python Executor (enhanced).
This module provides a safer wrapper around smolagents.LocalPythonExecutorwith improved exception handling and a few helpful tools registered withthe executor to make debugging executed code easier.
Key improvements:- Register a few helper utilities via send_tools so user code can use them for reporting (e.g. `format_exc`).- More robust extraction of stdout/stderr/exit codes from the executor result object, tolerant to different versions of smolagents.- Detailed stderr on unexpected exceptions including full traceback.- Structured logging for operational visibility."""
from __future__ import annotations
import jsonimport loggingimport traceback
from openenv.core.env_server.types import CodeExecResultfrom smolagents import LocalPythonExecutor
logger = logging.getLogger(__name__)logger.addHandler(logging.NullHandler())
class PyExecutor: """Wrapper around smolagents LocalPythonExecutor.
The wrapper registers a few non-privileged helper tools to the LocalPythonExecutor that can be used by the executed code to format exceptions and to safely stringify results for improved error reporting. """
def __init__(self, additional_imports: list[str] | None = None): if additional_imports is None: additional_imports = []
self._executor = LocalPythonExecutor( additional_authorized_imports=additional_imports )
# Register helpful utilities exposed to the execution environment. # These are intentionally small, read-only helpers. tools = { # Provide a small helper to format the current exception in the # executed context. This is a *string formatting* helper only. "format_exc": traceback.format_exc, # Safe JSON dumps with a fallback for non-serializable objects. "safe_json_dumps": lambda obj: json.dumps(obj, default=lambda o: repr(o)), }
# `send_tools` is the public API on LocalPythonExecutor to make # helper callables available to the sandboxed runtime. We don't # provide any builtins that could change the environment. try: self._executor.send_tools(tools) except Exception: # If the LocalPythonExecutor implementation doesn't support # send_tools or fails, log and continue — the executor is still usable. logger.debug( "LocalPythonExecutor.send_tools failed; continuing without extra tools", exc_info=True, )
def run(self, code: str) -> CodeExecResult: """Execute Python code and return a CodeExecResult.
This method is intentionally defensive: it attempts to extract meaningful stdout/stderr/exit_code information from a variety of possible return shapes that different versions of smolagents may provide. """ try: exec_result = self._executor(code)
# Default values stdout_parts: list[str] = [] stderr_parts: list[str] = [] exit_code = 0
# Extract logs/prints try: logs = getattr(exec_result, "logs", None) if logs: stdout_parts.append(str(logs)) except Exception: logger.debug("Failed to read exec_result.logs", exc_info=True)
# Extract the result / output value try: if hasattr(exec_result, "output"): out_val = exec_result.output # If the output is not None, stringify it in a safe way if out_val is not None: # Prefer JSON if possible, otherwise repr try: stdout_parts.append(json.dumps(out_val)) except Exception: stdout_parts.append(repr(out_val)) except Exception: logger.debug("Failed to read exec_result.output", exc_info=True)
# Some runtime implementations may put errors on `error` or `exception` try: err = getattr(exec_result, "error", None) if err: stderr_parts.append(str(err)) except Exception: logger.debug("Failed to read exec_result.error", exc_info=True)
try: ex = getattr(exec_result, "exception", None) if ex: stderr_parts.append(str(ex)) except Exception: logger.debug("Failed to read exec_result.exception", exc_info=True)
# Determine exit code if provided try: if hasattr(exec_result, "exit_code"): exit_code = ( int(exec_result.exit_code) if exec_result.exit_code is not None else 0 ) elif hasattr(exec_result, "success"): # Some versions use `success` boolean exit_code = 0 if exec_result.success else 1 else: # Fallback: if there were any stderr parts, treat as non-zero exit_code = 1 if stderr_parts else 0 except Exception: logger.debug("Failed to determine exec_result exit code", exc_info=True) exit_code = 1 if stderr_parts else 0
# Compose the final stdout/stderr strings stdout = "\n".join(part for part in stdout_parts if part is not None) stderr = "\n".join(part for part in stderr_parts if part is not None)
return CodeExecResult(stdout=stdout, stderr=stderr, exit_code=exit_code)
except Exception as e: # Any unexpected exception from the LocalPythonExecutor is # returned with a full traceback to make debugging easier. tb = traceback.format_exc() logger.exception("LocalPythonExecutor raised an exception during run") return CodeExecResult(stdout="", stderr=tb, exit_code=1)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Transforms specific to coding environments."""
import astimport re
from openenv.core.env_server.base_transforms import CompositeTransformfrom openenv.core.env_server.interfaces import Transformfrom openenv.core.env_server.types import Observation
from ..models import CodeObservation
class CodeSafetyTransform(Transform): """Evaluates code safety and assigns penalties for dangerous patterns."""
def __init__(self, penalty: float = -1.0): self.penalty = penalty self.dangerous_patterns = [ r"import\s+os", r"import\s+subprocess", r"eval\(", r"exec\(", r"__import__", r"open\(", ]
def __call__(self, observation: Observation) -> Observation: if not isinstance(observation, CodeObservation): return observation
if "last_code" in observation.metadata: code = observation.metadata["last_code"] for pattern in self.dangerous_patterns: if re.search(pattern, code): observation.reward = self.penalty observation.metadata["safety_violation"] = pattern break else: if observation.reward is None: observation.reward = 0.0
return observation
class CodeQualityTransform(Transform): """Evaluates and rewards code quality metrics."""
def __init__( self, concise_bonus: float = 0.1, max_length_threshold: int = 100, syntax_penalty: float = -0.2, ): self.concise_bonus = concise_bonus self.max_length_threshold = max_length_threshold self.syntax_penalty = syntax_penalty
def __call__(self, observation: Observation) -> Observation: if not isinstance(observation, CodeObservation): return observation
quality_score = 0.0
if "last_code" in observation.metadata: code = observation.metadata["last_code"]
# Reward concise code if len(code.strip()) <= self.max_length_threshold: quality_score += self.concise_bonus
# Check syntax (redundant but useful for quality assessment) try: ast.parse(code) except SyntaxError: quality_score += self.syntax_penalty
# Add to existing reward if observation.reward is None: observation.reward = quality_score else: observation.reward += quality_score
return observation
def create_safe_coding_transform() -> CompositeTransform: """Create a transform focused on safe coding practices and quality.""" return CompositeTransform([CodeSafetyTransform(), CodeQualityTransform()])1234567# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""EnvTorch: Standardized agentic execution environments."""1 unmodified line234567891011129 unmodified lines22232425262728291 unmodified line3132333435363738394041424344454647484950513 unmodified lines555657585960618 unmodified lines707172737475767778798081828384858631 unmodified lines1181191201211221231245 unmodified lines1301311321331341351364 unmodified lines14114214314414514614714814915015115215315420 unmodified lines1751761771781791801 unmodified lineAn e2e framework for creating, deploying and using isolated execution environments for agentic RL training, built using Gymnasium style simple APIs. OpenEnv provides a standard for interacting with agentic execution environments via simple Gymnasium style APIs - step(), reset(), state(). Users of agentic execution environments can interact with the environment during RL training loops using these simple APIs.In addition to making it easier for researchers and RL framework writers, we also provide tools for environment creators making it easier for them to create richer environments and make them available over familar protocols like HTTP and packaged using canonical technologies like docker. Environment creators can use the OpenEnv framework to create environments that are isolated, secure, and easy to deploy and use.## Overview`openenv-core` provides the foundational building blocks for creating and interacting with containerized environments over HTTP. It enables you to build agent environments that can be deployed as Docker containers and accessed via a simple HTTP API.> ⚠️ **Early Development Warning** OpenEnv is currently in an experimental> stage. You should expect bugs, incomplete features, and APIs that may change9 unmodified lines## Features- **HTTPEnvClient**: Generic HTTP client for interacting with remote environments- **HTTPEnvServer**: FastAPI-based server wrapper for exposing environments over HTTP- **Container Providers**: Pluggable architecture for running containers (Docker, Kubernetes, etc.)- **Type System**: Strongly-typed Action/Observation/State interfaces- **Web Interface**: Optional web UI for interacting with environments1 unmodified line## Installation```bashpip install openenv-core```For development:```bashpip install openenv-core[dev]```## Quick Start### Creating an Environment Client```pythonfrom openenv_core import HTTPEnvClient, StepResultfrom dataclasses import dataclass@dataclassclass MyAction:3 unmodified linesclass MyObservation:response: strclass MyEnvClient(HTTPEnvClient[MyAction, MyObservation]):def _step_payload(self, action: MyAction) -> dict:return {"text": action.text}8 unmodified linesdef _parse_state(self, payload: dict) -> Any:return payload# Use with Dockerenv = MyEnvClient.from_docker_image("my-env:latest")result = env.reset()step_result = env.step(MyAction(text="hello"))env.close()```### Creating an Environment Server```pythonfrom openenv_core.env_server import Environment, HTTPEnvServer, create_appfrom dataclasses import dataclass@dataclass31 unmodified lines### Local Docker Provider```pythonfrom openenv_core.containers.runtime import LocalDockerProviderprovider = LocalDockerProvider()base_url = provider.start_container("my-env:latest")5 unmodified lines### Kubernetes Provider (Coming Soon)```pythonfrom openenv_core.containers.runtime import KubernetesProviderprovider = KubernetesProvider(namespace="envs")base_url = provider.start_container("my-env:latest")4 unmodified lines## API Reference### HTTPEnvClientBase class for environment clients with these abstract methods:- `_step_payload(action)`: Convert action to JSON- `_parse_result(payload)`: Parse response to StepResult- `_parse_state(payload)`: Parse state response### HTTPEnvServerServer wrapper with these methods:20 unmodified lines## Links- **Homepage**: https://github.com/facebookresearch/OpenEnv- **Documentation**: https://github.com/facebookresearch/OpenEnv/blob/main/README.md- **Bug Tracker**: https://github.com/facebookresearch/OpenEnv/issues1 unmodified line234567891011129 unmodified lines2223242526272829301 unmodified line323334353637383940414243444546474849505152535455563 unmodified lines606162636465668 unmodified lines7576777879808182838485868788899091929394959697989931 unmodified lines1311321331341351361375 unmodified lines1431441451461471481494 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518620 unmodified lines2072082092102112121 unmodified lineAn e2e framework for creating, deploying and using isolated execution environments for agentic RL training, built using Gymnasium style simple APIs. OpenEnv provides a standard for interacting with agentic execution environments via simple Gymnasium style APIs - step(), reset(), state(). Users of agentic execution environments can interact with the environment during RL training loops using these simple APIs.In addition to making it easier for researchers and RL framework writers, we also provide tools for environment creators making it easier for them to create richer environments and make them available over familiar protocols like HTTP and packaged using canonical technologies like docker. Environment creators can use the OpenEnv framework to create environments that are isolated, secure, and easy to deploy and use.## Overview`openenv.core` provides the foundational building blocks for creating and interacting with containerized environments over HTTP. It enables you to build agent environments that can be deployed as Docker containers and accessed via a simple HTTP API.> ⚠️ **Early Development Warning** OpenEnv is currently in an experimental> stage. You should expect bugs, incomplete features, and APIs that may change9 unmodified lines## Features- **EnvClient**: Async-first client for interacting with remote environments- **SyncEnvClient**: Synchronous wrapper via `.sync()` for sync codebases- **HTTPEnvServer**: FastAPI-based server wrapper for exposing environments over HTTP/WebSocket- **Container Providers**: Pluggable architecture for running containers (Docker, Kubernetes, etc.)- **Type System**: Strongly-typed Action/Observation/State interfaces- **Web Interface**: Optional web UI for interacting with environments1 unmodified line## Installation```bashpip install "openenv[core]"```For development:```bashpip install "openenv[core]"```## Quick Start### Creating an Environment ClientEnvClient is **async by default**. Use `async with` and `await` for all operations:```pythonimport asynciofrom openenv.core import EnvClient, StepResultfrom dataclasses import dataclassfrom typing import Any@dataclassclass MyAction:3 unmodified linesclass MyObservation:response: strclass MyEnvClient(EnvClient[MyAction, MyObservation, Any]):def _step_payload(self, action: MyAction) -> dict:return {"text": action.text}8 unmodified linesdef _parse_state(self, payload: dict) -> Any:return payload# Async usage (recommended)async def main():client = await MyEnvClient.from_docker_image("my-env:latest")async with client:result = await client.reset()step_result = await client.step(MyAction(text="hello"))asyncio.run(main())# Sync usage (via .sync() wrapper)with MyEnvClient(base_url="http://localhost:8000").sync() as client:result = client.reset()step_result = client.step(MyAction(text="hello"))```### Creating an Environment Server```pythonfrom openenv.core.env_server import Environment, HTTPEnvServer, create_appfrom dataclasses import dataclass@dataclass31 unmodified lines### Local Docker Provider```pythonfrom openenv.core.containers.runtime import LocalDockerProviderprovider = LocalDockerProvider()base_url = provider.start_container("my-env:latest")5 unmodified lines### Kubernetes Provider (Coming Soon)```pythonfrom openenv.core.containers.runtime import KubernetesProviderprovider = KubernetesProvider(namespace="envs")base_url = provider.start_container("my-env:latest")4 unmodified lines## API Reference### EnvClientAsync base class for environment clients. Key methods:- `async connect()`: Establish WebSocket connection- `async reset(**kwargs)`: Reset environment- `async step(action)`: Execute action- `async state()`: Get current state- `async close()`: Close connection and cleanup- `sync()`: Return a SyncEnvClient wrapper for synchronous usageAbstract methods to implement:- `_step_payload(action)`: Convert action to JSON- `_parse_result(payload)`: Parse response to StepResult- `_parse_state(payload)`: Parse state response### SyncEnvClientSynchronous wrapper around EnvClient. Use `client.sync()` to get one:```pythonsync_client = async_client.sync()with sync_client:result = sync_client.reset()result = sync_client.step(action)```### HTTPEnvServerServer wrapper with these methods:20 unmodified lines## Links- **Homepage**: https://github.com/meta-pytorch/OpenEnv- **Documentation**: https://github.com/meta-pytorch/OpenEnv/blob/main/README.md- **Bug Tracker**: https://github.com/meta-pytorch/OpenEnv/issues
5 unmodified lines6789101112131415161718195 unmodified lines"""Core components for agentic environments."""# Re-export main components from submodules for conveniencefrom .env_server import *from .client_types import StepResultfrom .http_env_client import HTTPEnvClient# Note: MCP module doesn't export anything yet__all__ = ["HTTPEnvClient","StepResult",]5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980815 unmodified lines"""Core components for agentic environments."""from __future__ import annotationsfrom importlib import import_modulefrom typing import TYPE_CHECKINGfrom . import env_serverfrom .env_server import * # noqa: F403if TYPE_CHECKING:from .env_client import EnvClientfrom .generic_client import GenericAction, GenericEnvClientfrom .llm_client import (AnthropicClient,create_llm_client,LLMClient,LLMResponse,OpenAIClient,ToolCall,)from .mcp_client import MCPClientBase, MCPToolClientfrom .sync_client import SyncEnvClient__all__ = ["EnvClient","SyncEnvClient","GenericEnvClient","GenericAction","MCPClientBase","MCPToolClient","AnthropicClient","LLMClient","LLMResponse","OpenAIClient","ToolCall","create_llm_client",] + env_server.__all__ # type: ignore_LAZY_ATTRS = {"EnvClient": (".env_client", "EnvClient"),"SyncEnvClient": (".sync_client", "SyncEnvClient"),"GenericEnvClient": (".generic_client", "GenericEnvClient"),"GenericAction": (".generic_client", "GenericAction"),"MCPClientBase": (".mcp_client", "MCPClientBase"),"MCPToolClient": (".mcp_client", "MCPToolClient"),"AnthropicClient": (".llm_client", "AnthropicClient"),"LLMClient": (".llm_client", "LLMClient"),"LLMResponse": (".llm_client", "LLMResponse"),"OpenAIClient": (".llm_client", "OpenAIClient"),"ToolCall": (".llm_client", "ToolCall"),"create_llm_client": (".llm_client", "create_llm_client"),}def __getattr__(name: str):if name in _LAZY_ATTRS:module_path, attr_name = _LAZY_ATTRS[name]module = import_module(module_path, __name__)value = getattr(module, attr_name)globals()[name] = valuereturn valuetry:value = getattr(env_server, name)except AttributeError as exc:raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from excglobals()[name] = valuereturn valuedef __dir__() -> list[str]:return sorted(set(globals().keys()) | set(__all__))
123456789# Type definitions for EnvTorchfrom dataclasses import dataclassfrom typing import Any, Generic, Optional, TypeVar# Generic type for observationsObsT = TypeVar("ObsT") # TypeVar for typehinting in IDEs@dataclass12345678910# Type definitions for EnvTorchfrom dataclasses import dataclassfrom typing import Generic, Optional, TypeVar# Generic type for observationsObsT = TypeVar("ObsT")StateT = TypeVar("StateT")@dataclass
3 unmodified lines45673 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""Container management for environment servers."""3 unmodified lines45673 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""Container management for environment servers."""
7 unmodified lines89101112131415161718192021222324252627282930313233343536371 unmodified line3940414243447 unmodified lines# OpenEnv Base Image## This is the standard base image for all OpenEnv environment servers.# It includes the minimal dependencies needed to run HTTP environment servers.## Build: docker build -t openenv-base:latest -f src/core/containers/images/Dockerfile .# Tag: docker tag openenv-base:latest openenv-base:0.1.0#FROM python:3.11-slim# Set metadataLABEL maintainer="OpenEnv Team"LABEL description="Base image for OpenEnv based environment servers"LABEL version="0.1.0"# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \curl \&& rm -rf /var/lib/apt/lists/*# Install Python dependencies that all environments needRUN pip install --no-cache-dir \fastapi>=0.104.0 \"uvicorn[standard]>=0.24.0" \requests>=2.25.0 \wsproto>=1.0.0# Set working directoryWORKDIR /app1 unmodified line# Default environment variablesENV PYTHONPATH=/app/srcENV PYTHONUNBUFFERED=1# Default expose port (can be overridden)EXPOSE 80007 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253541 unmodified line565758596061627 unmodified lines# OpenEnv Base Image## This is the standard base image for all OpenEnv environment servers.# It includes the minimal dependencies needed to run HTTP environment servers# and uv for fast dependency management.## Build from repo root: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# Tag: docker tag openenv-base:latest openenv-base:0.2.0#FROM ghcr.io/astral-sh/uv:0.5.27-python3.11-bookworm-slim AS builder# Set working directoryWORKDIR /app# Copy core pyproject.toml and lockfile for dependency installationCOPY pyproject.toml uv.lock* ./# Install core dependencies using uv with cache mountRUN --mount=type=cache,target=/root/.cache/uv \uv pip install --system -r pyproject.toml# Final runtime stageFROM python:3.11-slim# Set metadataLABEL maintainer="OpenEnv Team"LABEL description="Base image for OpenEnv based environment servers with uv"LABEL version="0.2.0"# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \curl \ca-certificates \&& rm -rf /var/lib/apt/lists/*# Copy uv from builderCOPY --from=builder /usr/local/bin/uv /usr/local/bin/uvx /usr/local/bin/# Copy installed Python packages from builderCOPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages# Copy console scripts installed by pip (uvicorn, fastapi, etc.)COPY --from=builder /usr/local/bin/uvicorn /usr/local/bin/fastapi /usr/local/bin/# Set working directoryWORKDIR /app1 unmodified line# Default environment variablesENV PYTHONPATH=/app/srcENV PYTHONUNBUFFERED=1ENV UV_SYSTEM_PYTHON=1# Default expose port (can be overridden)EXPOSE 8000
35 unmodified lines363738394041424 unmodified lines474849505152535411 unmodified lines666768697071727374753 unmodified lines798081828384858687888990919235 unmodified lines```bash# From project rootdocker build -t openenv-base:latest -f src/core/containers/images/Dockerfile .```## Usage in Environment Dockerfiles4 unmodified linesFROM openenv-base:latest# Copy only environment-specific filesCOPY src/core/ /app/src/core/COPY src/envs/my_env/ /app/src/envs/my_env/# Run the serverCMD ["uvicorn", "envs.my_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]11 unmodified lines```bash# Step 1: Build base image (do this once)docker build -t openenv-base:latest -f src/core/containers/images/Dockerfile .# Step 2: Build echo environment (uses base)docker build -t echo-env:latest -f src/envs/echo_env/server/Dockerfile .# Step 3: Run echo environmentdocker run -p 8000:8000 echo-env:latest3 unmodified linesWhen dependencies need updating:1. Update `src/core/containers/images/Dockerfile`2. Rebuild base image3. Rebuild all environment images (they'll use new base)```bash# Update basedocker build -t openenv-base:latest -f src/core/containers/images/Dockerfile .# Rebuild environments (they automatically use new base)docker build -t echo-env:latest -f src/envs/echo_env/server/Dockerfile .```35 unmodified lines363738394041424 unmodified lines474849505152535411 unmodified lines666768697071727374753 unmodified lines798081828384858687888990919235 unmodified lines```bash# From project rootdocker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .```## Usage in Environment Dockerfiles4 unmodified linesFROM openenv-base:latest# Copy only environment-specific filesCOPY src/openenv/core/ /app/src/openenv/core/COPY envs/my_env/ /app/envs/my_env/# Run the serverCMD ["uvicorn", "envs.my_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]11 unmodified lines```bash# Step 1: Build base image (do this once)docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# Step 2: Build echo environment (uses base)docker build -t echo-env:latest -f envs/echo_env/server/Dockerfile .# Step 3: Run echo environmentdocker run -p 8000:8000 echo-env:latest3 unmodified linesWhen dependencies need updating:1. Update `src/openenv/core/containers/images/Dockerfile`2. Rebuild base image3. Rebuild all environment images (they'll use new base)```bash# Update basedocker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# Rebuild environments (they automatically use new base)docker build -t echo-env:latest -f envs/echo_env/server/Dockerfile .```
5 unmodified lines67891011121314155 unmodified lines"""Container runtime providers."""from .providers import ContainerProvider, KubernetesProvider, LocalDockerProvider__all__ = ["ContainerProvider","LocalDockerProvider","KubernetesProvider",]5 unmodified lines6789101112131415161718192021222324255 unmodified lines"""Container runtime providers."""from .providers import (ContainerProvider,DockerSwarmProvider,KubernetesProvider,LocalDockerProvider,RuntimeProvider,)from .uv_provider import UVProvider__all__ = ["ContainerProvider","DockerSwarmProvider","LocalDockerProvider","KubernetesProvider","RuntimeProvider","UVProvider",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Daytona container provider for running OpenEnv environments in Daytona cloud sandboxes.
Requires the ``daytona`` SDK: ``pip install daytona>=0.10``"""
from __future__ import annotations
import jsonimport osimport shleximport timefrom typing import Any, Callable, Dict, Optional
import yaml
from .providers import ContainerProvider
class DaytonaProvider(ContainerProvider): """ Container provider that runs environments in Daytona cloud sandboxes.
Example: >>> provider = DaytonaProvider(api_key="your-key") >>> image = DaytonaProvider.image_from_dockerfile("envs/echo_env/server/Dockerfile") >>> base_url = provider.start_container(image) >>> provider.wait_for_ready(base_url) >>> provider.stop_container() """
_dockerfile_registry: Dict[str, Dict[str, Any]] = {}
def __init__( self, *, api_key: Optional[str] = None, public: bool = False, resources: Optional[Any] = None, auto_stop_interval: int = 15, target: Optional[str] = None, on_snapshot_create_logs: Optional[Callable[[str], None]] = None, cmd: Optional[str] = None, create_timeout: float = 300, ): """ Args: api_key: Daytona API key. Falls back to ``DAYTONA_API_KEY`` env var. public: If True, the sandbox preview is publicly accessible. resources: Optional ``daytona.Resources`` instance for CPU/memory. auto_stop_interval: Minutes of inactivity before auto-stop (0 disables). target: Daytona target region (e.g. "us"). on_snapshot_create_logs: Callback for snapshot build log lines. cmd: Shell command to start the server inside the sandbox. create_timeout: Seconds to wait for sandbox creation (default 300). Heavy images (e.g. with Playwright/Chromium) may need more. """ from daytona import Daytona, DaytonaConfig
config_kwargs: Dict[str, Any] = {} resolved_key = api_key or os.environ.get("DAYTONA_API_KEY") if resolved_key: config_kwargs["api_key"] = resolved_key if target: config_kwargs["target"] = target
self._daytona = Daytona(DaytonaConfig(**config_kwargs)) self._public = public self._resources = resources self._auto_stop_interval = auto_stop_interval self._on_snapshot_create_logs = on_snapshot_create_logs self._cmd = cmd self._create_timeout = create_timeout self._sandbox: Any = None self._preview_url: Optional[str] = None
def _discover_server_cmd(self, sandbox: Any, port: int = 8000) -> str: """Discover the server command from ``openenv.yaml`` inside *sandbox*.
Finds the file, reads the ``app`` field, and constructs a command of the form ``cd <env_root> && python -m uvicorn <app> --host 0.0.0.0 --port <port>``.
Raises: ValueError: If ``openenv.yaml`` is not found or lacks an ``app`` field. """ yaml_path = self._find_openenv_yaml(sandbox) if yaml_path is None: raise ValueError( "Could not find openenv.yaml inside the sandbox. " "Pass an explicit cmd= to DaytonaProvider or start_container()." )
cat_resp = sandbox.process.exec(f"cat {shlex.quote(yaml_path)}", timeout=10) content = cat_resp.result if hasattr(cat_resp, "result") else str(cat_resp) app = self._parse_app_field(content) if app is None: raise ValueError( f"openenv.yaml at {yaml_path} does not contain an 'app' field. " "Pass an explicit cmd= to DaytonaProvider or start_container()." )
# The directory containing openenv.yaml is the env root env_root = yaml_path.rsplit("/", 1)[0] return ( f"cd {shlex.quote(env_root)} && " f"python -m uvicorn {shlex.quote(app)} --host 0.0.0.0 --port {port}" )
def _find_openenv_yaml(self, sandbox: Any) -> Optional[str]: """Locate ``openenv.yaml`` inside the sandbox.
Tries the modern layout path ``/app/env/openenv.yaml`` first, then falls back to a ``find`` command for the old layout. """ # Fast path: modern Dockerfile layout resp = sandbox.process.exec( "test -f /app/env/openenv.yaml && echo found", timeout=10 ) out = resp.result if hasattr(resp, "result") else str(resp) if "found" in (out or ""): return "/app/env/openenv.yaml"
# Fallback: search for it (redirect stderr so error messages # like "No such file or directory" don't get mistaken for paths). resp = sandbox.process.exec( "find /app -maxdepth 4 -name openenv.yaml -print -quit 2>/dev/null", timeout=10, ) path = (resp.result if hasattr(resp, "result") else str(resp) or "").strip() if path and path.startswith("/"): return path
return None
@staticmethod def _parse_app_field(yaml_content: str) -> Optional[str]: """Extract the ``app`` value from raw openenv.yaml content.
Uses PyYAML to handle comments, quotes, and nested keys correctly. """ try: data = yaml.safe_load(yaml_content) or {} except Exception: return None
if not isinstance(data, dict): return None
value = data.get("app") if isinstance(value, str): value = value.strip() return value if value else None return None
@staticmethod def _parse_dockerfile_cmd(dockerfile_content: str) -> Optional[str]: """Extract the server command from the last ``CMD`` in a Dockerfile.
Handles exec form (``CMD ["prog", "arg"]``) and shell form (``CMD prog arg``). When a Dockerfile has multiple ``CMD`` instructions (e.g. multi-stage builds), the last one wins - same semantics as Docker itself. Lines where ``CMD`` appears inside a comment are ignored.
Returns: The command as a single string, or ``None`` if no ``CMD`` found. """ import re
last_cmd: Optional[str] = None for line in dockerfile_content.splitlines(): stripped = line.strip() # Skip comments if stripped.startswith("#"): continue match = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE) if match: last_cmd = match.group(1).strip()
if last_cmd is None: return None
# Exec form: CMD ["executable", "param1", ...] if last_cmd.startswith("["): try: parts = json.loads(last_cmd) if isinstance(parts, list) and all(isinstance(p, str) for p in parts): return " ".join(parts) except (json.JSONDecodeError, TypeError): pass
# Shell form: CMD executable param1 ... return last_cmd if last_cmd else None
@staticmethod def strip_buildkit_syntax(dockerfile_content: str) -> str: """Remove BuildKit ``--mount=...`` flags from ``RUN`` instructions.
Handles single-line flags, multi-line continuations, and multiple ``--mount`` flags spread across continuation lines. Only leading ``--mount`` flags are removed (before the actual command starts).
Daytona's ``Image.from_dockerfile`` does not support BuildKit ``--mount`` syntax. This helper strips the flags so that standard Dockerfiles (like the ones generated by ``openenv build``) can be used directly. """ import re
def strip_leading_mounts(text: str) -> str: remaining = text while True: match = re.match(r"\s*--mount=\S+\s*", remaining) if not match: return remaining remaining = remaining[match.end() :]
lines = dockerfile_content.split("\n") result: list[str] = [] in_run = False in_mount_prefix = False
for line in lines: line_out = line run_start = False if re.match(r"\s*RUN(\s+|$)", line, flags=re.IGNORECASE): in_run = True in_mount_prefix = True run_start = True
if in_run and in_mount_prefix: original_ends_with_slash = line_out.rstrip().endswith("\\") if run_start: match = re.match(r"(\s*RUN\s+)(.*)$", line_out, flags=re.IGNORECASE) if match: run_prefix, remainder = match.group(1), match.group(2) else: run_prefix, remainder = line_out, "" new_remainder = strip_leading_mounts(remainder) line_out = run_prefix + new_remainder content_for_check = new_remainder else: new_remainder = strip_leading_mounts(line_out) line_out = new_remainder content_for_check = new_remainder
if original_ends_with_slash and not line_out.rstrip().endswith("\\"): line_out = line_out.rstrip() + " \\"
if content_for_check.strip() not in ("", "\\"): in_mount_prefix = False
if in_run and not line_out.rstrip().endswith("\\"): in_run = False in_mount_prefix = False
result.append(line_out)
return "\n".join(result)
@classmethod def image_from_dockerfile( cls, dockerfile_path: str, context_dir: str | None = None, ) -> str: """Validate a Dockerfile and return a ``dockerfile:`` URI for :meth:`start_container`.
Eagerly validates the Dockerfile (existence, COPY sources, BuildKit stripping) and stores the processed content in an internal registry. The actual ``daytona.Image`` is created later inside ``start_container``.
Args: dockerfile_path: Path to the Dockerfile on disk. context_dir: Build context directory. Defaults to the Dockerfile's grandparent directory, matching the ``openenv init`` convention where Dockerfiles live in ``<env>/server/Dockerfile`` and the build context is ``<env>/``. Pass explicitly for non-standard layouts (e.g. ``context_dir="."`` for repo-root contexts).
Returns: A ``"dockerfile:<abs_path>"`` string to pass to ``start_container``.
Raises: FileNotFoundError: If *dockerfile_path* does not exist. ValueError: If *context_dir* is given but does not exist, or if COPY sources in the Dockerfile cannot be found under the resolved context directory. """ import pathlib import re
src = pathlib.Path(dockerfile_path).resolve() if not src.is_file(): raise FileNotFoundError(f"Dockerfile not found: {dockerfile_path}")
if context_dir is not None: ctx = pathlib.Path(context_dir) if not ctx.is_dir(): raise ValueError(f"context_dir does not exist: {context_dir}") else: # Default: grandparent of the Dockerfile, matching the # openenv init layout (<env>/server/Dockerfile -> <env>/). ctx = src.parent.parent
content = src.read_text() stripped = cls.strip_buildkit_syntax(content)
# Validate that COPY sources exist under the context directory. # This catches mismatches early (e.g. a Dockerfile expecting repo # root as context when we defaulted to the env directory). for line in stripped.splitlines(): m = re.match(r"^\s*COPY\s+(?!--from=)(\S+)\s+", line, re.IGNORECASE) if not m: continue copy_src = m.group(1) if copy_src.startswith("/"): continue resolved = ctx / copy_src if not resolved.exists() and not any(ctx.glob(copy_src)): raise ValueError( f"Dockerfile COPY source '{copy_src}' not found " f"under context_dir '{ctx}'. This Dockerfile may " f"expect a different build context (e.g. the repo " f"root). Pass context_dir explicitly." )
# Parse CMD from the original Dockerfile so start_container can # use it as a fallback when openenv.yaml is unavailable. parsed_cmd = cls._parse_dockerfile_cmd(content)
cls._dockerfile_registry[str(src)] = { "stripped_content": stripped, "context_dir": str(ctx), "server_cmd": parsed_cmd, }
return f"dockerfile:{src}"
def start_container( self, image: str, port: Optional[int] = None, env_vars: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> str: """ Create a Daytona sandbox from a Docker image or snapshot.
Daytona does not execute the image's CMD (known bug — ENTRYPOINT runs, CMD does not). The server command is resolved in order:
1. Explicit ``cmd`` passed to the constructor. 2. ``cmd`` key in ``**kwargs`` (popped before forwarding). 3. Auto-discovered from ``openenv.yaml`` inside the sandbox. 4. ``CMD`` parsed from the Dockerfile (when *image* came from ``image_from_dockerfile``).
Args: image: Docker image name (e.g. ``"echo-env:latest"``), ``"snapshot:<name>"`` to create from a pre-built snapshot, or ``"dockerfile:<path>"`` returned by :meth:`image_from_dockerfile`. port: Must be ``None`` or ``8000``. Daytona exposes port 8000 via its preview proxy; other ports raise ``ValueError``. env_vars: Environment variables forwarded to the sandbox. **kwargs: ``cmd`` (str) to override the server command; remaining kwargs passed through to ``Daytona.create()``.
Returns: HTTPS preview URL for the sandbox (base_url). """ if port is not None and port != 8000: raise ValueError( f"DaytonaProvider only supports port 8000 (got {port}). " "The Daytona preview proxy routes to port 8000 inside the sandbox." )
# Resolve the server command (may be None; discovery happens after # sandbox creation when we can inspect the filesystem). cmd = kwargs.pop("cmd", None) or self._cmd
# CMD parsed from Dockerfile (populated for "dockerfile:" images). parsed_cmd: Optional[str] = None
# Build creation params create_kwargs: Dict[str, Any] = {} if env_vars: create_kwargs["env_vars"] = env_vars if self._public: create_kwargs["public"] = True if self._auto_stop_interval != 15: create_kwargs["auto_stop_interval"] = self._auto_stop_interval
if image.startswith("snapshot:"): from daytona import CreateSandboxFromSnapshotParams
snapshot_name = image[len("snapshot:") :] params = CreateSandboxFromSnapshotParams( snapshot=snapshot_name, **create_kwargs ) elif image.startswith("dockerfile:"): from daytona import CreateSandboxFromImageParams, Image
dockerfile_path = image[len("dockerfile:") :] meta = self._dockerfile_registry.get(dockerfile_path) if meta is None: raise ValueError( f"No registered Dockerfile metadata for {dockerfile_path}. " "Call DaytonaProvider.image_from_dockerfile() first." )
parsed_cmd = meta.get("server_cmd")
# Build the daytona Image from the pre-stripped content. import pathlib import uuid
ctx = pathlib.Path(meta["context_dir"]) tmp_name = f".daytona-{uuid.uuid4().hex[:8]}.dockerfile" tmp_path = ctx / tmp_name try: tmp_path.write_text(meta["stripped_content"]) daytona_image = Image.from_dockerfile(str(tmp_path)) finally: tmp_path.unlink(missing_ok=True)
img_kwargs: Dict[str, Any] = { "image": daytona_image, **create_kwargs, } if self._resources is not None: img_kwargs["resources"] = self._resources params = CreateSandboxFromImageParams(**img_kwargs) else: from daytona import CreateSandboxFromImageParams
img_kwargs = {"image": image, **create_kwargs} if self._resources is not None: img_kwargs["resources"] = self._resources params = CreateSandboxFromImageParams(**img_kwargs)
# Create sandbox extra: Dict[str, Any] = dict(kwargs) if self._on_snapshot_create_logs is not None: extra["on_snapshot_create_logs"] = self._on_snapshot_create_logs
self._sandbox = self._daytona.create( params, timeout=self._create_timeout, **extra )
try: # Discover server command from openenv.yaml if not explicitly set. if cmd is None: try: cmd = self._discover_server_cmd(self._sandbox) except ValueError: # Fall back to CMD parsed from Dockerfile (if available). if parsed_cmd: cmd = parsed_cmd else: raise
# Wrap in bash -c so compound commands (cd ... && uvicorn ...) # are handled correctly by nohup. Write PID so we can check # if the process crashed later in wait_for_ready(). escaped_cmd = shlex.quote(cmd) self._sandbox.process.exec( f"nohup bash -c {escaped_cmd} > /tmp/openenv-server.log 2>&1 &" " echo $! > /tmp/openenv-server.pid", timeout=10, )
# Get a signed preview URL for port 8000. The token is # embedded in the URL itself so no extra headers are needed. signed = self._sandbox.create_signed_preview_url( 8000, expires_in_seconds=86400 ) self._preview_url = signed.url except Exception: self.stop_container() raise
return self._preview_url
def refresh_preview_url(self) -> str: """Get a fresh signed preview URL (valid for 24h).
Daytona signed URLs expire after at most 24 hours. Call this to get a new one for long-running sessions. The returned URL points to the same sandbox — clients will need to reconnect using it. """ if self._sandbox is None: raise RuntimeError("No active sandbox to refresh URL for.") signed = self._sandbox.create_signed_preview_url(8000, expires_in_seconds=86400) self._preview_url = signed.url return self._preview_url
def stop_container(self) -> None: """Delete the Daytona sandbox.""" if self._sandbox is None: return
try: self._daytona.delete(self._sandbox) finally: self._sandbox = None self._preview_url = None
def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: """ Poll the /health endpoint until the sandbox is ready.
Uses a longer default timeout (120s) than Docker providers because Daytona sandboxes may have cold-start latency.
Args: base_url: Preview URL returned by ``start_container()``. timeout_s: Maximum seconds to wait.
Raises: TimeoutError: If the sandbox doesn't become ready in time. RuntimeError: If the server process died (detected via PID check). """ import requests
health_url = f"{base_url}/health"
deadline = time.time() + timeout_s while time.time() < deadline: try: response = requests.get(health_url, timeout=5.0) if response.status_code == 200: return except requests.RequestException: pass
# Early exit: if the server process died, raise immediately # instead of waiting for the full health-check timeout. if self._sandbox is not None: resp = self._sandbox.process.exec( "kill -0 $(cat /tmp/openenv-server.pid) 2>/dev/null" " && echo RUNNING || echo DEAD", timeout=10, ) out = resp.result if hasattr(resp, "result") else str(resp) if "DEAD" in (out or ""): log_resp = self._sandbox.process.exec( "cat /tmp/openenv-server.log 2>/dev/null", timeout=10 ) log = ( log_resp.result if hasattr(log_resp, "result") else str(log_resp) ) raise RuntimeError(f"Server process died.\nLog:\n{log}")
time.sleep(1.0)
raise TimeoutError( f"Daytona sandbox at {base_url} did not become ready within {timeout_s}s" )7 unmodified lines89101112131415161718192097 unmodified lines11811912012112212312429 unmodified lines15415515615715815916016116216362 unmodified lines22622722822923023123223323423523623723823937 unmodified lines2772782792802812827 unmodified lines2902912922937 unmodified linesContainer provider abstractions for running environment servers.This module provides a pluggable architecture for different container providers(local Docker, Kubernetes, cloud providers, etc.) to be used with HTTPEnvClient."""from __future__ import annotationsfrom abc import ABC, abstractmethodfrom typing import Any, Dict, Optionalclass ContainerProvider(ABC):97 unmodified linescapture_output=True,timeout=5,)except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):raise RuntimeError("Docker is not available. Please install Docker Desktop or Docker Engine.")29 unmodified lines# Build docker run commandcmd = ["docker", "run","-d", # Detached"--name", self._container_name,"-p", f"{port}:8000", # Map port]# Add environment variables62 unmodified linesTimeoutError: If container doesn't become ready"""import timeimport requestsstart_time = time.time()health_url = f"{base_url}/health"while time.time() - start_time < timeout_s:try:response = requests.get(health_url, timeout=2.0)if response.status_code == 200:returnexcept requests.RequestException:37 unmodified linesreturn f"{clean_image}-{timestamp}"class KubernetesProvider(ContainerProvider):"""Container provider for Kubernetes clusters.7 unmodified lines>>> # Pod running in k8s, accessible via service or port-forward>>> provider.stop_container()"""pass7 unmodified lines89101112131415161718192097 unmodified lines11811912012112212312412512612712829 unmodified lines15815916016116216316416516616716816917062 unmodified lines23323423523623723823924024124224324424524624724824925037 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945957 unmodified lines6036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686697 unmodified linesContainer provider abstractions for running environment servers.This module provides a pluggable architecture for different container providers(local Docker, Kubernetes, cloud providers, etc.) to be used with EnvClient."""from __future__ import annotationsfrom abc import ABC, abstractmethodfrom typing import Any, Dict, Optional, Sequenceclass ContainerProvider(ABC):97 unmodified linescapture_output=True,timeout=5,)except (subprocess.CalledProcessError,FileNotFoundError,subprocess.TimeoutExpired,):raise RuntimeError("Docker is not available. Please install Docker Desktop or Docker Engine.")29 unmodified lines# Build docker run commandcmd = ["docker","run","-d", # Detached"--name",self._container_name,"-p",f"{port}:8000", # Map port]# Add environment variables62 unmodified linesTimeoutError: If container doesn't become ready"""import timeimport requestsstart_time = time.time()health_url = f"{base_url}/health"# Bypass proxy for localhost to avoid proxy issuesproxies = {"http": None, "https": None}while time.time() - start_time < timeout_s:try:response = requests.get(health_url, timeout=2.0, proxies=proxies)if response.status_code == 200:returnexcept requests.RequestException:37 unmodified linesreturn f"{clean_image}-{timestamp}"class DockerSwarmProvider(ContainerProvider):"""Container provider that uses Docker Swarm services for local concurrency.This provider creates a replicated Swarm service backed by the local Dockerengine. The built-in load-balancer fans requests across the replicas,allowing multiple container instances to run concurrently on the developerworkstation (mirroring the workflow described in the Docker stack docs)."""def __init__(self,*,auto_init_swarm: bool = True,overlay_network: Optional[str] = None,):"""Args:auto_init_swarm: Whether to call ``docker swarm init`` when Swarmis not active. Otherwise, user must manually initialize Swarm.overlay_network: Optional overlay network name for the service.When provided, the network is created with``docker network create --driver overlay --attachable`` if itdoes not already exist."""self._service_name: Optional[str] = Noneself._service_id: Optional[str] = Noneself._published_port: Optional[int] = Noneself._overlay_network = overlay_networkself._auto_init_swarm = auto_init_swarmself._ensure_docker_available()self._ensure_swarm_initialized()if self._overlay_network:self._ensure_overlay_network(self._overlay_network)def start_container(self,image: str,port: Optional[int] = None,env_vars: Optional[Dict[str, str]] = None,**kwargs: Any,) -> str:"""Start (or scale) a Swarm service for the given image.Supported kwargs:replicas (int): Number of container replicas (default: 2).cpu_limit (float | str): CPU limit passed to ``--limit-cpu``.memory_limit (str): Memory limit passed to ``--limit-memory``.constraints (Sequence[str]): Placement constraints.labels (Dict[str, str]): Service labels.command (Sequence[str] | str): Override container command."""import shleximport subprocessimport timeallowed_kwargs = {"replicas","cpu_limit","memory_limit","constraints","labels","command",}unknown = set(kwargs) - allowed_kwargsif unknown:raise ValueError(f"Unsupported kwargs for DockerSwarmProvider: {unknown}")replicas = int(kwargs.get("replicas", 2))cpu_limit = kwargs.get("cpu_limit")memory_limit = kwargs.get("memory_limit")constraints: Optional[Sequence[str]] = kwargs.get("constraints")labels: Optional[Dict[str, str]] = kwargs.get("labels")command_override = kwargs.get("command")if port is None:port = self._find_available_port()self._service_name = self._generate_service_name(image)self._published_port = portcmd = ["docker","service","create","--detach","--name",self._service_name,"--replicas",str(max(1, replicas)),"--publish",f"{port}:8000",]if self._overlay_network:cmd.extend(["--network", self._overlay_network])if env_vars:for key, value in env_vars.items():cmd.extend(["--env", f"{key}={value}"])if cpu_limit is not None:cmd.extend(["--limit-cpu", str(cpu_limit)])if memory_limit is not None:cmd.extend(["--limit-memory", str(memory_limit)])if constraints:for constraint in constraints:cmd.extend(["--constraint", constraint])if labels:for key, value in labels.items():cmd.extend(["--label", f"{key}={value}"])cmd.append(image)if command_override:if isinstance(command_override, str):cmd.extend(shlex.split(command_override))else:cmd.extend(command_override)try:result = subprocess.run(cmd,capture_output=True,text=True,check=True,)self._service_id = result.stdout.strip()except subprocess.CalledProcessError as e:error_msg = ("Failed to start Docker Swarm service.\n"f"Command: {' '.join(cmd)}\n"f"Exit code: {e.returncode}\n"f"Stdout: {e.stdout}\n"f"Stderr: {e.stderr}")raise RuntimeError(error_msg) from e# Give Swarm a brief moment to schedule the tasks.time.sleep(1.0)return f"http://localhost:{port}"def stop_container(self) -> None:"""Remove the Swarm service (and keep the Swarm manager running)."""if not self._service_name:returnimport subprocesstry:subprocess.run(["docker", "service", "rm", self._service_name],capture_output=True,check=True,timeout=10,)except subprocess.CalledProcessError:# Service may already be gone; ignore.passfinally:self._service_name = Noneself._service_id = Noneself._published_port = Nonedef wait_for_ready(self, base_url: str, timeout_s: float = 30.0) -> None:"""Wait for at least one replica to become healthy by polling /health.Note: With Swarm's load balancer, requests round-robin across replicas,so this only verifies that at least one replica is responding. Somereplicas may still be starting when this returns."""import timeimport requestsdeadline = time.time() + timeout_shealth_url = f"{base_url}/health"# Bypass proxy for localhost to avoid proxy issuesproxies = {"http": None, "https": None}while time.time() < deadline:try:response = requests.get(health_url, timeout=2.0, proxies=proxies)if response.status_code == 200:returnexcept requests.RequestException:passtime.sleep(0.5)raise TimeoutError(f"Swarm service at {base_url} did not become ready within {timeout_s}s")def _ensure_docker_available(self) -> None:import subprocesstry:subprocess.run(["docker", "version"],check=True,capture_output=True,timeout=5,)except (subprocess.CalledProcessError,FileNotFoundError,subprocess.TimeoutExpired,) as exc:raise RuntimeError("Docker is not available. Please install Docker Desktop or Docker Engine.") from excdef _ensure_swarm_initialized(self) -> None:import subprocesstry:result = subprocess.run(["docker", "info", "--format", "{{.Swarm.LocalNodeState}}"],capture_output=True,text=True,check=True,timeout=5,)state = result.stdout.strip().lower()if state == "active":returnexcept subprocess.CalledProcessError:state = "unknown"if not self._auto_init_swarm:raise RuntimeError(f"Docker Swarm is not active (state={state}). Enable Swarm manually or pass auto_init_swarm=True.")try:subprocess.run(["docker", "swarm", "init"],check=True,capture_output=True,timeout=10,)except subprocess.CalledProcessError as e:raise RuntimeError("Failed to initialize Docker Swarm") from edef _ensure_overlay_network(self, network: str) -> None:import subprocessinspect = subprocess.run(["docker", "network", "inspect", network],capture_output=True,text=True,check=False,)if inspect.returncode == 0:returntry:subprocess.run(["docker","network","create","--driver","overlay","--attachable",network,],check=True,capture_output=True,timeout=10,)except subprocess.CalledProcessError as e:raise RuntimeError(f"Failed to create overlay network '{network}'") from edef _find_available_port(self) -> int:import socketwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:s.bind(("", 0))s.listen(1)port = s.getsockname()[1]return portdef _generate_service_name(self, image: str) -> str:import timeclean_image = image.split("/")[-1].split(":")[0]timestamp = int(time.time() * 1000)return f"{clean_image}-swarm-{timestamp}"class KubernetesProvider(ContainerProvider):"""Container provider for Kubernetes clusters.7 unmodified lines>>> # Pod running in k8s, accessible via service or port-forward>>> provider.stop_container()"""passclass RuntimeProvider(ABC):"""Abstract base class for runtime providers that are not container providers.Providers implement this interface to support different runtime platforms:- UVProvider: Runs environments via `uv run`The provider manages a single runtime lifecycle and provides the base URLfor connecting to it.Example:>>> provider = UVProvider(project_path="/path/to/env")>>> base_url = provider.start()>>> print(base_url) # http://localhost:8000>>> provider.stop()"""@abstractmethoddef start(self,port: Optional[int] = None,env_vars: Optional[Dict[str, str]] = None,**kwargs: Any,) -> str:"""Start a runtime from the specified image.Args:image: Runtime image nameport: Port to expose (if None, provider chooses)env_vars: Environment variables for the runtime**kwargs: Additional runtime options"""@abstractmethoddef stop(self) -> None:"""Stop the runtime."""pass@abstractmethoddef wait_for_ready(self, timeout_s: float = 30.0) -> None:"""Wait for the runtime to be ready to accept requests."""passdef __enter__(self) -> "RuntimeProvider":"""Enter the runtime provider."""self.start()return selfdef __exit__(self, exc_type, exc, tb) -> None:"""Exit the runtime provider."""self.stop()return False
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224"""Providers for launching ASGI applications via ``uv run``."""
from __future__ import annotations
import osimport socketimport subprocessimport timefrom typing import Dict, Optional
import requests
from .providers import RuntimeProvider
def _check_uv_installed() -> None: try: subprocess.check_output(["uv", "--version"]) except FileNotFoundError as exc: raise RuntimeError( "`uv` executable not found. Install uv from https://docs.astral.sh and ensure it is on PATH." ) from exc
def _find_free_port() -> int: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind(("", 0)) sock.listen(1) return sock.getsockname()[1]
def _create_uv_command( *, host: str, port: int, reload: bool, workers: int, app: str, project_path: str,) -> list[str]: command: list[str] = ["uv", "run", "--isolated", "--project", project_path]
command.append("--") command.extend( [ "uvicorn", app, "--host", host, "--port", str(port), "--workers", str(workers), ] )
if reload: command.append("--reload")
return command
def _poll_health(health_url: str, timeout_s: float) -> None: """Poll a health endpoint until it returns HTTP 200 or times out."""
deadline = time.time() + timeout_s while time.time() < deadline: try: timeout = max(0.0001, min(deadline - time.time(), 2.0)) response = requests.get(health_url, timeout=timeout) if response.status_code == 200: return except requests.RequestException: continue
time.sleep(0.5)
raise TimeoutError(f"Server did not become ready within {timeout_s:.1f} seconds")
class UVProvider(RuntimeProvider): """ RuntimeProvider implementation backed by ``uv run``.
Args: project_path: Local path to a uv project (passed to ``uv run --project``) app: ASGI application path for uvicorn (defaults to ``server.app:app``) host: Host interface to bind to (defaults to ``0.0.0.0``) reload: Whether to enable uvicorn's reload mode env_vars: Environment variables to pass through to the spawned process context_timeout_s: How long to wait for the environment to become ready
Example: >>> provider = UVProvider(project_path="/path/to/env") >>> base_url = provider.start() >>> print(base_url) # http://localhost:8000 >>> # Use the environment via base_url >>> provider.stop() """
def __init__( self, *, project_path: str, app: str = "server.app:app", host: str = "0.0.0.0", reload: bool = False, env_vars: Optional[Dict[str, str]] = None, context_timeout_s: float = 60.0, ): """Initialize the UVProvider.""" self.project_path = os.path.abspath(project_path) self.app = app self.host = host self.reload = reload self.env_vars = env_vars self.context_timeout_s = context_timeout_s _check_uv_installed() self._process = None self._base_url = None
def start( self, port: Optional[int] = None, env_vars: Optional[Dict[str, str]] = None, workers: int = 1, **_: Dict[str, str], ) -> str: """ Start the environment via `uv run`.
Args: port: The port to bind the environment to env_vars: Environment variables to pass to the environment workers: The number of workers to use
Returns: The base URL of the environment
Raises: RuntimeError: If the environment is already running """ if self._process is not None and self._process.poll() is None: raise RuntimeError("UVProvider is already running")
bind_port = port or _find_free_port()
command = _create_uv_command( host=self.host, port=bind_port, reload=self.reload, workers=workers, app=self.app, project_path=self.project_path, )
env = os.environ.copy()
if self.env_vars: env.update(self.env_vars) if env_vars: env.update(env_vars)
try: self._process = subprocess.Popen(command, env=env) except OSError as exc: raise RuntimeError(f"Failed to launch `uv run`: {exc}") from exc
client_host = "127.0.0.1" if self.host in {"0.0.0.0", "::"} else self.host self._base_url = f"http://{client_host}:{bind_port}" return self._base_url
def wait_for_ready(self, timeout_s: float = 60.0) -> None: """ Wait for the environment to become ready.
Args: timeout_s: The timeout to wait for the environment to become ready
Raises: RuntimeError: If the environment is not running TimeoutError: If the environment does not become ready within the timeout """ if self._process and self._process.poll() is not None: code = self._process.returncode raise RuntimeError(f"uv process exited prematurely with code {code}")
_poll_health(f"{self._base_url}/health", timeout_s=timeout_s)
def stop(self) -> None: """ Stop the environment.
Raises: RuntimeError: If the environment is not running """ if self._process is None: return
if self._process.poll() is None: self._process.terminate() try: self._process.wait(timeout=10.0) except subprocess.TimeoutExpired: self._process.kill() self._process.wait(timeout=5.0)
self._process = None self._base_url = None
@property def base_url(self) -> str: """ The base URL of the environment.
Returns: The base URL of the environment
Raises: RuntimeError: If the environment is not running """ if self._base_url is None: raise RuntimeError("UVProvider has not been started") return self._base_url15 unmodified lines161718192021222363 unmodified lines8788899091929313 unmodified lines10710810911011111211311411511611712 unmodified lines13013113213313413561 unmodified lines19719819920020120220320415 unmodified linessys.path.insert(0, str(Path(__file__).parent.parent.parent))import requestsfrom core.containers.runtime import LocalDockerProvider# TODO: Remove this test or make it a functional test sicne this will be tested in e2e test for echo envdef test_local_docker_provider():63 unmodified linesprint(f" Length: {data['observation']['message_length']}")print(f" Reward: {data['reward']}")assert response.status_code == 200assert data["observation"]["echoed_message"] == "Hello from LocalDockerProvider!"assert data["observation"]["message_length"] == 31print("✓ Step test passed\n")13 unmodified linesfor i in range(3):response = requests.post(f"{base_url}/step",json={"action": {"message": f"Message {i+1}"}},headers={"Content-Type": "application/json"},)assert response.status_code == 200print(f" Step {i+1}: ✓")# Check state updatedresponse = requests.get(f"{base_url}/state")12 unmodified linesexcept Exception as e:print(f"\n❌ Test failed: {e}")import tracebacktraceback.print_exc()return False61 unmodified linesprint("Starting container with environment variables...")base_url = provider.start_container("echo-env:latest",env_vars={"DEBUG": "true", "LOG_LEVEL": "info"})print(f"✓ Started at: {base_url}")15 unmodified lines161718192021222363 unmodified lines87888990919293949513 unmodified lines10911011111211311411511611711811912 unmodified lines13213313413513613713861 unmodified lines20020120220320420520615 unmodified linessys.path.insert(0, str(Path(__file__).parent.parent.parent))import requestsfrom openenv.core.containers.runtime import LocalDockerProvider# TODO: Remove this test or make it a functional test sicne this will be tested in e2e test for echo envdef test_local_docker_provider():63 unmodified linesprint(f" Length: {data['observation']['message_length']}")print(f" Reward: {data['reward']}")assert response.status_code == 200assert (data["observation"]["echoed_message"] == "Hello from LocalDockerProvider!")assert data["observation"]["message_length"] == 31print("✓ Step test passed\n")13 unmodified linesfor i in range(3):response = requests.post(f"{base_url}/step",json={"action": {"message": f"Message {i + 1}"}},headers={"Content-Type": "application/json"},)assert response.status_code == 200print(f" Step {i + 1}: ✓")# Check state updatedresponse = requests.get(f"{base_url}/state")12 unmodified linesexcept Exception as e:print(f"\n❌ Test failed: {e}")import tracebacktraceback.print_exc()return False61 unmodified linesprint("Starting container with environment variables...")base_url = provider.start_container("echo-env:latest", env_vars={"DEBUG": "true", "LOG_LEVEL": "info"})print(f"✓ Started at: {base_url}")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Environment client for persistent sessions.
This module provides a WebSocket-based client that maintains a persistent connectionto an environment server, enabling efficient multi-step interactions withoutthe overhead of HTTP request/response cycles.
The client is async by default. For synchronous usage, use the `.sync()` methodto get a `SyncEnvClient` wrapper.
Example (async): >>> async with GenericEnvClient(base_url="ws://localhost:8000") as env: ... result = await env.reset() ... result = await env.step({"code": "print('hello')"})
Example (sync wrapper): >>> env = GenericEnvClient(base_url="ws://localhost:8000").sync() >>> with env: ... result = env.reset() ... result = env.step({"code": "print('hello')"})"""
from __future__ import annotations
import asyncioimport jsonimport osfrom abc import ABC, abstractmethodfrom typing import Any, Dict, Generic, Optional, Type, TYPE_CHECKING, TypeVar
from .client_types import StateT, StepResultfrom .containers.runtime import LocalDockerProvider, UVProviderfrom .utils import convert_to_ws_url
if TYPE_CHECKING: from websockets.asyncio.client import ClientConnection
from .containers.runtime import ContainerProvider, RuntimeProvider from .sync_client import SyncEnvClient
from websockets.asyncio.client import connect as ws_connect
ActT = TypeVar("ActT")ObsT = TypeVar("ObsT")EnvClientT = TypeVar("EnvClientT", bound="EnvClient")
class EnvClient(ABC, Generic[ActT, ObsT, StateT]): """ Async environment client for persistent sessions.
This client maintains a persistent WebSocket connection to an environment server, enabling efficient multi-step interactions. Each client instance corresponds to a dedicated environment session on the server.
The client is async by default. For synchronous usage, use the `.sync()` method to get a `SyncEnvClient` wrapper.
Features: - Lower latency for sequential interactions - Session state is maintained server-side - Better suited for long-running episodes - Async by default for modern Python async/await patterns
Example (async): >>> from envs.coding_env.client import CodingEnv >>> >>> # Connect to a server using async context manager >>> async with CodingEnv(base_url="ws://localhost:8000") as env: ... result = await env.reset(seed=42) ... while not result.done: ... action = agent.predict(result.observation) ... result = await env.step(action)
Example (sync wrapper): >>> env = CodingEnv(base_url="ws://localhost:8000").sync() >>> with env: ... result = env.reset(seed=42) ... result = env.step(action) """
def __init__( self, base_url: str, connect_timeout_s: float = 10.0, message_timeout_s: float = 60.0, max_message_size_mb: float = 100.0, provider: Optional["ContainerProvider | RuntimeProvider"] = None, mode: Optional[str] = None, ): """ Initialize environment client.
Args: base_url: Base URL of the environment server (http:// or ws://). Will be converted to ws:// if http:// is provided. connect_timeout_s: Timeout for establishing WebSocket connection message_timeout_s: Timeout for receiving responses to messages max_message_size_mb: Maximum WebSocket message size in megabytes. Default 100MB to handle large observations (screenshots, DOM, etc.) provider: Optional container/runtime provider for lifecycle management. Can be a ContainerProvider (Docker) or RuntimeProvider (UV). mode: Communication mode: 'simulation' for Gym-style API (default) or 'production' for MCP JSON-RPC protocol. Can also be set via the OPENENV_CLIENT_MODE environment variable. Constructor parameter takes precedence over environment variable. Case-insensitive. """ # Determine mode (constructor > env var > default) if mode is None: mode = os.environ.get("OPENENV_CLIENT_MODE", "simulation")
# Normalize and validate mode mode = mode.lower() if mode not in ("simulation", "production"): raise ValueError( f"Invalid mode: '{mode}'. Must be 'simulation' or 'production'. " f"Set via constructor parameter or OPENENV_CLIENT_MODE environment variable." )
# Store mode (use object.__setattr__ to bypass immutability) object.__setattr__(self, "_mode", mode)
# Convert HTTP URL to WebSocket URL ws_url = convert_to_ws_url(base_url)
self._ws_url = f"{ws_url}/ws" self._connect_timeout = connect_timeout_s self._message_timeout = message_timeout_s self._max_message_size = int( max_message_size_mb * 1024 * 1024 ) # Convert MB to bytes self._provider = provider self._ws: Optional[ClientConnection] = None
def __setattr__(self, name: str, value: Any) -> None: """Prevent modification of _mode after initialization.""" if name == "_mode" and hasattr(self, "_mode"): raise AttributeError("Cannot modify mode after initialization") super().__setattr__(name, value)
async def connect(self) -> "EnvClient": """ Establish WebSocket connection to the server.
Returns: self for method chaining
Raises: ConnectionError: If connection cannot be established """ if self._ws is not None: return self
# Bypass proxy for localhost connections ws_url_lower = self._ws_url.lower() is_localhost = "localhost" in ws_url_lower or "127.0.0.1" in ws_url_lower
old_no_proxy = os.environ.get("NO_PROXY") if is_localhost: # Set NO_PROXY to bypass proxy for localhost current_no_proxy = old_no_proxy or "" if "localhost" not in current_no_proxy.lower(): os.environ["NO_PROXY"] = ( f"{current_no_proxy},localhost,127.0.0.1" if current_no_proxy else "localhost,127.0.0.1" )
try: self._ws = await ws_connect( self._ws_url, open_timeout=self._connect_timeout, max_size=self._max_message_size, ) except Exception as e: raise ConnectionError(f"Failed to connect to {self._ws_url}: {e}") from e finally: # Restore original NO_PROXY value if is_localhost: if old_no_proxy is None: os.environ.pop("NO_PROXY", None) else: os.environ["NO_PROXY"] = old_no_proxy
return self
async def disconnect(self) -> None: """Close the WebSocket connection.""" if self._ws is not None: try: # Send close message await self._send({"type": "close"}) except Exception: pass # Best effort try: await self._ws.close() except Exception: pass self._ws = None
async def _ensure_connected(self) -> None: """Ensure WebSocket connection is established.""" if self._ws is None: await self.connect()
async def _send(self, message: Dict[str, Any]) -> None: """Send a message over the WebSocket.""" await self._ensure_connected() assert self._ws is not None await self._ws.send(json.dumps(message))
async def _receive(self) -> Dict[str, Any]: """Receive and parse a message from the WebSocket.""" assert self._ws is not None raw = await asyncio.wait_for(self._ws.recv(), timeout=self._message_timeout) return json.loads(raw)
async def _send_and_receive(self, message: Dict[str, Any]) -> Dict[str, Any]: """Send a message and wait for response.""" await self._send(message) response = await self._receive()
# Check for error response if response.get("type") == "error": error_data = response.get("data", {}) raise RuntimeError( f"Server error: {error_data.get('message', 'Unknown error')} " f"(code: {error_data.get('code', 'UNKNOWN')})" )
return response
@classmethod async def from_docker_image( cls: Type[EnvClientT], image: str, provider: Optional["ContainerProvider"] = None, **kwargs: Any, ) -> EnvClientT: """ Create an environment client by spinning up a Docker container.
Args: image: Docker image name to run (e.g., "coding-env:latest") provider: Container provider to use (defaults to LocalDockerProvider) **kwargs: Additional arguments to pass to provider.start_container()
Returns: Connected client instance """ if provider is None: provider = LocalDockerProvider()
# Start container base_url = provider.start_container(image, **kwargs)
# Wait for server to be ready provider.wait_for_ready(base_url)
# Create and connect client client = cls(base_url=base_url, provider=provider) await client.connect()
return client
@classmethod async def from_env( cls: Type[EnvClientT], repo_id: str, *, use_docker: bool = True, provider: Optional["ContainerProvider | RuntimeProvider"] = None, **provider_kwargs: Any, ) -> EnvClientT: """ Create a client from a Hugging Face Space.
Args: repo_id: Hugging Face space identifier ``{org}/{space}``. use_docker: When ``True`` (default) pull from the HF registry and launch via :class:`LocalDockerProvider`. When ``False`` run the space locally with :class:`UVProvider`. provider: Optional provider instance to reuse. Must be a :class:`ContainerProvider` when ``use_docker=True`` and a :class:`RuntimeProvider` otherwise. provider_kwargs: Additional keyword arguments forwarded to either the container provider's ``start_container`` (docker) or to the ``UVProvider`` constructor/start (uv). When ``use_docker=False``, the ``project_path`` argument can be used to override the default git URL (``git+https://huggingface.co/spaces/{repo_id}``).
Returns: Connected client instance
Examples: >>> # Pull and run from HF Docker registry >>> env = await MyEnv.from_env("openenv/echo-env") >>> >>> # Run locally with UV (clones the space) >>> env = await MyEnv.from_env("openenv/echo-env", use_docker=False) >>> >>> # Run from a local checkout >>> env = await MyEnv.from_env( ... "openenv/echo-env", ... use_docker=False, ... project_path="/path/to/local/checkout" ... ) """ # Extract start args that apply to both providers start_args = {} for key in ("port", "env_vars", "workers"): if key in provider_kwargs: start_args[key] = provider_kwargs.pop(key)
if use_docker: # Docker mode: pull from HF registry docker_provider = provider or LocalDockerProvider() tag = provider_kwargs.pop("tag", "latest") image = f"registry.hf.space/{repo_id.replace('/', '-')}:{tag}" base_url = docker_provider.start_container( image, **start_args, **provider_kwargs ) docker_provider.wait_for_ready(base_url)
client = cls(base_url=base_url, provider=docker_provider) await client.connect() return client else: # UV mode: clone and run with uv if provider is None: uv_kwargs = dict(provider_kwargs) project_path = uv_kwargs.pop("project_path", None) if project_path is None: project_path = f"git+https://huggingface.co/spaces/{repo_id}"
provider = UVProvider(project_path=project_path, **uv_kwargs) else: if provider_kwargs: raise ValueError( "provider_kwargs cannot be used when supplying a provider instance" )
base_url = provider.start(**start_args) provider.wait_for_ready()
client = cls(base_url=base_url, provider=provider) await client.connect() return client
@abstractmethod def _step_payload(self, action: ActT) -> Dict[str, Any]: """Convert an Action object to the JSON data expected by the env server.""" raise NotImplementedError
@abstractmethod def _parse_result(self, payload: Dict[str, Any]) -> StepResult[ObsT]: """Convert a JSON response from the env server to StepResult[ObsT].""" raise NotImplementedError
@abstractmethod def _parse_state(self, payload: Dict[str, Any]) -> StateT: """Convert a JSON response from the state endpoint to a State object.""" raise NotImplementedError
async def reset(self, **kwargs: Any) -> StepResult[ObsT]: """ Reset the environment with optional parameters.
Args: **kwargs: Optional parameters passed to the environment's reset method. Common parameters include: - seed: Random seed for reproducibility - episode_id: Custom episode identifier
Returns: StepResult containing initial observation """ message = { "type": "reset", "data": kwargs, } response = await self._send_and_receive(message) return self._parse_result(response.get("data", {}))
async def step(self, action: ActT, **kwargs: Any) -> StepResult[ObsT]: """ Execute an action in the environment.
Args: action: The action to execute **kwargs: Optional parameters (currently ignored)
Returns: StepResult containing observation, reward, and done status """ message = { "type": "step", "data": self._step_payload(action), } response = await self._send_and_receive(message) return self._parse_result(response.get("data", {}))
async def state(self) -> StateT: """ Get the current environment state from the server.
Returns: State object with environment state information """ message = {"type": "state"} response = await self._send_and_receive(message) return self._parse_state(response.get("data", {}))
async def close(self) -> None: """ Close the WebSocket connection and clean up resources.
If this client was created via from_docker_image() or from_env(), this will also stop and remove the associated container/process. """ await self.disconnect()
if self._provider is not None: # Handle both ContainerProvider and RuntimeProvider if hasattr(self._provider, "stop_container"): self._provider.stop_container() elif hasattr(self._provider, "stop"): self._provider.stop()
async def __aenter__(self) -> "EnvClient": """Enter async context manager, ensuring connection is established.""" await self.connect() return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: """Exit async context manager, closing connection.""" await self.close()
def __enter__(self) -> "EnvClient": """Sync context manager entry - raises error suggesting async usage.""" raise TypeError( "EnvClient is async by default. Use 'async with' instead of 'with', " "or call .sync() to get a synchronous wrapper:\n" " async with client: # async usage\n" " with client.sync(): # sync wrapper" )
def __exit__(self, exc_type, exc_val, exc_tb) -> None: """Sync context manager exit - should not be reached.""" pass # pragma: no cover
def sync(self) -> "SyncEnvClient": """ Return a synchronous wrapper around this async client.
Use this method when you need synchronous access to the environment without async/await syntax. This is useful for: - Integration with synchronous codebases - Interactive/REPL usage - Stopping async from "infecting" the call stack
Returns: SyncEnvClient wrapper that provides synchronous methods
Example: >>> # Create async client and get sync wrapper >>> async_client = GenericEnvClient(base_url="http://localhost:8000") >>> sync_client = async_client.sync() >>> >>> # Use synchronous API >>> with sync_client: ... result = sync_client.reset() ... result = sync_client.step({"code": "print('hello')"}) """ from .sync_client import SyncEnvClient
return SyncEnvClient(self)6 unmodified lines789101112131415165 unmodified lines2223242526274 unmodified lines323334356 unmodified lines"""Core environment interfaces and types."""from .base_transforms import CompositeTransform, NullTransformfrom .http_server import HTTPEnvServer, create_app, create_fastapi_appfrom .interfaces import Environment, Message, ModelTokenizer, Transformfrom .types import Action, Observation, Statefrom .web_interface import create_web_interface_app, WebInterfaceManager__all__ = [# Core interfaces5 unmodified lines"Action","Observation","State",# Base transforms"CompositeTransform","NullTransform",4 unmodified lines# Web Interface"create_web_interface_app","WebInterfaceManager",]6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879805 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171184 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491506 unmodified lines"""Core environment interfaces and types."""from .base_transforms import CompositeTransform, NullTransformfrom .exceptions import (ConcurrencyConfigurationError,EnvironmentFactoryError,OpenEnvError,SessionCapacityError,SessionCreationError,SessionNotFoundError,)from .http_server import create_app, create_fastapi_app, HTTPEnvServerfrom .interfaces import Environment, Message, ModelTokenizer, Transformtry:from .mcp_environment import MCPEnvironmentexcept ModuleNotFoundError:MCPEnvironment = None # type: ignore[assignment]from .mcp_types import (CallToolAction,CallToolObservation,JsonRpcError,# JSON-RPC typesJsonRpcErrorCode,JsonRpcRequest,JsonRpcResponse,ListToolsAction,ListToolsObservation,McpMethod,RESERVED_TOOL_NAMES,Tool,ToolError,ToolErrorType,WSMCPMessage,WSMCPResponse,)from .route_config import GetEndpointConfigfrom .serialization import (deserialize_action,deserialize_action_with_preprocessing,serialize_observation,)from .types import (Action,BaseMessage,ConcurrencyConfig,HealthResponse,HealthStatus,Observation,SchemaResponse,ServerCapacityStatus,ServerMode,SessionInfo,State,WSCloseMessage,WSErrorCode,WSErrorResponse,WSIncomingMessage,WSObservationResponse,WSResetMessage,WSStateMessage,WSStateResponse,WSStepMessage,)try:from .web_interface import create_web_interface_app, WebInterfaceManagerexcept ModuleNotFoundError:create_web_interface_app = None # type: ignore[assignment]WebInterfaceManager = None # type: ignore[assignment]__all__ = [# Core interfaces5 unmodified lines"Action","Observation","State","SchemaResponse","HealthResponse",# Enums"HealthStatus","ServerMode","WSErrorCode",# WebSocket message types"BaseMessage","WSIncomingMessage","WSResetMessage","WSStepMessage","WSStateMessage","WSCloseMessage","WSObservationResponse","WSStateResponse","WSErrorResponse",# Concurrency types"ConcurrencyConfig","ServerCapacityStatus","SessionInfo",# Exceptions"OpenEnvError","ConcurrencyConfigurationError","SessionCapacityError","SessionNotFoundError","SessionCreationError","EnvironmentFactoryError",# Base transforms"CompositeTransform","NullTransform",4 unmodified lines# Web Interface"create_web_interface_app","WebInterfaceManager",# Serialization utilities"deserialize_action","deserialize_action_with_preprocessing","serialize_observation",# Route configuration"GetEndpointConfig",# MCP types"Tool","ToolError","ToolErrorType","ListToolsAction","CallToolAction","ListToolsObservation","CallToolObservation","WSMCPMessage","WSMCPResponse","RESERVED_TOOL_NAMES","MCPEnvironment",# JSON-RPC types"JsonRpcErrorCode","JsonRpcError","JsonRpcRequest","JsonRpcResponse","McpMethod",]
25 unmodified lines2627282925 unmodified lines"""Default transform that passes through unchanged."""def __call__(self, observation: Observation) -> Observation:return observation25 unmodified lines2627282925 unmodified lines"""Default transform that passes through unchanged."""def __call__(self, observation: Observation) -> Observation:return observation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Custom exceptions for environment server operations."""
from typing import Optional
class OpenEnvError(Exception): """Base exception for all OpenEnv errors."""
pass
class ConcurrencyConfigurationError(OpenEnvError): """ Raised when an environment is misconfigured for concurrent sessions.
This error is raised during server startup when max_concurrent_envs > 1 is specified for an environment that is not marked as SUPPORTS_CONCURRENT_SESSIONS. """
def __init__( self, environment_name: str, max_concurrent_envs: int, message: Optional[str] = None, ): self.environment_name = environment_name self.max_concurrent_envs = max_concurrent_envs
if message is None: message = ( f"Environment '{environment_name}' is not marked as SUPPORTS_CONCURRENT_SESSIONS. " f"Cannot run with max_concurrent_envs={max_concurrent_envs}. " f"Either set max_concurrent_envs=1 or ensure the environment " f"properly isolates session state and set SUPPORTS_CONCURRENT_SESSIONS=True." )
super().__init__(message)
class SessionCapacityError(OpenEnvError): """ Raised when the server cannot accept new sessions due to capacity limits.
This error is raised when a new WebSocket connection is attempted but the server has already reached max_concurrent_envs active sessions. """
def __init__( self, active_sessions: int, max_sessions: int, message: Optional[str] = None, ): self.active_sessions = active_sessions self.max_sessions = max_sessions
if message is None: message = ( f"Server at capacity: {active_sessions}/{max_sessions} sessions active. " f"Cannot accept new connections." )
super().__init__(message)
class SessionNotFoundError(OpenEnvError): """Raised when attempting to access a session that does not exist."""
def __init__(self, session_id: str, message: Optional[str] = None): self.session_id = session_id
if message is None: message = f"Session '{session_id}' not found."
super().__init__(message)
class SessionCreationError(OpenEnvError): """Raised when a session cannot be created."""
def __init__(self, reason: str, message: Optional[str] = None): self.reason = reason
if message is None: message = f"Failed to create session: {reason}"
super().__init__(message)
class EnvironmentFactoryError(OpenEnvError): """Raised when the environment factory fails to create an instance."""
def __init__(self, factory_name: str, message: Optional[str] = None): self.factory_name = factory_name
if message is None: message = f"Environment factory '{factory_name}' failed to create instance."
super().__init__(message)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Unified terminal-style theme for OpenEnv Gradio UI (light/dark)."""
from __future__ import annotations
import gradio as gr
_MONO_FONTS = ( "JetBrains Mono", "Fira Code", "Cascadia Code", "Consolas", "ui-monospace", "monospace",)
_CORE_FONT = ( "Lato", "Inter", "Arial", "Helvetica", "sans-serif",)
_ZERO_RADIUS = gr.themes.Size( xxs="0px", xs="0px", sm="0px", md="0px", lg="0px", xl="0px", xxl="0px",)
_GREEN_HUE = gr.themes.Color( c50="#e6f4ea", c100="#ceead6", c200="#a8dab5", c300="#6fcc8b", c400="#3fb950", c500="#238636", c600="#1a7f37", c700="#116329", c800="#0a4620", c900="#033a16", c950="#04200d",)
_NEUTRAL_HUE = gr.themes.Color( c50="#f6f8fa", c100="#eaeef2", c200="#d0d7de", c300="#afb8c1", c400="#8c959f", c500="#6e7781", c600="#57606a", c700="#424a53", c800="#32383f", c900="#24292f", c950="#1b1f24",)
OPENENV_GRADIO_THEME = gr.themes.Base( primary_hue=_GREEN_HUE, secondary_hue=_NEUTRAL_HUE, neutral_hue=_NEUTRAL_HUE, font=_CORE_FONT, font_mono=_MONO_FONTS, radius_size=_ZERO_RADIUS,).set( body_background_fill="#ffffff", background_fill_primary="#ffffff", background_fill_secondary="#f6f8fa", block_background_fill="#ffffff", block_border_color="#ffffff", block_label_text_color="#57606a", block_title_text_color="#24292f", border_color_primary="#d0d7de", input_background_fill="#ffffff", input_border_color="#d0d7de", button_primary_background_fill="#1a7f37", button_primary_background_fill_hover="#116329", button_primary_text_color="#ffffff", button_secondary_background_fill="#f6f8fa", button_secondary_background_fill_hover="#eaeef2", button_secondary_text_color="#24292f", button_secondary_border_color="#d0d7de", body_background_fill_dark="#0d1117", background_fill_primary_dark="#0d1117", background_fill_secondary_dark="#0d1117", block_background_fill_dark="#0d1117", block_border_color_dark="#0d1117", block_label_text_color_dark="#8b949e", block_title_text_color_dark="#c9d1d9", border_color_primary_dark="#30363d", input_background_fill_dark="#0d1117", input_border_color_dark="#30363d", button_primary_background_fill_dark="#30363d", button_primary_background_fill_hover_dark="#484f58", button_primary_text_color_dark="#c9d1d9", button_secondary_background_fill_dark="#21262d", button_secondary_background_fill_hover_dark="#30363d", button_secondary_text_color_dark="#c9d1d9", button_secondary_border_color_dark="#30363d",)
OPENENV_GRADIO_CSS = """* { border-radius: 0 !important; }.col-left { padding: 16px !important; }.col-right { padding: 16px !important; }.prose, .markdown-text, .md,.prose > *, .markdown-text > * { background: transparent !important; border: none !important; box-shadow: none !important;}.dark .col-left { border-left-color: rgba(139, 148, 158, 0.4) !important;}.dark .col-right { border-left-color: rgba(201, 209, 217, 0.3) !important;}"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Gradio-based web UI for OpenEnv environments.
Replaces the legacy HTML/JavaScript interface when ENABLE_WEB_INTERFACE is set.Mount at /web via gr.mount_gradio_app() from create_web_interface_app()."""
from __future__ import annotations
import jsonimport refrom typing import Any, Dict, List, Optional
import gradio as gr
from .types import EnvironmentMetadata
def _escape_md(text: str) -> str: """Escape Markdown special characters in user-controlled content.""" return re.sub(r"([\\`*_\{\}\[\]()#+\-.!|~>])", r"\\\1", str(text))
def _format_observation(data: Dict[str, Any]) -> str: """Format reset/step response for Markdown display.""" lines: List[str] = [] obs = data.get("observation", {}) if isinstance(obs, dict): if obs.get("prompt"): lines.append(f"**Prompt:**\n\n{_escape_md(obs['prompt'])}\n") messages = obs.get("messages", []) if messages: lines.append("**Messages:**\n") for msg in messages: sender = _escape_md(str(msg.get("sender_id", "?"))) content = _escape_md(str(msg.get("content", ""))) cat = _escape_md(str(msg.get("category", ""))) lines.append(f"- `[{cat}]` Player {sender}: {content}") lines.append("") reward = data.get("reward") done = data.get("done") if reward is not None: lines.append(f"**Reward:** `{reward}`") if done is not None: lines.append(f"**Done:** `{done}`") return "\n".join(lines) if lines else "*No observation data*"
def _readme_section(metadata: Optional[EnvironmentMetadata]) -> str: """README content for the left panel.""" if not metadata or not metadata.readme_content: return "*No README available.*" return metadata.readme_content
def get_gradio_display_title( metadata: Optional[EnvironmentMetadata], fallback: str = "OpenEnv Environment",) -> str: """Return the title used for the Gradio app (browser tab and Blocks).""" name = metadata.name if metadata else fallback return f"OpenEnv Agentic Environment: {name}"
def build_gradio_app( web_manager: Any, action_fields: List[Dict[str, Any]], metadata: Optional[EnvironmentMetadata], is_chat_env: bool, title: str = "OpenEnv Environment", quick_start_md: Optional[str] = None,) -> gr.Blocks: """ Build a Gradio Blocks app for the OpenEnv web interface.
Args: web_manager: WebInterfaceManager (reset/step_environment, get_state). action_fields: Field dicts from _extract_action_fields(action_cls). metadata: Environment metadata for README/name. is_chat_env: If True, single message textbox; else form from action_fields. title: App title (overridden by metadata.name when present; see get_gradio_display_title). quick_start_md: Optional Quick Start markdown (class names already replaced).
Returns: gr.Blocks to mount with gr.mount_gradio_app(app, blocks, path="/web"). """ readme_content = _readme_section(metadata) display_title = get_gradio_display_title(metadata, fallback=title)
async def reset_env(): try: data = await web_manager.reset_environment() obs_md = _format_observation(data) return ( obs_md, json.dumps(data, indent=2), "Environment reset successfully.", ) except Exception as e: return ("", "", f"Error: {e}")
def _step_with_action(action_data: Dict[str, Any]): async def _run(): try: data = await web_manager.step_environment(action_data) obs_md = _format_observation(data) return ( obs_md, json.dumps(data, indent=2), "Step complete.", ) except Exception as e: return ("", "", f"Error: {e}")
return _run
async def step_chat(message: str): if not (message or str(message).strip()): return ("", "", "Please enter an action message.") action = {"message": str(message).strip()} return await _step_with_action(action)()
def get_state_sync(): try: data = web_manager.get_state() return json.dumps(data, indent=2) except Exception as e: return f"Error: {e}"
with gr.Blocks(title=display_title) as demo: with gr.Row(): with gr.Column(scale=1, elem_classes="col-left"): if quick_start_md: with gr.Accordion("Quick Start", open=True): gr.Markdown(quick_start_md) with gr.Accordion("README", open=False): gr.Markdown(readme_content)
with gr.Column(scale=2, elem_classes="col-right"): obs_display = gr.Markdown( value=("# Playground\n\nClick **Reset** to start a new episode."), ) with gr.Group(): if is_chat_env: action_input = gr.Textbox( label="Action message", placeholder="e.g. Enter your message...", ) step_inputs = [action_input] step_fn = step_chat else: step_inputs = [] for field in action_fields: name = field["name"] field_type = field.get("type", "text") label = name.replace("_", " ").title() placeholder = field.get("placeholder", "") if field_type == "checkbox": inp = gr.Checkbox(label=label) elif field_type == "number": inp = gr.Number(label=label) elif field_type == "select": choices = field.get("choices") or [] inp = gr.Dropdown( choices=choices, label=label, allow_custom_value=False, ) elif field_type in ("textarea", "tensor"): inp = gr.Textbox( label=label, placeholder=placeholder, lines=3, ) else: inp = gr.Textbox( label=label, placeholder=placeholder, ) step_inputs.append(inp)
async def step_form(*values): if not action_fields: return await _step_with_action({})() action_data = {} for i, field in enumerate(action_fields): if i >= len(values): break name = field["name"] val = values[i] if field.get("type") == "checkbox": action_data[name] = bool(val) elif val is not None and val != "": action_data[name] = val return await _step_with_action(action_data)()
step_fn = step_form
with gr.Row(): step_btn = gr.Button("Step", variant="primary") reset_btn = gr.Button("Reset", variant="secondary") state_btn = gr.Button("Get state", variant="secondary") with gr.Row(): status = gr.Textbox( label="Status", interactive=False, ) raw_json = gr.Code( label="Raw JSON response", language="json", interactive=False, )
reset_btn.click( fn=reset_env, outputs=[obs_display, raw_json, status], ) step_btn.click( fn=step_fn, inputs=step_inputs, outputs=[obs_display, raw_json, status], ) if is_chat_env: action_input.submit( fn=step_fn, inputs=step_inputs, outputs=[obs_display, raw_json, status], ) state_btn.click( fn=get_state_sync, outputs=[raw_json], )
return demo7 unmodified lines8910111213141516171819202122232425262728293031322 unmodified lines3536373839404142433 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242 unmodified lines2272282292302312322337 unmodified linesHTTP server wrapper for Environment instances.This module provides utilities to wrap any Environment subclass and expose itover HTTP endpoints that HTTPEnvClient can consume."""from __future__ import annotationsimport osfrom dataclasses import asdictfrom typing import Any, Dict, Typefrom .interfaces import Environmentfrom .types import Action, Observationfrom fastapi import Body, FastAPIclass HTTPEnvServer:"""HTTP server wrapper for Environment instances.This class wraps an Environment and exposes its reset(), step(), and statemethods as HTTP endpoints compatible with HTTPEnvClient.The server expects:- Action deserialization: Converts JSON dict to Action subclass2 unmodified linesExample:>>> from core.env_server import HTTPEnvServer>>> from envs.coding_env.server import CodeExecutionEnvironment>>>>>> env = CodeExecutionEnvironment()>>> server = HTTPEnvServer(env)>>>>>> # Register routes with FastAPI>>> from fastapi import FastAPI3 unmodified linesdef __init__(self,env: Environment,action_cls: Type[Action],observation_cls: Type[Observation],):"""Initialize HTTP server wrapper.Args:env: The Environment instance to wrapaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returns"""self.env = envself.action_cls = action_clsself.observation_cls = observation_clsdef register_routes(self, app: Any) -> None:"""Register HTTP routes on a FastAPI application.Args:app: FastAPI application instance"""if not isinstance(app, FastAPI):raise TypeError("app must be a FastAPI instance")@app.post("/reset")async def reset(request: Dict[str, Any] = Body(default={})) -> Dict[str, Any]:"""Reset endpoint - returns initial observation."""# TODO: Handle seed, episode_id from request if providedobservation = self.env.reset()return self._serialize_observation(observation)@app.post("/step")async def step(request: Dict[str, Any]) -> Dict[str, Any]:"""Step endpoint - executes action and returns observation."""action_data = request.get("action", {})# TODO: Handle timeout_s, request_id, episode_id from request if provided# Deserialize actionaction = self._deserialize_action(action_data)# Execute stepobservation = self.env.step(action)# Return serialized observationreturn self._serialize_observation(observation)@app.get("/state")async def get_state() -> Dict[str, Any]:"""State endpoint - returns current environment state."""state = self.env.statereturn asdict(state)@app.get("/health")async def health() -> Dict[str, str]:"""Health check endpoint."""return {"status": "healthy"}def _deserialize_action(self, action_data: Dict[str, Any]) -> Action:"""Convert JSON dict to Action instance.Args:action_data: Dictionary containing action dataReturns:Action instanceNote:This is a simple implementation. Subclasses may need to overridefor more complex deserialization logic."""# Remove metadata if present (it will be set via kw_only field)metadata = action_data.pop("metadata", {})action = self.action_cls(**action_data)action.metadata = metadatareturn actiondef _serialize_observation(self, observation: Observation) -> Dict[str, Any]:"""Convert Observation instance to JSON-compatible dict.Args:observation: Observation instanceReturns:Dictionary compatible with HTTPEnvClient._parse_result()The format matches what HTTPEnvClient expects:{"observation": {...}, # Observation fields"reward": float | None,"done": bool,}"""obs_dict = asdict(observation)# Extract reward and done (these are part of StepResult on client side)reward = obs_dict.pop("reward", None)done = obs_dict.pop("done", False)obs_dict.pop("metadata", None) # Remove metadata from observation# Return in HTTPEnvClient expected formatreturn {"observation": obs_dict,"reward": reward,"done": done,}def create_app(env: Environment,action_cls: Type[Action],observation_cls: Type[Observation],env_name: Optional[str] = None,) -> Any:"""Create a FastAPI application with or without web interface.This function creates a FastAPI app with the web interface enabled by default,including README integration for better user experience.Args:env: The Environment instance to serveaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsenv_name: Optional environment name for README loadingReturns:FastAPI application instance with or without web interface and README integration"""# Check if web interface should be enabled# This can be controlled via environment variable or build argumentenable_web = (os.getenv("ENABLE_WEB_INTERFACE", "false").lower() in ("true", "1", "yes"))if enable_web:# Import web interface only when neededfrom .web_interface import create_web_interface_appreturn create_web_interface_app(env, action_cls, observation_cls, env_name)else:# Use standard FastAPI app without web interfacereturn create_fastapi_app(env, action_cls, observation_cls)def create_fastapi_app(env: Environment,action_cls: Type[Action],observation_cls: Type[Observation],) -> Any:"""Create a FastAPI application with routes for the given environment.Args:env: The Environment instance to serveaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsReturns:FastAPI application instance with routes registeredExample:>>> from envs.coding_env.server import CodeExecutionEnvironment>>> from envs.coding_env.models import CodeAction, CodeObservation>>>>>> env = CodeExecutionEnvironment()>>> app = create_fastapi_app(env, CodeAction, CodeObservation)>>>>>> # Run with: uvicorn module:app --host 0.0.0.0 --port 8000"""try:from fastapi import FastAPI2 unmodified lines"FastAPI is required. Install with: pip install fastapi uvicorn")app = FastAPI(title="Environment HTTP Server")server = HTTPEnvServer(env, action_cls, observation_cls)server.register_routes(app)return app7 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191202 unmodified lines1231241251261271281291301311321331341351361373 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613172 unmodified lines1320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013917 unmodified linesHTTP server wrapper for Environment instances.This module provides utilities to wrap any Environment subclass and expose itover HTTP and WebSocket endpoints that EnvClient can consume."""from __future__ import annotationsimport asyncioimport inspectimport jsonimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Callable, Dict, Optional, Typefrom fastapi import (Body,FastAPI,HTTPException,Request,status,WebSocket,WebSocketDisconnect,)from pydantic import ValidationErrorfrom .interfaces import Environmentfrom .mcp_environment import get_server_toolsfrom .mcp_types import (JsonRpcErrorCode,JsonRpcRequest,JsonRpcResponse,McpMethod,WSMCPMessage,WSMCPResponse,)from .route_config import GetEndpointConfig, register_get_endpointsfrom .serialization import deserialize_action, serialize_observationfrom .types import (Action,ConcurrencyConfig,EnvironmentMetadata,HealthResponse,HealthStatus,Observation,ResetRequest,ResetResponse,SchemaResponse,ServerCapacityStatus,ServerMode,SessionInfo,State,StepRequest,StepResponse,WSCloseMessage,WSErrorCode,WSErrorResponse,WSObservationResponse,WSResetMessage,WSStateMessage,WSStateResponse,WSStepMessage,)def _make_json_serializable(obj: Any) -> Any:"""Convert an object to a JSON-serializable form.Handles Pydantic models, dataclasses, and other common types.Args:obj: The object to convertReturns:A JSON-serializable representation of the object"""if obj is None:return Noneif isinstance(obj, (str, int, float, bool)):return objif isinstance(obj, (list, tuple)):return [_make_json_serializable(item) for item in obj]if isinstance(obj, dict):return {k: _make_json_serializable(v) for k, v in obj.items()}if hasattr(obj, "model_dump"):# Pydantic modelreturn obj.model_dump()if hasattr(obj, "__dict__"):# Object with __dict__return {k: _make_json_serializable(v) for k, v in obj.__dict__.items()}# Fallback to string representationreturn str(obj)from .exceptions import (ConcurrencyConfigurationError,EnvironmentFactoryError,SessionCapacityError,)class HTTPEnvServer:"""HTTP server wrapper for Environment instances.This class wraps an Environment and exposes its reset(), step(), and statemethods as HTTP and WebSocket endpoints compatible with EnvClient.The server expects:- Action deserialization: Converts JSON dict to Action subclass2 unmodified linesExample:>>> from core.env_server import HTTPEnvServer>>> from envs.coding_env.server import CodeExecutionEnvironment>>> from envs.coding_env.models import CodeAction, CodeObservation>>>>>> # Pass environment class (factory pattern)>>> server = HTTPEnvServer(... env=CodeExecutionEnvironment,... action_cls=CodeAction,... observation_cls=CodeObservation,... max_concurrent_envs=4,... )>>>>>> # Register routes with FastAPI>>> from fastapi import FastAPI3 unmodified linesdef __init__(self,env: Callable[[], Environment],action_cls: Type[Action],observation_cls: Type[Observation],max_concurrent_envs: Optional[int] = None,concurrency_config: Optional[ConcurrencyConfig] = None,):"""Initialize HTTP server wrapper.Args:env: Environment factory (callable) that creates new instances.Will be called to create a new environment for each WebSocket session.action_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsmax_concurrent_envs: Maximum number of concurrent WebSocket sessions.Mutually exclusive with concurrency_config.concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings.Mutually exclusive with max_concurrent_envs.Raises:ValueError: If both max_concurrent_envs and concurrency_config are provided.ConcurrencyConfigurationError: If max_concurrent_envs > 1 for anenvironment that is not marked as SUPPORTS_CONCURRENT_SESSIONS."""# Validate that env is callableif not callable(env):raise TypeError(f"env must be a callable (class or factory function), got {type(env)}. "f"Pass the environment class (e.g., MyEnvironment) not an instance (e.g., MyEnvironment()).")self._env_factory: Callable[[], Environment] = env# Handle concurrency configurationif max_concurrent_envs is not None and concurrency_config is not None:raise ValueError("Cannot specify both 'max_concurrent_envs' and 'concurrency_config'. ""Please use only one method to configure concurrency.")if concurrency_config is not None:self._concurrency_config = concurrency_configelif max_concurrent_envs is not None:self._concurrency_config = ConcurrencyConfig(max_concurrent_envs=max_concurrent_envs,session_timeout=None,)else:# Default configurationself._concurrency_config = ConcurrencyConfig(max_concurrent_envs=1,session_timeout=None,)self._max_concurrent_envs = self._concurrency_config.max_concurrent_envs# Validate concurrency configurationself._validate_concurrency_safety()self.action_cls = action_clsself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Environment] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()# Create thread pool for running sync code in async context# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)def _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.Raises:ConcurrencyConfigurationError: If max_concurrent_envs > 1 for anenvironment that is not marked as SUPPORTS_CONCURRENT_SESSIONS."""if self._max_concurrent_envs <= 1:returnif inspect.isclass(self._env_factory):env_cls = self._env_factoryelse:_temp_env = self._env_factory()env_cls = type(_temp_env)_temp_env.close()del _temp_envif not getattr(env_cls, "SUPPORTS_CONCURRENT_SESSIONS", False):raise ConcurrencyConfigurationError(environment_name=env_cls.__name__,max_concurrent_envs=self._max_concurrent_envs,)def get_capacity_status(self) -> ServerCapacityStatus:"""Get the current capacity status of the server.Returns:ServerCapacityStatus with current session counts and availability."""return ServerCapacityStatus.from_counts(active=len(self._sessions),max_sessions=self._max_concurrent_envs,)async def _run_sync_in_thread_pool(self, func: Callable[..., Observation], *args, **kwargs) -> Observation:"""Run a synchronous function in the thread pool executor."""loop = asyncio.get_event_loop()return await loop.run_in_executor(self._executor, lambda: func(*args, **kwargs))def _get_valid_kwargs(self,sig: inspect.Signature,kwargs: Dict[str, Any],skip_params: Optional[set[str]] = None,) -> Dict[str, Any]:"""Filter kwargs to only include parameters accepted by the function signature."""if skip_params is None:skip_params = set()valid_kwargs = {}has_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values())for k, v in kwargs.items():if k in sig.parameters or has_kwargs:if k not in skip_params:valid_kwargs[k] = vreturn valid_kwargsasync def _create_session(self) -> tuple[str, Environment]:"""Create a new WebSocket session with its own environment instance.Returns:Tuple of (session_id, environment)Raises:SessionCapacityError: If max concurrent sessions reachedEnvironmentFactoryError: If the factory fails to create an environment"""async with self._session_lock:if len(self._sessions) >= self._max_concurrent_envs:raise SessionCapacityError(active_sessions=len(self._sessions),max_sessions=self._max_concurrent_envs,)session_id = str(uuid.uuid4())current_time = time.time()# Create executor and reserve slot so capacity is not exceeded while# we create the env outside the lock (avoids blocking other sessions)executor = ThreadPoolExecutor(max_workers=1)self._session_executors[session_id] = executorself._sessions[session_id] = None # placeholder until env is readytry:# Create environment in the executor thread (outside lock)loop = asyncio.get_event_loop()env = await loop.run_in_executor(executor, self._env_factory)except Exception as e:async with self._session_lock:executor.shutdown(wait=False)self._session_executors.pop(session_id, None)self._sessions.pop(session_id, None)factory_name = getattr(self._env_factory, "__name__", str(self._env_factory))raise EnvironmentFactoryError(factory_name) from easync with self._session_lock:self._sessions[session_id] = envself._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=current_time,step_count=0,environment_type=type(env).__name__,)return session_id, envasync def _destroy_session(self, session_id: str) -> None:"""Destroy a WebSocket session and cleanup resources.Args:session_id: The session ID to destroy"""async with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:if executor is not None:try:loop = asyncio.get_event_loop()await loop.run_in_executor(executor, env.close)except Exception:# If executor close fails, try direct close as fallbacktry:env.close()except Exception:pass # Best effort cleanupelse:try:env.close()except Exception:pass # Best effort cleanup# Shutdown executor after close is doneif executor is not None:executor.shutdown(wait=False)def _update_session_activity(self, session_id: str, increment_step: bool = False) -> None:"""Update session activity timestamp and optionally increment step count.Args:session_id: The session ID to updateincrement_step: If True, increment the step count"""if session_id in self._session_info:self._session_info[session_id].last_activity_at = time.time()if increment_step:self._session_info[session_id].step_count += 1def get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.Args:session_id: The session ID to queryReturns:SessionInfo if the session exists, None otherwise"""return self._session_info.get(session_id)async def _run_in_session_executor(self, session_id: str, func: Callable[..., Observation], *args, **kwargs) -> Observation:"""Run a synchronous function in the session's thread pool executor."""executor = self._session_executors.get(session_id, self._executor)loop = asyncio.get_event_loop()return await loop.run_in_executor(executor, lambda: func(*args, **kwargs))@propertydef active_sessions(self) -> int:"""Return the number of active WebSocket sessions."""return len(self._sessions)@propertydef max_concurrent_envs(self) -> int:"""Return the maximum number of concurrent environments."""return self._max_concurrent_envs@propertydef is_concurrency_safe(self) -> bool:"""Return whether the environment is marked as concurrency safe."""import inspectif inspect.isclass(self._env_factory):return getattr(self._env_factory, "SUPPORTS_CONCURRENT_SESSIONS", False)else:_temp_env = self._env_factory()result = getattr(_temp_env, "SUPPORTS_CONCURRENT_SESSIONS", False)_temp_env.close()del _temp_envreturn result@propertydef concurrency_config(self) -> ConcurrencyConfig:"""Return the concurrency configuration."""return self._concurrency_configdef register_routes(self, app: FastAPI, mode: ServerMode | str = ServerMode.SIMULATION) -> None:"""Register HTTP routes on a FastAPI application.Args:app: FastAPI application instancemode: Server mode - either SIMULATION or PRODUCTION (or string equivalents).In production mode, simulation control endpoints (/reset, /step, /state)are NOT registered. Only safe endpoints (/health, /schema, /metadata, /ws)are available. Defaults to SIMULATION for backwards compatibility.Raises:ValueError: If mode is not a valid ServerMode or string equivalent."""# Convert string to ServerMode enum for backwards compatibilityif isinstance(mode, str):try:mode = ServerMode(mode.lower())except ValueError:valid_modes = [m.value for m in ServerMode]raise ValueError(f"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),) -> ResetResponse:"""Reset endpoint - returns initial observation."""_env = self._env_factory()try:kwargs = request.model_dump(exclude_unset=True)is_async = _env.reset_async.__func__ is not Environment.reset_asyncif is_async:sig = inspect.signature(_env.reset_async)else:sig = inspect.signature(_env.reset)valid_kwargs = self._get_valid_kwargs(sig, kwargs)if is_async:observation = await _env.reset_async(**valid_kwargs)else:observation = await self._run_sync_in_thread_pool(_env.reset, **valid_kwargs)return ResetResponse(**serialize_observation(observation))finally:_env.close()# Helper function to handle step endpointasync def step_handler(request: StepRequest) -> StepResponse:"""Step endpoint - executes action and returns observation."""action_data = request.actiontry:action = deserialize_action(action_data, self.action_cls)except ValidationError as e:raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=e.errors())_env = self._env_factory()try:kwargs = request.model_dump(exclude_unset=True, exclude={"action"})is_async = _env.step_async.__func__ is not Environment.step_asyncif is_async:sig = inspect.signature(_env.step_async)else:sig = inspect.signature(_env.step)valid_kwargs = self._get_valid_kwargs(sig, kwargs, skip_params={"action"})if is_async:observation = await _env.step_async(action, **valid_kwargs)else:observation = await self._run_sync_in_thread_pool(_env.step, action, **valid_kwargs)return StepResponse(**serialize_observation(observation))finally:_env.close()# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest, session_env: Optional[Environment] = None) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format."""method = request.methodrequest_id = request.id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelse:_env = self._env_factory()should_close = Truetry:if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump() if hasattr(t, "model_dump") else dict(t)for t in tools]},request_id=request_id,)elif method == McpMethod.TOOLS_CALL:params = request.paramstool_name = params.get("name")arguments = params.get("arguments", {})if not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)if not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Missing 'name' in params",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)# Ensure result is JSON serializableserializable_result = _make_json_serializable(result)return JsonRpcResponse.success(result=serializable_result,request_id=request_id,)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,f"Method not found: {method}",request_id=request_id,)except Exception as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=request_id,)finally:if should_close:_env.close()# Register MCP WebSocket endpoint (available in both production and simulation modes)@app.websocket("/mcp")async def mcp_websocket_endpoint(websocket: WebSocket):"""WebSocket endpoint for MCP JSON-RPC requests.Each WebSocket connection gets its own environment instance for MCP operations.Message Protocol:- Client sends: JSON-RPC 2.0 request (tools/list, tools/call)- Server responds: JSON-RPC 2.0 response (result or error)"""await websocket.accept()session_id = Nonesession_env = Nonetry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request, session_env=session_env)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:passexcept SessionCapacityError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),data={"active_sessions": e.active_sessions,"max_sessions": e.max_sessions,},)await websocket.send_text(error_resp.model_dump_json())except EnvironmentFactoryError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),data={"factory_name": e.factory_name},)await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),)await websocket.send_text(error_resp.model_dump_json())finally:if session_id:await self._destroy_session(session_id)try:await websocket.close()except RuntimeError:pass# Register simulation control routes only in simulation modeif mode == ServerMode.SIMULATION:@app.post("/reset",response_model=ResetResponse,tags=["Environment Control"],summary="Reset the environment",description="""Reset the environment to its initial state and return the first observation.You can optionally provide a seed for reproducibility and an episode_id for tracking.""",responses={200: {"description": "Environment reset successfully","content": {"application/json": {"example": {"observation": {"status": "ready", "data": {}},"reward": None,"done": False,}}},}},)async def reset(request: ResetRequest = Body(default_factory=ResetRequest),) -> ResetResponse:return await reset_handler(request)@app.post("/step",response_model=StepResponse,tags=["Environment Control"],summary="Execute an action in the environment",description="""Execute an action in the environment and receive the resulting observation.The action must conform to the environment's action schema, which can beretrieved from the `/schema` endpoint. If the action is invalid,the endpoint will return HTTP 422 with detailed validation errors.The response includes:- **observation**: The environment's response to the action- **reward**: Optional reward signal (float or None)- **done**: Boolean indicating if the episode has terminated""",responses={200: {"description": "Action executed successfully","content": {"application/json": {"example": {"observation": {"status": "success", "data": {}},"reward": 1.0,"done": False,}}},},422: {"description": "Validation error - invalid action format or values","content": {"application/json": {"example": {"detail": [{"type": "string_too_short","loc": ["body", "action", "message"],"msg": "String should have at least 1 character","input": "",}]}}},},500: {"description": "Internal server error during action execution"},},)async def step(request: StepRequest) -> StepResponse:return await step_handler(request)def get_state_handler() -> State:_env = self._env_factory()try:return _env.statefinally:_env.close()def get_metadata_handler() -> EnvironmentMetadata:_env = self._env_factory()try:return _env.get_metadata()finally:_env.close()# Build list of GET endpoints based on modeget_endpoints = [GetEndpointConfig(path="/metadata",handler=get_metadata_handler,response_model=EnvironmentMetadata,tag="Environment Info",summary="Get environment metadata",description="""Get metadata about this environment.Returns information about the environment including name, description,version, author, and documentation links.""",),GetEndpointConfig(path="/health",handler=lambda: HealthResponse(status=HealthStatus.HEALTHY),response_model=HealthResponse,tag="Health",summary="Health check",description="Check if the environment server is running and healthy.",),]# Only register /state endpoint in simulation modeif mode == ServerMode.SIMULATION:get_endpoints.insert(0,GetEndpointConfig(path="/state",handler=get_state_handler,response_model=State,tag="State Management",summary="Get current environment state",description="""Retrieve the current internal state of the environment.The structure of the state object is defined by the environment's State model.""",),)register_get_endpoints(app, get_endpoints)# Register combined schema endpoint@app.get("/schema",response_model=SchemaResponse,tags=["Schema"],summary="Get all JSON schemas",description="""Get JSON schemas for actions, observations, and state in a single response.Returns a combined schema object containing:- **action**: JSON schema for actions accepted by this environment- **observation**: JSON schema for observations returned by this environment- **state**: JSON schema for environment state objectsThis is more efficient than calling individual schema endpoints and providesall schema information needed to interact with the environment.""",responses={200: {"description": "Combined schemas retrieved successfully","content": {"application/json": {"example": {"action": {"type": "object","properties": {"message": {"type": "string"}},},"observation": {"type": "object","properties": {"response": {"type": "string"}},},"state": {"type": "object","properties": {"step_count": {"type": "integer"}},},}}},}},)async def get_schemas() -> SchemaResponse:"""Return all schemas in one response."""return SchemaResponse(action=self.action_cls.model_json_schema(),observation=self.observation_cls.model_json_schema(),state=State.model_json_schema(),)# Register MCP endpoint for production mode (direct MCP access)@app.post("/mcp")async def mcp_endpoint(request_raw: Request) -> Dict[str, Any]:"""MCP JSON-RPC endpoint for production mode.Bypasses step() overhead and provides direct access to MCP tools.Supports tools/list and tools/call methods."""# Parse JSON manually to handle parse errors gracefullytry:body = await request_raw.body()request_dict = json.loads(body)request = JsonRpcRequest(**request_dict)except json.JSONDecodeError:return JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR).model_dump()except ValidationError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",).model_dump()except Exception:return JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR).model_dump()method = request.methodparams = request.paramsrequest_id = request.id# Create a temporary environment for MCP access_env = self._env_factory()try:# Check if environment supports MCPif not hasattr(_env, "mcp_client") and not hasattr(_env, "mcp_server"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,).model_dump()if method == McpMethod.TOOLS_LIST:# List tools from MCP serverif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,).model_dump()elif hasattr(_env, "mcp_server") and _env.mcp_server:# Use server directlytools = []for tool_name, tool in get_server_tools(_env.mcp_server).items():tool_dict = {"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},}tools.append(tool_dict)return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'name' is required",request_id=request_id,).model_dump()# Call tool via MCPif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)elif hasattr(_env, "mcp_server") and _env.mcp_server:# Call tool directly on FastMCP serverserver_tools = get_server_tools(_env.mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()# Make result JSON serializableserializable_result = _make_json_serializable(result)return JsonRpcResponse.success(result=serializable_result,request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,f"Method not found: {method}",request_id=request_id,).model_dump()except Exception as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=request_id,).model_dump()finally:_env.close()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket):"""WebSocket endpoint for persistent environment sessions.Each WebSocket connection gets its own environment instance.Message Protocol:- Client sends: WSResetMessage | WSStepMessage | WSStateMessage | WSCloseMessage- Server responds: WSObservationResponse | WSStateResponse | WSErrorResponse"""await websocket.accept()session_id = Nonesession_env = Nonetry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await self._run_in_session_executor(session_id, session_env.reset, **valid_kwargs)self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = await self._run_in_session_executor(session_id, session_env.step, action)self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:passexcept SessionCapacityError as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.CAPACITY_REACHED,"active_sessions": e.active_sessions,"max_sessions": e.max_sessions,})await websocket.send_text(error_resp.model_dump_json())except EnvironmentFactoryError as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.FACTORY_ERROR,"factory_name": e.factory_name,})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e), "code": WSErrorCode.SESSION_ERROR})await websocket.send_text(error_resp.model_dump_json())finally:if session_id:await self._destroy_session(session_id)try:await websocket.close()except RuntimeError:passdef create_app(env: Callable[[], Environment],action_cls: Type[Action],observation_cls: Type[Observation],env_name: Optional[str] = None,max_concurrent_envs: Optional[int] = None,concurrency_config: Optional[ConcurrencyConfig] = None,gradio_builder: Optional[Callable[..., Any]] = None,) -> FastAPI:"""Create a FastAPI application with or without web interface.This function creates a FastAPI app with the web interface enabled by default,including README integration for better user experience.Args:env: Environment factory (callable) that creates new instancesaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsenv_name: Optional environment name for README loadingmax_concurrent_envs: Maximum concurrent WebSocket sessions.Mutually exclusive with concurrency_config.concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings.Mutually exclusive with max_concurrent_envs.gradio_builder: Optional callable to build a custom Gradio UI at /web.Signature: (web_manager, action_fields, metadata, is_chat_env, title,quick_start_md) -> gr.Blocks. When None, the default Gradio app is used.See docs/customizing-web-ui.md.Returns:FastAPI application instance with or without web interface and README integration"""# Check if web interface should be enabled# This can be controlled via environment variable or build argumentenable_web = os.getenv("ENABLE_WEB_INTERFACE", "false").lower() in ("true","1","yes",)if enable_web:# Gradio-based web UI (gradio is a core dependency)from .web_interface import create_web_interface_appreturn create_web_interface_app(env,action_cls,observation_cls,env_name,max_concurrent_envs,concurrency_config,gradio_builder=gradio_builder,)else:# Use standard FastAPI app without web interfacereturn create_fastapi_app(env, action_cls, observation_cls, max_concurrent_envs, concurrency_config)def create_fastapi_app(env: Callable[[], Environment],action_cls: Type[Action],observation_cls: Type[Observation],max_concurrent_envs: Optional[int] = None,concurrency_config: Optional[ConcurrencyConfig] = None,) -> FastAPI:"""Create a FastAPI application with comprehensive documentation.Args:env: Environment factory (callable) that creates new instancesaction_cls: The Action subclass this environment expectsobservation_cls: The Observation subclass this environment returnsmax_concurrent_envs: Maximum concurrent WebSocket sessions.Mutually exclusive with concurrency_config.concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings.Mutually exclusive with max_concurrent_envs.Returns:FastAPI application instance"""try:from fastapi import FastAPI2 unmodified lines"FastAPI is required. Install with: pip install fastapi uvicorn")app = FastAPI(title="OpenEnv Environment HTTP API",version="1.0.0",description="""# OpenEnv Environment HTTP APIHTTP API for interacting with OpenEnv environments through a standardized interface.## Features* **Environment Reset**: Initialize or restart episodes* **Action Execution**: Send actions and receive observations* **State Inspection**: Query current environment state* **Schema Access**: Retrieve JSON schemas for actions and observations## Workflow1. Call `/reset` to start a new episode and get initial observation2. Call `/step` repeatedly with actions to interact with environment3. Episode ends when observation returns `done: true`4. Call `/state` anytime to inspect current environment state## Documentation* **Swagger UI**: Available at `/docs`* **ReDoc**: Available at `/redoc`* **OpenAPI Schema**: Available at `/openapi.json`""",openapi_tags=[{"name": "Environment Control","description": "Core operations for environment interaction (reset, step)",},{"name": "State Management","description": "Operations for inspecting environment state",},{"name": "Environment Info","description": "Information about the environment",},{"name": "Schema","description": "JSON Schema endpoints for actions, observations, and state",},{"name": "Health", "description": "Service health and status checks"},],docs_url="/docs",redoc_url="/redoc",openapi_url="/openapi.json",contact={"name": "OpenEnv Team","url": "https://github.com/meta-pytorch/OpenEnv",},license_info={"name": "BSD-3-Clause","url": "https://github.com/meta-pytorch/OpenEnv/blob/main/LICENSE",},)server = HTTPEnvServer(env,action_cls,observation_cls,max_concurrent_envs,concurrency_config=concurrency_config,)server.register_routes(app)return app
3 unmodified lines4567891011121350 unmodified lines646566676869702 unmodified lines737475767778795 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171183 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.from abc import ABC, abstractmethodfrom typing import Any, Protocol, TypedDictfrom .types import Action, Observation, Stateclass Message(TypedDict):50 unmodified lines...class Transform(ABC):"""Transform observations to add rewards, metrics, or other modifications.Transforms follow the TorchRL pattern where they take an observation2 unmodified lines"""@abstractmethoddef __call__(self, observation: Observation) -> Observation:"""Transform an observation.Args:5 unmodified linespassclass Environment(ABC):"""Base class for all environment servers following Gym/Gymnasium API.Args:transform: Optional transform to apply to observations"""def __init__(self, transform: Transform | None = None):self.transform = transform@abstractmethoddef reset(self) -> Observation:"""Reset the environment and return initial observation."""pass@abstractmethoddef step(self, action: Action) -> Observation:"""Take a step in the environment."""pass@property@abstractmethoddef state(self) -> State:"""Get the current environment state."""passdef _apply_transform(self, observation: Observation) -> Observation:"""Apply transform if one is provided."""if self.transform is not None:return self.transform(observation)return observation3 unmodified lines456789101112131415161718192021222350 unmodified lines747576777879802 unmodified lines838485868788895 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962973 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.import inspectfrom abc import ABC, abstractmethodfrom typing import Any, Generic, Optional, Protocol, TYPE_CHECKING, TypeVarfrom typing_extensions import TypedDictfrom .types import Action, EnvironmentMetadata, Observation, Stateif TYPE_CHECKING:from openenv.core.rubrics import RubricActT = TypeVar("ActT", bound=Action)ObsT = TypeVar("ObsT", bound=Observation)StateT = TypeVar("StateT", bound=State)class Message(TypedDict):50 unmodified lines...class Transform(ABC, Generic[ObsT]):"""Transform observations to add rewards, metrics, or other modifications.Transforms follow the TorchRL pattern where they take an observation2 unmodified lines"""@abstractmethoddef __call__(self, observation: ObsT) -> ObsT:"""Transform an observation.Args:5 unmodified linespassclass Environment(ABC, Generic[ActT, ObsT, StateT]):"""Base class for all environment servers following Gym/Gymnasium API.Args:transform: Optional transform to apply to observationsrubric: Optional rubric for reward computation. When provided, therubric's output can be used to set the observation's reward in step().Class Attributes:SUPPORTS_CONCURRENT_SESSIONS: Whether this environment supports concurrent sessions.When True, multiple WebSocket connections can each have their ownenvironment instance (up to max_concurrent_envs). When False (default),the environment should only be used with a single session at a time.Set this to True in your Environment subclass if:- The environment uses proper session isolation (e.g., unique working dirs)- No shared mutable state exists between instances- External resources (databases, APIs) can handle concurrent accessAttributes:rubric: Optional rubric for computing rewards. Environments can set thisin __init__ and use it in step() to compute observation rewards.Training infrastructure can access it for introspection:for name, r in env.rubric.named_rubrics():print(f"{name}: {r.last_score}")See RFC 004 for rubric design: rfcs/004-rubrics.md"""# Class-level flag indicating whether this environment supports concurrent sessionsSUPPORTS_CONCURRENT_SESSIONS: bool = False# Optional rubric for reward computationrubric: Optional["Rubric"]def __init__(self,transform: Optional[Transform[ObsT]] = None,rubric: Optional["Rubric"] = None,):self.transform = transformself.rubric = rubric@abstractmethoddef reset(self,seed: Optional[int] = None,episode_id: Optional[str] = None,**kwargs: Any,) -> ObsT:"""Reset the environment and return initial observation."""passasync def reset_async(self,seed: Optional[int] = None,episode_id: Optional[str] = None,**kwargs: Any,) -> ObsT:"""Async version of reset. Default implementation calls sync reset.Override to provide true async implementation."""return self.reset(seed=seed, episode_id=episode_id, **kwargs)@abstractmethoddef step(self,action: ActT,timeout_s: Optional[float] = None,**kwargs: Any,) -> ObsT:"""Take a step in the environment."""passasync def step_async(self,action: ActT,timeout_s: Optional[float] = None,**kwargs: Any,) -> ObsT:"""Async version of step. Default implementation calls sync step.Override to provide true async implementation."""return self.step(action, timeout_s=timeout_s, **kwargs)@property@abstractmethoddef state(self) -> StateT:"""Get the current environment state."""passdef get_metadata(self) -> EnvironmentMetadata:"""Get metadata about this environment.Override this method to provide custom metadata for the environment.Default implementation returns basic metadata derived from class name.Returns:EnvironmentMetadata with environment information"""return EnvironmentMetadata(name=self.__class__.__name__,description=f"{self.__class__.__name__} environment",version="1.0.0",)def _apply_transform(self, observation: ObsT) -> ObsT:"""Apply transform if one is provided."""if self.transform is not None:return self.transform(observation)return observationdef _apply_rubric(self, action: ActT, observation: ObsT) -> float:"""Apply rubric if one is provided.Args:action: The action taken by the agent.observation: The resulting observation.Returns:Reward value from the rubric, or 0.0 if no rubric is set.Usage in step():def step(self, action: MyAction, ...) -> MyObservation:# ... execute action and create observation ...observation.reward = self._apply_rubric(action, observation)return observation"""if self.rubric is not None:return self.rubric(action, observation)return 0.0async def _apply_rubric_async(self, action: ActT, observation: ObsT) -> float:"""Apply rubric asynchronously if one is provided.Args:action: The action taken by the agent.observation: The resulting observation.Returns:Reward value from the rubric, or 0.0 if no rubric is set.Usage in step_async():async def step_async(self, action: MyAction, ...) -> MyObservation:# ... execute action and create observation ...observation.reward = await self._apply_rubric_async(action, observation)return observation"""if self.rubric is not None:result = self.rubric(action, observation)# If rubric returns a coroutine, await itif inspect.iscoroutine(result):return await resultreturn resultreturn 0.0def _reset_rubric(self) -> None:"""Reset the rubric state if one is provided.Call this in reset() to clear any trajectory state in the rubric.Usage in reset():def reset(self, ...) -> MyObservation:self._reset_rubric()# ... create initial observation ...return observation"""if self.rubric is not None:self.rubric.reset()async def _reset_rubric_async(self) -> None:"""Reset the rubric state asynchronously if one is provided.Call this in reset_async() to clear any trajectory state in the rubric.Usage in reset_async():async def reset_async(self, ...) -> MyObservation:await self._reset_rubric_async()# ... create initial observation ...return observation"""if self.rubric is not None:# Check if rubric has async reset methodif hasattr(self.rubric, "reset_async"):result = self.rubric.reset_async()if inspect.iscoroutine(result):await resultelse:self.rubric.reset()def close(self) -> None:"""Clean up resources used by the environment.Override this method to implement custom cleanup logic.Called when the environment is being destroyed or reset."""pass
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""MCP Environment base class for OpenEnv.
This module provides the MCPEnvironment base class that integrates FastMCP serverswith OpenEnv's Gym-style Environment interface. It handles MCP tool discoveryand invocation through the step() API, following RFC 003.
Key features:- Automatic routing of ListToolsAction and CallToolAction to MCP server- Reserved tool name validation (reset, step, state, close are protected)- Timeout handling for tool calls- Proper error categorization (tool not found, execution errors, timeouts)- Mode-aware tool registration (production vs simulation)- Code mode support via get_callables() and execute_code()
Usage: from fastmcp import FastMCP from openenv.core.env_server.mcp_environment import MCPEnvironment
class MyMCPEnv(MCPEnvironment): def __init__(self): mcp = FastMCP("my-server")
# Register mode-specific tools @self.tool(mode="production") def my_tool(arg: str) -> str: return f"Production: {arg}"
@self.tool(mode="simulation") def my_tool(arg: str) -> str: return f"Simulation: {arg}"
super().__init__(mcp)
def reset(self, seed=None, episode_id=None, **kwargs): # Reset logic here ...
def _step_impl(self, action): # Handle non-MCP actions ...
@property def state(self): # Return current state ..."""
import asyncioimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom typing import Any, Callable, Dict, Optional
from fastmcp import Clientfrom fastmcp.client.client import CallToolResultfrom mcp.types import TextContent
from ..utils import run_async_safelyfrom .interfaces import Environmentfrom .mcp_types import ( CallToolAction, CallToolObservation, ListToolsAction, ListToolsObservation, RESERVED_TOOL_NAMES, Tool, ToolError, ToolErrorType,)from .types import Action, Observation
# Default timeout for MCP tool calls in secondsMCP_TOOL_CALL_TIMEOUT = 30.0
# Valid modes for tool registrationVALID_MODES = {"production", "simulation"}
def get_server_tools(mcp_server: Any) -> Dict[str, Any]: """ Get tools from a FastMCP server, compatible with both 2.x and 3.x.
Returns: Dictionary mapping tool names to tool objects. """ # FastMCP 2.x: get_tools() returns dict {name: Tool} if hasattr(mcp_server, "get_tools"): result = run_async_safely(mcp_server.get_tools()) if isinstance(result, dict): return result # FastMCP 3.x: list_tools() returns list of Tool objects if hasattr(mcp_server, "list_tools"): tools_list = run_async_safely(mcp_server.list_tools()) return {t.name: t for t in tools_list} return {}
class MCPEnvironment(Environment): """ Base class for environments that expose tools via MCP (Model Context Protocol).
MCPEnvironment bridges FastMCP servers with OpenEnv's Gym-style API, allowing agents to discover and invoke MCP tools through the standard step() interface.
The class automatically handles: - ListToolsAction: Returns available tools from the MCP server - CallToolAction: Invokes a specific tool with arguments
All other actions are delegated to the abstract _step_impl() method, which subclasses must implement.
Args: mcp_server: A FastMCP server instance containing tool definitions. The server's tools will be validated against reserved names. transform: Optional transform to apply to observations (inherited from Environment).
Raises: ValueError: If any tool in the MCP server uses a reserved name (reset, step, state, close).
Example: >>> from fastmcp import FastMCP >>> mcp = FastMCP("calculator") >>> @mcp.tool() ... def add(a: int, b: int) -> int: ... return a + b >>> env = MyMCPEnvironment(mcp) >>> obs = env.step(ListToolsAction()) >>> obs.tools[0].name 'add' """
def __init__(self, mcp_server: Any, transform: Optional[Any] = None) -> None: """ Initialize the MCP environment.
Args: mcp_server: A FastMCP server instance with tool definitions. transform: Optional transform to apply to observations.
Raises: ValueError: If any tool uses a reserved name (reset, step, state, close). """ super().__init__(transform=transform)
# Validate tool names before storing self._validate_tool_names(mcp_server)
self.mcp_server = mcp_server self.mcp_client = Client(mcp_server)
# Track mode-specific tools: {tool_name: {mode: func}} # mode can be "production", "simulation", or None (available in all modes) self._mode_tools = defaultdict(dict)
# Track tool schemas for list_tools: {tool_name: {mode: schema}} self._mode_tool_schemas = defaultdict(dict)
@property def supports_code_mode(self) -> bool: """Check if this environment supports code mode (execute_code).""" return True
def _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]: """ Get tools from a FastMCP server, compatible with both 2.x and 3.x.
Returns: Dictionary mapping tool names to tool objects. """ return get_server_tools(mcp_server)
def get_callables(self) -> Dict[str, Callable]: """ Get callable functions for code mode.
Returns tool functions as direct Python callables, enabling code mode where agents write Python code that calls tools directly (no JSON-RPC overhead). Mode-specific tools are filtered by the current mode.
Returns: Dictionary mapping tool names to callables. """ callables: Dict[str, Callable] = {} current_mode = getattr(self, "_mode", None)
# Extract callables from FastMCP server using public API for tool_name, tool in self._get_server_tools(self.mcp_server).items(): if hasattr(tool, "fn") and callable(tool.fn): callables[tool_name] = tool.fn
# Add mode-specific tools available in current mode for tool_name, mode_funcs in self._mode_tools.items(): if None in mode_funcs: # Tool available in all modes (already in FastMCP if registered there) if tool_name not in callables: callables[tool_name] = mode_funcs[None] elif current_mode in mode_funcs: # Tool available in current mode only callables[tool_name] = mode_funcs[current_mode]
return callables
def execute_code(self, code: str) -> Observation: """ Execute Python code with tools available as callables.
This enables the CodeAct pattern where agents write Python code that calls tools directly as functions, avoiding JSON-RPC overhead.
Args: code: Python code to execute. Tools are available as functions in the execution namespace. Set a variable named 'result' to capture the return value.
Returns: Observation with result in metadata["result"] or error in metadata["error"]. """ namespace = self.get_callables()
result_dict: Dict[str, Any] = {} try: exec(code, namespace, result_dict) result = result_dict.get("result") return Observation(done=False, reward=0.0, metadata={"result": result}) except SyntaxError as e: return Observation( done=False, reward=0.0, metadata={"error": f"Syntax error: {str(e)}"} ) except Exception as e: return Observation(done=False, reward=0.0, metadata={"error": str(e)})
def _validate_tool_names(self, mcp_server: Any) -> None: """ Validate that no tools use reserved names.
Reserved names (reset, step, state, close) are protected to maintain the dual API boundary between infrastructure and agent APIs.
Args: mcp_server: The FastMCP server to validate.
Raises: ValueError: If any tool uses a reserved name. """ tools_dict = self._get_server_tools(mcp_server) if tools_dict: tool_names = set(tools_dict.keys()) conflicts = tool_names & RESERVED_TOOL_NAMES if conflicts: raise ValueError( f"MCP tools cannot use reserved names: {sorted(conflicts)}. " f"Reserved names are: {sorted(RESERVED_TOOL_NAMES)}" )
def tool(self, mode: Optional[str] = None) -> Callable: """ Decorator for registering mode-aware tools.
Args: mode: Optional mode for the tool ("production" or "simulation"). If None, tool is available in all modes.
Returns: A decorator function for registering tools.
Raises: ValueError: If mode is not None, "production", or "simulation". """ if mode is not None and mode not in VALID_MODES: raise ValueError( f"Invalid mode '{mode}'. Mode must be 'production', 'simulation', or None." )
def decorator(func: Callable) -> Callable: tool_name = func.__name__ # Validate tool name is not reserved if tool_name in RESERVED_TOOL_NAMES: raise ValueError( f"Tool name '{tool_name}' is reserved and cannot be used. " f"Reserved names are: {sorted(RESERVED_TOOL_NAMES)}" )
# If mode is None, register with FastMCP as usual if mode is None: decorated_func = self.mcp_server.tool()(func) self._mode_tools[tool_name][None] = func return decorated_func
# For mode-specific tools, don't register with FastMCP # Instead, track them ourselves self._mode_tools[tool_name][mode] = func
# Extract schema information from function signature sig = inspect.signature(func) schema = { "type": "object", "properties": {}, "required": [], }
for param_name, param in sig.parameters.items(): # Get type annotation param_type = param.annotation json_type = "string" # default if param_type in (int, "int"): json_type = "integer" elif param_type in (float, "float"): json_type = "number" elif param_type in (bool, "bool"): json_type = "boolean"
schema["properties"][param_name] = {"type": json_type}
# If no default value, it's required if param.default == inspect.Parameter.empty: schema["required"].append(param_name)
# Store the schema for this mode-specific tool self._mode_tool_schemas[tool_name][mode] = { "name": tool_name, "description": func.__doc__ or "", "input_schema": schema, }
return func
return decorator
def step( self, action: Action, timeout_s: Optional[float] = None, **kwargs: Any, ) -> Observation: """ Execute an action in the environment.
This method routes MCP-specific actions (ListToolsAction, CallToolAction) to the appropriate handlers, while delegating all other actions to the subclass's _step_impl() method.
Args: action: The action to execute. Can be: - ListToolsAction: Returns available MCP tools - CallToolAction: Invokes a specific MCP tool - Any other Action: Delegated to _step_impl() timeout_s: Optional timeout in seconds for the action. Defaults to MCP_TOOL_CALL_TIMEOUT (30s) for MCP actions. **kwargs: Additional arguments passed to handlers.
Returns: Observation appropriate to the action type: - ListToolsObservation for ListToolsAction - CallToolObservation for CallToolAction - Subclass-defined Observation for other actions """ if isinstance(action, ListToolsAction): return self._handle_list_tools() elif isinstance(action, CallToolAction): return self._handle_call_tool(action, timeout_s=timeout_s) else: return self._step_impl(action, timeout_s=timeout_s, **kwargs)
def _handle_list_tools(self) -> ListToolsObservation: """ Handle a ListToolsAction by querying the MCP server.
Returns: ListToolsObservation containing all available tools with their names, descriptions, and input schemas, filtered by current mode. """ try: # Get current mode current_mode = getattr(self, "_mode", None)
# Start with tools from FastMCP server (mode=None tools) tools_result = run_async_safely(self._async_list_tools())
# Build list of Tool objects tools = []
# Add FastMCP tools that are not mode-specific for tool in tools_result: if tool.name not in self._mode_tool_schemas: tools.append( Tool( name=tool.name, description=tool.description or "", input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {}, ) )
# Add mode-specific tools available in current mode for tool_name, mode_schemas in self._mode_tool_schemas.items(): if None in mode_schemas: # Tool available in all modes schema = mode_schemas[None] tools.append( Tool( name=schema["name"], description=schema["description"], input_schema=schema["input_schema"], ) ) elif current_mode in mode_schemas: # Tool available in current mode schema = mode_schemas[current_mode] tools.append( Tool( name=schema["name"], description=schema["description"], input_schema=schema["input_schema"], ) )
return ListToolsObservation(tools=tools)
except Exception as e: # Return an observation with error in metadata return ListToolsObservation( tools=[], metadata={ "error": str(e), "error_type": "list_tools_failed", }, )
async def _async_list_tools(self) -> list: """ Async helper to list tools from the MCP client.
Returns: List of tool objects from the MCP server. """ async with self.mcp_client: return await self.mcp_client.list_tools()
def _handle_call_tool( self, action: CallToolAction, timeout_s: Optional[float] = None, ) -> CallToolObservation: """ Handle a CallToolAction by invoking the specified tool.
Args: action: The CallToolAction containing tool_name and arguments. timeout_s: Timeout in seconds. Defaults to MCP_TOOL_CALL_TIMEOUT (30s).
Returns: CallToolObservation with the tool's result or an error. """ timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUT
# Check if this is a mode-specific tool tool_name = action.tool_name current_mode = getattr(self, "_mode", None)
if tool_name in self._mode_tools: mode_info = self._mode_tools[tool_name]
# Check if tool is available in current mode # Tool is available if: # 1. It has a None mode (available in all modes), OR # 2. It has an implementation for the current mode if None in mode_info: # Use the mode-agnostic version func = mode_info[None] elif current_mode in mode_info: # Use the mode-specific version func = mode_info[current_mode] else: # Tool not available in current mode return CallToolObservation( tool_name=tool_name, result=None, error=ToolError( error_type=ToolErrorType.TOOL_NOT_FOUND, message=f"Tool '{tool_name}' not available in {current_mode} mode", ), )
# Call the mode-specific function directly try: # Check if function is async and await if necessary if inspect.iscoroutinefunction(func): result = run_async_safely(func(**action.arguments)) else: result = func(**action.arguments)
# Wrap result in CallToolResult format to match FastMCP behavior return CallToolObservation( tool_name=tool_name, result=CallToolResult( content=[TextContent(type="text", text=str(result))], structured_content={"result": result}, meta=None, data=result, is_error=False, ), ) except Exception as e: return CallToolObservation( tool_name=tool_name, result=None, error=ToolError( error_type=ToolErrorType.EXECUTION_ERROR, message=str(e), ), )
# Not a mode-specific tool, use FastMCP try: # Run the async call_tool with timeout # Use run_async_safely to handle both sync and async contexts result = run_async_safely( asyncio.wait_for( self._async_call_tool(action.tool_name, action.arguments), timeout=timeout, ) )
return CallToolObservation( tool_name=action.tool_name, result=result, )
except asyncio.TimeoutError: return CallToolObservation( tool_name=action.tool_name, result=None, error=ToolError( error_type=ToolErrorType.TIMEOUT, message=f"Tool '{action.tool_name}' timed out after {timeout} seconds", ), )
except Exception as e: error_message = str(e)
# Determine error type based on the exception if ( "not found" in error_message.lower() or "unknown tool" in error_message.lower() ): error_type = ToolErrorType.TOOL_NOT_FOUND elif ( "invalid" in error_message.lower() or "argument" in error_message.lower() ): error_type = ToolErrorType.INVALID_ARGS else: error_type = ToolErrorType.EXECUTION_ERROR
return CallToolObservation( tool_name=action.tool_name, result=None, error=ToolError( error_type=error_type, message=error_message, ), )
async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any: """ Async helper to call a tool on the MCP server.
Args: tool_name: Name of the tool to invoke. arguments: Dictionary of arguments to pass to the tool.
Returns: The result from the tool execution. """ async with self.mcp_client: return await self.mcp_client.call_tool(tool_name, arguments)
@abstractmethod def _step_impl( self, action: Action, timeout_s: Optional[float] = None, **kwargs: Any, ) -> Observation: """ Handle non-MCP actions in the environment.
Subclasses must implement this method to handle any actions that are not ListToolsAction or CallToolAction. This is where environment-specific action processing should occur.
Args: action: The action to execute (guaranteed not to be an MCP action). timeout_s: Optional timeout in seconds. **kwargs: Additional arguments.
Returns: An Observation appropriate for the action. """ pass
def close(self) -> None: """ Clean up resources used by the environment.
This method cleans up the MCP client and any other resources. Subclasses should call super().close() if they override this method. """ # The MCP client uses async context manager, so cleanup happens # automatically when the context exits. We just clear references. self.mcp_client = None self.mcp_server = NoneDockerfile+26-22
README.md+85-38
__init__.pyAdded+12
client.pyAdded+56
envs/coding_env/README.mdAdded+163
envs/coding_env/__init__.pyAdded+12
envs/coding_env/client.pyAdded+56
envs/coding_env/models.pyAdded+34
envs/coding_env/openenv.yamlAdded+5
envs/coding_env/pyproject.tomlAdded+35
envs/coding_env/server/DockerfileAdded+35
envs/coding_env/server/Dockerfile.backupAdded+25
envs/coding_env/server/README.mdAdded+51
envs/coding_env/server/__init__.pyAdded+11
envs/coding_env/server/app.pyAdded+47
envs/coding_env/server/python_codeact_env.pyAdded+117
envs/coding_env/server/python_executor.pyAdded+157
envs/coding_env/server/transforms.pyAdded+94
models.pyAdded+34
openenv.yamlAdded+5
pyproject.tomlAdded+35
server/DockerfileAdded+35
server/Dockerfile.backupAdded+25
server/README.mdAdded+51
server/__init__.pyAdded+11
server/app.pyAdded+47
server/python_codeact_env.pyAdded+117
server/python_executor.pyAdded+157
server/transforms.pyAdded+94
src/__init__.pyAdded+7
src/core/README.md+53-21
src/core/__init__.py+70-8
src/core/client_types.py+3-2
src/core/containers/__init__.py+1-1
src/core/containers/images/Dockerfile+29-11
src/core/containers/images/README.md+8-8
src/core/containers/runtime/__init__.py+12-2
src/core/containers/runtime/daytona_provider.pyAdded+572
src/core/containers/runtime/providers.py+383-7
src/core/containers/runtime/uv_provider.pyAdded+224
src/core/containers/test_local_docker_provider.py+8-6
src/core/env_client.pyAdded+484
src/core/env_server/__init__.py+118-3
src/core/env_server/base_transforms.py+1-1
src/core/env_server/exceptions.pyAdded+105
src/core/env_server/gradio_theme.pyAdded+128
src/core/env_server/gradio_ui.pyAdded+240
src/core/env_server/http_server.py+1263-105
src/core/env_server/interfaces.py+189-10
src/core/env_server/mcp_environment.pyAdded+624