burtenshaw HF Staff commited on
Commit
f174c9d
·
verified ·
1 Parent(s): 6dd47af

Upload folder using huggingface_hub

Browse files
src/core/README.md ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # <img width="35" height="35" alt="image" src="https://github.com/user-attachments/assets/2700a971-e5d6-4036-b03f-2f89c9791609" /> OpenEnv: Agentic Execution Environments
2
+
3
+ An 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.
4
+
5
+ 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.
6
+
7
+
8
+ ## Overview
9
+ `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.
10
+
11
+ > ⚠️ **Early Development Warning** OpenEnv is currently in an experimental
12
+ > stage. You should expect bugs, incomplete features, and APIs that may change
13
+ > in future versions. The project welcomes bugfixes, but to make sure things are
14
+ > well coordinated you should discuss any significant change before starting the
15
+ > work. It's recommended that you signal your intention to contribute in the
16
+ > issue tracker, either by filing a new issue or by claiming an existing one.
17
+
18
+
19
+ # OpenEnv Core
20
+
21
+ Core components for OpenEnv - a framework for building HTTP-based agentic environments.
22
+
23
+ ## Features
24
+
25
+ - **EnvClient**: Async-first client for interacting with remote environments
26
+ - **SyncEnvClient**: Synchronous wrapper via `.sync()` for sync codebases
27
+ - **HTTPEnvServer**: FastAPI-based server wrapper for exposing environments over HTTP/WebSocket
28
+ - **Container Providers**: Pluggable architecture for running containers (Docker, Kubernetes, etc.)
29
+ - **Type System**: Strongly-typed Action/Observation/State interfaces
30
+ - **Web Interface**: Optional web UI for interacting with environments
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install "openenv[core]"
36
+ ```
37
+
38
+ For development:
39
+ ```bash
40
+ pip install "openenv[core]"
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ### Creating an Environment Client
46
+
47
+ EnvClient is **async by default**. Use `async with` and `await` for all operations:
48
+
49
+ ```python
50
+ import asyncio
51
+ from openenv.core import EnvClient, StepResult
52
+ from dataclasses import dataclass
53
+ from typing import Any
54
+
55
+ @dataclass
56
+ class MyAction:
57
+ text: str
58
+
59
+ @dataclass
60
+ class MyObservation:
61
+ response: str
62
+
63
+ class MyEnvClient(EnvClient[MyAction, MyObservation, Any]):
64
+ def _step_payload(self, action: MyAction) -> dict:
65
+ return {"text": action.text}
66
+
67
+ def _parse_result(self, payload: dict) -> StepResult[MyObservation]:
68
+ obs_data = payload["observation"]
69
+ return StepResult(
70
+ observation=MyObservation(**obs_data),
71
+ reward=payload.get("reward"),
72
+ done=payload.get("done", False)
73
+ )
74
+
75
+ def _parse_state(self, payload: dict) -> Any:
76
+ return payload
77
+
78
+ # Async usage (recommended)
79
+ async def main():
80
+ client = await MyEnvClient.from_docker_image("my-env:latest")
81
+ async with client:
82
+ result = await client.reset()
83
+ step_result = await client.step(MyAction(text="hello"))
84
+
85
+ asyncio.run(main())
86
+
87
+ # Sync usage (via .sync() wrapper)
88
+ with MyEnvClient(base_url="http://localhost:8000").sync() as client:
89
+ result = client.reset()
90
+ step_result = client.step(MyAction(text="hello"))
91
+ ```
92
+
93
+ ### Creating an Environment Server
94
+
95
+ ```python
96
+ from openenv.core.env_server import Environment, HTTPEnvServer, create_app
97
+ from dataclasses import dataclass
98
+
99
+ @dataclass
100
+ class MyAction:
101
+ text: str
102
+
103
+ @dataclass
104
+ class MyObservation:
105
+ response: str
106
+ reward: float = 0.0
107
+ done: bool = False
108
+
109
+ class MyEnvironment(Environment):
110
+ def reset(self) -> MyObservation:
111
+ return MyObservation(response="Ready")
112
+
113
+ def step(self, action: MyAction) -> MyObservation:
114
+ return MyObservation(
115
+ response=f"Echo: {action.text}",
116
+ reward=1.0,
117
+ done=False
118
+ )
119
+
120
+ # Create FastAPI app
121
+ env = MyEnvironment()
122
+ app = create_app(env, MyAction, MyObservation)
123
+
124
+ # Run with: uvicorn module:app --host 0.0.0.0 --port 8000
125
+ ```
126
+
127
+ ## Container Providers
128
+
129
+ OpenEnv Core supports multiple container providers:
130
+
131
+ ### Local Docker Provider
132
+
133
+ ```python
134
+ from openenv.core.containers.runtime import LocalDockerProvider
135
+
136
+ provider = LocalDockerProvider()
137
+ base_url = provider.start_container("my-env:latest")
138
+ provider.wait_for_ready(base_url)
139
+ # Use environment...
140
+ provider.stop_container()
141
+ ```
142
+
143
+ ### Kubernetes Provider (Coming Soon)
144
+
145
+ ```python
146
+ from openenv.core.containers.runtime import KubernetesProvider
147
+
148
+ provider = KubernetesProvider(namespace="envs")
149
+ base_url = provider.start_container("my-env:latest")
150
+ # Use environment...
151
+ provider.stop_container()
152
+ ```
153
+
154
+
155
+ ## API Reference
156
+
157
+ ### EnvClient
158
+
159
+ Async base class for environment clients. Key methods:
160
+
161
+ - `async connect()`: Establish WebSocket connection
162
+ - `async reset(**kwargs)`: Reset environment
163
+ - `async step(action)`: Execute action
164
+ - `async state()`: Get current state
165
+ - `async close()`: Close connection and cleanup
166
+ - `sync()`: Return a SyncEnvClient wrapper for synchronous usage
167
+
168
+ Abstract methods to implement:
169
+ - `_step_payload(action)`: Convert action to JSON
170
+ - `_parse_result(payload)`: Parse response to StepResult
171
+ - `_parse_state(payload)`: Parse state response
172
+
173
+ ### SyncEnvClient
174
+
175
+ Synchronous wrapper around EnvClient. Use `client.sync()` to get one:
176
+
177
+ ```python
178
+ sync_client = async_client.sync()
179
+ with sync_client:
180
+ result = sync_client.reset()
181
+ result = sync_client.step(action)
182
+ ```
183
+
184
+ ### HTTPEnvServer
185
+
186
+ Server wrapper with these methods:
187
+
188
+ - `register_routes(app)`: Register endpoints on FastAPI app
189
+ - `_deserialize_action(data)`: Convert JSON to Action
190
+ - `_serialize_observation(obs)`: Convert Observation to JSON
191
+
192
+ ### Environment Interface
193
+
194
+ Base interface for environment implementations:
195
+
196
+ - `reset()`: Reset environment and return initial observation
197
+ - `step(action)`: Execute action and return observation
198
+ - `state`: Property returning current environment state
199
+
200
+ ## License
201
+
202
+ This project is licensed under the BSD-3-Clause License - see the LICENSE file for details.
203
+
204
+ ## Contributing
205
+
206
+ Contributions are welcome! Please see the main OpenEnv repository for contribution guidelines.
207
+
208
+ ## Links
209
+
210
+ - **Homepage**: https://github.com/meta-pytorch/OpenEnv
211
+ - **Documentation**: https://github.com/meta-pytorch/OpenEnv/blob/main/README.md
212
+ - **Bug Tracker**: https://github.com/meta-pytorch/OpenEnv/issues
src/core/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Core components for agentic environments."""
8
+
9
+ # Re-export main components from submodules for convenience
10
+ from .env_server import * # noqa: F403
11
+ from . import env_server
12
+ from .env_client import EnvClient
13
+ from .sync_client import SyncEnvClient
14
+ from .generic_client import GenericEnvClient, GenericAction
15
+ from .mcp_client import MCPClientBase, MCPToolClient
16
+
17
+ __all__ = [
18
+ "EnvClient",
19
+ "SyncEnvClient",
20
+ "GenericEnvClient",
21
+ "GenericAction",
22
+ "MCPClientBase",
23
+ "MCPToolClient",
24
+ ] + env_server.__all__ # type: ignore
src/core/client_types.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Type definitions for EnvTorch
2
+ from dataclasses import dataclass
3
+ from typing import Generic, Optional, TypeVar
4
+
5
+ # Generic type for observations
6
+ ObsT = TypeVar("ObsT")
7
+ StateT = TypeVar("StateT")
8
+
9
+
10
+ @dataclass
11
+ class StepResult(Generic[ObsT]):
12
+ """
13
+ Represents the result of one environment step.
14
+
15
+ Attributes:
16
+ observation: The environment's observation after the action.
17
+ reward: Scalar reward for this step (optional).
18
+ done: Whether the episode is finished.
19
+ """
20
+
21
+ observation: ObsT
22
+ reward: Optional[float] = None
23
+ done: bool = False
src/core/containers/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Container management for environment servers."""
src/core/containers/images/Dockerfile ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ #
8
+ # OpenEnv Base Image
9
+ #
10
+ # This is the standard base image for all OpenEnv environment servers.
11
+ # It includes the minimal dependencies needed to run HTTP environment servers
12
+ # and uv for fast dependency management.
13
+ #
14
+ # Build from repo root: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .
15
+ # Tag: docker tag openenv-base:latest openenv-base:0.2.0
16
+ #
17
+
18
+ FROM ghcr.io/astral-sh/uv:0.5.27-python3.11-bookworm-slim AS builder
19
+
20
+ # Set working directory
21
+ WORKDIR /app
22
+
23
+ # Copy core pyproject.toml and lockfile for dependency installation
24
+ COPY pyproject.toml uv.lock* ./
25
+
26
+ # Install core dependencies using uv with cache mount
27
+ RUN --mount=type=cache,target=/root/.cache/uv \
28
+ uv pip install --system -r pyproject.toml
29
+
30
+ # Final runtime stage
31
+ FROM python:3.11-slim
32
+
33
+ # Set metadata
34
+ LABEL maintainer="OpenEnv Team"
35
+ LABEL description="Base image for OpenEnv based environment servers with uv"
36
+ LABEL version="0.2.0"
37
+
38
+ # Install system dependencies
39
+ RUN apt-get update && apt-get install -y --no-install-recommends \
40
+ curl \
41
+ ca-certificates \
42
+ && rm -rf /var/lib/apt/lists/*
43
+
44
+ # Copy uv from builder
45
+ COPY --from=builder /usr/local/bin/uv /usr/local/bin/uvx /usr/local/bin/
46
+
47
+ # Copy installed Python packages from builder
48
+ COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
49
+
50
+ # Copy console scripts installed by pip (uvicorn, fastapi, etc.)
51
+ COPY --from=builder /usr/local/bin/uvicorn /usr/local/bin/fastapi /usr/local/bin/
52
+
53
+ # Set working directory
54
+ WORKDIR /app
55
+
56
+ # Default environment variables
57
+ ENV PYTHONPATH=/app/src
58
+ ENV PYTHONUNBUFFERED=1
59
+ ENV UV_SYSTEM_PYTHON=1
60
+
61
+ # Default expose port (can be overridden)
62
+ EXPOSE 8000
63
+
64
+ # Note: CMD should be specified in child Dockerfiles
src/core/containers/images/README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenEnv Base Image
2
+
3
+ Standard base image for all OpenEnv environment servers.
4
+
5
+ ## What's Included
6
+
7
+ | Layer | Size | Contents |
8
+ |-------|------|----------|
9
+ | python:3.11-slim | 200 MB | Base Python runtime |
10
+ | + Dependencies | 100 MB | FastAPI, uvicorn, requests |
11
+ | **Total** | **~300 MB** | Ready for environment servers |
12
+
13
+ ## Image Sizes
14
+
15
+ ```
16
+ openenv-base:latest 300 MB (python + fastapi + uvicorn)
17
+ ```
18
+ echo-env:latest 500 MB (python + fastapi + uvicorn + app)
19
+ coding-env:latest 520 MB (python + fastapi + uvicorn + app + tools)
20
+ another-env:latest 510 MB (python + fastapi + uvicorn + app)
21
+ ---
22
+ Total: 1.5 GB (with lots of duplication)
23
+ ```
24
+
25
+ ### With Base Images (✅ Solution)
26
+ ```
27
+ openenv-base:latest 300 MB (python + fastapi + uvicorn)
28
+ echo-env:latest 50 MB (app only, uses base)
29
+ coding-env:latest 70 MB (app + tools, uses base)
30
+ another-env:latest 45 MB (app only, uses base)
31
+ ---
32
+ Total: 465 MB (base shared, minimal duplication)
33
+ ```
34
+
35
+ ## Building the Base Image
36
+
37
+ ```bash
38
+ # From project root
39
+ docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .
40
+ ```
41
+
42
+ ## Usage in Environment Dockerfiles
43
+
44
+ Each environment Dockerfile should start with:
45
+
46
+ ```dockerfile
47
+ FROM openenv-base:latest
48
+
49
+ # Copy only environment-specific files
50
+ COPY src/openenv/core/ /app/src/openenv/core/
51
+ COPY envs/my_env/ /app/envs/my_env/
52
+
53
+ # Run the server
54
+ CMD ["uvicorn", "envs.my_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]
55
+ ```
56
+
57
+ ## Base Image Contents
58
+
59
+ - Python 3.11-slim
60
+ - FastAPI >= 0.104.0
61
+ - Uvicorn >= 0.24.0
62
+ - Requests >= 2.25.0
63
+ - curl (for health checks)
64
+
65
+ ## Example: Building Echo Environment
66
+
67
+ ```bash
68
+ # Step 1: Build base image (do this once)
69
+ docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .
70
+
71
+ # Step 2: Build echo environment (uses base)
72
+ docker build -t echo-env:latest -f envs/echo_env/server/Dockerfile .
73
+
74
+ # Step 3: Run echo environment
75
+ docker run -p 8000:8000 echo-env:latest
76
+ ```
77
+
78
+ ## Updating the Base
79
+
80
+ When dependencies need updating:
81
+
82
+ 1. Update `src/openenv/core/containers/images/Dockerfile`
83
+ 2. Rebuild base image
84
+ 3. Rebuild all environment images (they'll use new base)
85
+
86
+ ```bash
87
+ # Update base
88
+ docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .
89
+
90
+ # Rebuild environments (they automatically use new base)
91
+ docker build -t echo-env:latest -f envs/echo_env/server/Dockerfile .
92
+ ```
src/core/containers/runtime/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Container runtime providers."""
8
+
9
+ from .providers import (
10
+ ContainerProvider,
11
+ DockerSwarmProvider,
12
+ KubernetesProvider,
13
+ LocalDockerProvider,
14
+ RuntimeProvider,
15
+ )
16
+ from .uv_provider import UVProvider
17
+
18
+ __all__ = [
19
+ "ContainerProvider",
20
+ "DockerSwarmProvider",
21
+ "LocalDockerProvider",
22
+ "KubernetesProvider",
23
+ "RuntimeProvider",
24
+ "UVProvider",
25
+ ]
src/core/containers/runtime/daytona_provider.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Daytona container provider for running OpenEnv environments in Daytona cloud sandboxes.
9
+
10
+ Requires the ``daytona`` SDK: ``pip install daytona>=0.10``
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import shlex
18
+ import time
19
+ from typing import Any, Callable, Dict, Optional
20
+
21
+ import yaml
22
+
23
+ from .providers import ContainerProvider
24
+
25
+
26
+ class DaytonaProvider(ContainerProvider):
27
+ """
28
+ Container provider that runs environments in Daytona cloud sandboxes.
29
+
30
+ Example:
31
+ >>> provider = DaytonaProvider(api_key="your-key")
32
+ >>> image = DaytonaProvider.image_from_dockerfile("envs/echo_env/server/Dockerfile")
33
+ >>> base_url = provider.start_container(image)
34
+ >>> provider.wait_for_ready(base_url)
35
+ >>> provider.stop_container()
36
+ """
37
+
38
+ _dockerfile_registry: Dict[str, Dict[str, Any]] = {}
39
+
40
+ def __init__(
41
+ self,
42
+ *,
43
+ api_key: Optional[str] = None,
44
+ public: bool = False,
45
+ resources: Optional[Any] = None,
46
+ auto_stop_interval: int = 15,
47
+ target: Optional[str] = None,
48
+ on_snapshot_create_logs: Optional[Callable[[str], None]] = None,
49
+ cmd: Optional[str] = None,
50
+ create_timeout: float = 300,
51
+ ):
52
+ """
53
+ Args:
54
+ api_key: Daytona API key. Falls back to ``DAYTONA_API_KEY`` env var.
55
+ public: If True, the sandbox preview is publicly accessible.
56
+ resources: Optional ``daytona.Resources`` instance for CPU/memory.
57
+ auto_stop_interval: Minutes of inactivity before auto-stop (0 disables).
58
+ target: Daytona target region (e.g. "us").
59
+ on_snapshot_create_logs: Callback for snapshot build log lines.
60
+ cmd: Shell command to start the server inside the sandbox.
61
+ create_timeout: Seconds to wait for sandbox creation (default 300).
62
+ Heavy images (e.g. with Playwright/Chromium) may need more.
63
+ """
64
+ from daytona import Daytona, DaytonaConfig
65
+
66
+ config_kwargs: Dict[str, Any] = {}
67
+ resolved_key = api_key or os.environ.get("DAYTONA_API_KEY")
68
+ if resolved_key:
69
+ config_kwargs["api_key"] = resolved_key
70
+ if target:
71
+ config_kwargs["target"] = target
72
+
73
+ self._daytona = Daytona(DaytonaConfig(**config_kwargs))
74
+ self._public = public
75
+ self._resources = resources
76
+ self._auto_stop_interval = auto_stop_interval
77
+ self._on_snapshot_create_logs = on_snapshot_create_logs
78
+ self._cmd = cmd
79
+ self._create_timeout = create_timeout
80
+ self._sandbox: Any = None
81
+ self._preview_url: Optional[str] = None
82
+
83
+ def _discover_server_cmd(self, sandbox: Any, port: int = 8000) -> str:
84
+ """Discover the server command from ``openenv.yaml`` inside *sandbox*.
85
+
86
+ Finds the file, reads the ``app`` field, and constructs a command
87
+ of the form ``cd <env_root> && python -m uvicorn <app> --host 0.0.0.0 --port <port>``.
88
+
89
+ Raises:
90
+ ValueError: If ``openenv.yaml`` is not found or lacks an ``app`` field.
91
+ """
92
+ yaml_path = self._find_openenv_yaml(sandbox)
93
+ if yaml_path is None:
94
+ raise ValueError(
95
+ "Could not find openenv.yaml inside the sandbox. "
96
+ "Pass an explicit cmd= to DaytonaProvider or start_container()."
97
+ )
98
+
99
+ cat_resp = sandbox.process.exec(f"cat {shlex.quote(yaml_path)}", timeout=10)
100
+ content = cat_resp.result if hasattr(cat_resp, "result") else str(cat_resp)
101
+ app = self._parse_app_field(content)
102
+ if app is None:
103
+ raise ValueError(
104
+ f"openenv.yaml at {yaml_path} does not contain an 'app' field. "
105
+ "Pass an explicit cmd= to DaytonaProvider or start_container()."
106
+ )
107
+
108
+ # The directory containing openenv.yaml is the env root
109
+ env_root = yaml_path.rsplit("/", 1)[0]
110
+ return (
111
+ f"cd {shlex.quote(env_root)} && "
112
+ f"python -m uvicorn {shlex.quote(app)} --host 0.0.0.0 --port {port}"
113
+ )
114
+
115
+ def _find_openenv_yaml(self, sandbox: Any) -> Optional[str]:
116
+ """Locate ``openenv.yaml`` inside the sandbox.
117
+
118
+ Tries the modern layout path ``/app/env/openenv.yaml`` first,
119
+ then falls back to a ``find`` command for the old layout.
120
+ """
121
+ # Fast path: modern Dockerfile layout
122
+ resp = sandbox.process.exec(
123
+ "test -f /app/env/openenv.yaml && echo found", timeout=10
124
+ )
125
+ out = resp.result if hasattr(resp, "result") else str(resp)
126
+ if "found" in (out or ""):
127
+ return "/app/env/openenv.yaml"
128
+
129
+ # Fallback: search for it (redirect stderr so error messages
130
+ # like "No such file or directory" don't get mistaken for paths).
131
+ resp = sandbox.process.exec(
132
+ "find /app -maxdepth 4 -name openenv.yaml -print -quit 2>/dev/null",
133
+ timeout=10,
134
+ )
135
+ path = (resp.result if hasattr(resp, "result") else str(resp) or "").strip()
136
+ if path and path.startswith("/"):
137
+ return path
138
+
139
+ return None
140
+
141
+ @staticmethod
142
+ def _parse_app_field(yaml_content: str) -> Optional[str]:
143
+ """Extract the ``app`` value from raw openenv.yaml content.
144
+
145
+ Uses PyYAML to handle comments, quotes, and nested keys correctly.
146
+ """
147
+ try:
148
+ data = yaml.safe_load(yaml_content) or {}
149
+ except Exception:
150
+ return None
151
+
152
+ if not isinstance(data, dict):
153
+ return None
154
+
155
+ value = data.get("app")
156
+ if isinstance(value, str):
157
+ value = value.strip()
158
+ return value if value else None
159
+ return None
160
+
161
+ @staticmethod
162
+ def _parse_dockerfile_cmd(dockerfile_content: str) -> Optional[str]:
163
+ """Extract the server command from the last ``CMD`` in a Dockerfile.
164
+
165
+ Handles exec form (``CMD ["prog", "arg"]``) and shell form
166
+ (``CMD prog arg``). When a Dockerfile has multiple ``CMD``
167
+ instructions (e.g. multi-stage builds), the last one wins - same
168
+ semantics as Docker itself. Lines where ``CMD`` appears inside a
169
+ comment are ignored.
170
+
171
+ Returns:
172
+ The command as a single string, or ``None`` if no ``CMD`` found.
173
+ """
174
+ import re
175
+
176
+ last_cmd: Optional[str] = None
177
+ for line in dockerfile_content.splitlines():
178
+ stripped = line.strip()
179
+ # Skip comments
180
+ if stripped.startswith("#"):
181
+ continue
182
+ match = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE)
183
+ if match:
184
+ last_cmd = match.group(1).strip()
185
+
186
+ if last_cmd is None:
187
+ return None
188
+
189
+ # Exec form: CMD ["executable", "param1", ...]
190
+ if last_cmd.startswith("["):
191
+ try:
192
+ parts = json.loads(last_cmd)
193
+ if isinstance(parts, list) and all(isinstance(p, str) for p in parts):
194
+ return " ".join(parts)
195
+ except (json.JSONDecodeError, TypeError):
196
+ pass
197
+
198
+ # Shell form: CMD executable param1 ...
199
+ return last_cmd if last_cmd else None
200
+
201
+ @staticmethod
202
+ def strip_buildkit_syntax(dockerfile_content: str) -> str:
203
+ """Remove BuildKit ``--mount=...`` flags from ``RUN`` instructions.
204
+
205
+ Handles single-line flags, multi-line continuations, and multiple
206
+ ``--mount`` flags spread across continuation lines. Only leading
207
+ ``--mount`` flags are removed (before the actual command starts).
208
+
209
+ Daytona's ``Image.from_dockerfile`` does not support BuildKit
210
+ ``--mount`` syntax. This helper strips the flags so that standard
211
+ Dockerfiles (like the ones generated by ``openenv build``) can
212
+ be used directly.
213
+ """
214
+ import re
215
+
216
+ def strip_leading_mounts(text: str) -> str:
217
+ remaining = text
218
+ while True:
219
+ match = re.match(r"\s*--mount=\S+\s*", remaining)
220
+ if not match:
221
+ return remaining
222
+ remaining = remaining[match.end() :]
223
+
224
+ lines = dockerfile_content.split("\n")
225
+ result: list[str] = []
226
+ in_run = False
227
+ in_mount_prefix = False
228
+
229
+ for line in lines:
230
+ line_out = line
231
+ run_start = False
232
+ if re.match(r"\s*RUN(\s+|$)", line, flags=re.IGNORECASE):
233
+ in_run = True
234
+ in_mount_prefix = True
235
+ run_start = True
236
+
237
+ if in_run and in_mount_prefix:
238
+ original_ends_with_slash = line_out.rstrip().endswith("\\")
239
+ if run_start:
240
+ match = re.match(r"(\s*RUN\s+)(.*)$", line_out, flags=re.IGNORECASE)
241
+ if match:
242
+ run_prefix, remainder = match.group(1), match.group(2)
243
+ else:
244
+ run_prefix, remainder = line_out, ""
245
+ new_remainder = strip_leading_mounts(remainder)
246
+ line_out = run_prefix + new_remainder
247
+ content_for_check = new_remainder
248
+ else:
249
+ new_remainder = strip_leading_mounts(line_out)
250
+ line_out = new_remainder
251
+ content_for_check = new_remainder
252
+
253
+ if original_ends_with_slash and not line_out.rstrip().endswith("\\"):
254
+ line_out = line_out.rstrip() + " \\"
255
+
256
+ if content_for_check.strip() not in ("", "\\"):
257
+ in_mount_prefix = False
258
+
259
+ if in_run and not line_out.rstrip().endswith("\\"):
260
+ in_run = False
261
+ in_mount_prefix = False
262
+
263
+ result.append(line_out)
264
+
265
+ return "\n".join(result)
266
+
267
+ @classmethod
268
+ def image_from_dockerfile(
269
+ cls,
270
+ dockerfile_path: str,
271
+ context_dir: str | None = None,
272
+ ) -> str:
273
+ """Validate a Dockerfile and return a ``dockerfile:`` URI for
274
+ :meth:`start_container`.
275
+
276
+ Eagerly validates the Dockerfile (existence, COPY sources,
277
+ BuildKit stripping) and stores the processed content in an
278
+ internal registry. The actual ``daytona.Image`` is created
279
+ later inside ``start_container``.
280
+
281
+ Args:
282
+ dockerfile_path: Path to the Dockerfile on disk.
283
+ context_dir: Build context directory. Defaults to the
284
+ Dockerfile's grandparent directory, matching the
285
+ ``openenv init`` convention where Dockerfiles live in
286
+ ``<env>/server/Dockerfile`` and the build context is
287
+ ``<env>/``. Pass explicitly for non-standard layouts
288
+ (e.g. ``context_dir="."`` for repo-root contexts).
289
+
290
+ Returns:
291
+ A ``"dockerfile:<abs_path>"`` string to pass to
292
+ ``start_container``.
293
+
294
+ Raises:
295
+ FileNotFoundError: If *dockerfile_path* does not exist.
296
+ ValueError: If *context_dir* is given but does not exist,
297
+ or if COPY sources in the Dockerfile cannot be found
298
+ under the resolved context directory.
299
+ """
300
+ import pathlib
301
+ import re
302
+
303
+ src = pathlib.Path(dockerfile_path).resolve()
304
+ if not src.is_file():
305
+ raise FileNotFoundError(f"Dockerfile not found: {dockerfile_path}")
306
+
307
+ if context_dir is not None:
308
+ ctx = pathlib.Path(context_dir)
309
+ if not ctx.is_dir():
310
+ raise ValueError(f"context_dir does not exist: {context_dir}")
311
+ else:
312
+ # Default: grandparent of the Dockerfile, matching the
313
+ # openenv init layout (<env>/server/Dockerfile -> <env>/).
314
+ ctx = src.parent.parent
315
+
316
+ content = src.read_text()
317
+ stripped = cls.strip_buildkit_syntax(content)
318
+
319
+ # Validate that COPY sources exist under the context directory.
320
+ # This catches mismatches early (e.g. a Dockerfile expecting repo
321
+ # root as context when we defaulted to the env directory).
322
+ for line in stripped.splitlines():
323
+ m = re.match(r"^\s*COPY\s+(?!--from=)(\S+)\s+", line, re.IGNORECASE)
324
+ if not m:
325
+ continue
326
+ copy_src = m.group(1)
327
+ if copy_src.startswith("/"):
328
+ continue
329
+ resolved = ctx / copy_src
330
+ if not resolved.exists() and not any(ctx.glob(copy_src)):
331
+ raise ValueError(
332
+ f"Dockerfile COPY source '{copy_src}' not found "
333
+ f"under context_dir '{ctx}'. This Dockerfile may "
334
+ f"expect a different build context (e.g. the repo "
335
+ f"root). Pass context_dir explicitly."
336
+ )
337
+
338
+ # Parse CMD from the original Dockerfile so start_container can
339
+ # use it as a fallback when openenv.yaml is unavailable.
340
+ parsed_cmd = cls._parse_dockerfile_cmd(content)
341
+
342
+ cls._dockerfile_registry[str(src)] = {
343
+ "stripped_content": stripped,
344
+ "context_dir": str(ctx),
345
+ "server_cmd": parsed_cmd,
346
+ }
347
+
348
+ return f"dockerfile:{src}"
349
+
350
+ def start_container(
351
+ self,
352
+ image: str,
353
+ port: Optional[int] = None,
354
+ env_vars: Optional[Dict[str, str]] = None,
355
+ **kwargs: Any,
356
+ ) -> str:
357
+ """
358
+ Create a Daytona sandbox from a Docker image or snapshot.
359
+
360
+ Daytona does not execute the image's CMD (known bug — ENTRYPOINT
361
+ runs, CMD does not). The server command is resolved in order:
362
+
363
+ 1. Explicit ``cmd`` passed to the constructor.
364
+ 2. ``cmd`` key in ``**kwargs`` (popped before forwarding).
365
+ 3. Auto-discovered from ``openenv.yaml`` inside the sandbox.
366
+ 4. ``CMD`` parsed from the Dockerfile (when *image* came from
367
+ ``image_from_dockerfile``).
368
+
369
+ Args:
370
+ image: Docker image name (e.g. ``"echo-env:latest"``),
371
+ ``"snapshot:<name>"`` to create from a pre-built snapshot,
372
+ or ``"dockerfile:<path>"`` returned by
373
+ :meth:`image_from_dockerfile`.
374
+ port: Must be ``None`` or ``8000``. Daytona exposes port 8000
375
+ via its preview proxy; other ports raise ``ValueError``.
376
+ env_vars: Environment variables forwarded to the sandbox.
377
+ **kwargs: ``cmd`` (str) to override the server command;
378
+ remaining kwargs passed through to ``Daytona.create()``.
379
+
380
+ Returns:
381
+ HTTPS preview URL for the sandbox (base_url).
382
+ """
383
+ if port is not None and port != 8000:
384
+ raise ValueError(
385
+ f"DaytonaProvider only supports port 8000 (got {port}). "
386
+ "The Daytona preview proxy routes to port 8000 inside the sandbox."
387
+ )
388
+
389
+ # Resolve the server command (may be None; discovery happens after
390
+ # sandbox creation when we can inspect the filesystem).
391
+ cmd = kwargs.pop("cmd", None) or self._cmd
392
+
393
+ # CMD parsed from Dockerfile (populated for "dockerfile:" images).
394
+ parsed_cmd: Optional[str] = None
395
+
396
+ # Build creation params
397
+ create_kwargs: Dict[str, Any] = {}
398
+ if env_vars:
399
+ create_kwargs["env_vars"] = env_vars
400
+ if self._public:
401
+ create_kwargs["public"] = True
402
+ if self._auto_stop_interval != 15:
403
+ create_kwargs["auto_stop_interval"] = self._auto_stop_interval
404
+
405
+ if image.startswith("snapshot:"):
406
+ from daytona import CreateSandboxFromSnapshotParams
407
+
408
+ snapshot_name = image[len("snapshot:") :]
409
+ params = CreateSandboxFromSnapshotParams(
410
+ snapshot=snapshot_name, **create_kwargs
411
+ )
412
+ elif image.startswith("dockerfile:"):
413
+ from daytona import CreateSandboxFromImageParams, Image
414
+
415
+ dockerfile_path = image[len("dockerfile:") :]
416
+ meta = self._dockerfile_registry.get(dockerfile_path)
417
+ if meta is None:
418
+ raise ValueError(
419
+ f"No registered Dockerfile metadata for {dockerfile_path}. "
420
+ "Call DaytonaProvider.image_from_dockerfile() first."
421
+ )
422
+
423
+ parsed_cmd = meta.get("server_cmd")
424
+
425
+ # Build the daytona Image from the pre-stripped content.
426
+ import pathlib
427
+ import uuid
428
+
429
+ ctx = pathlib.Path(meta["context_dir"])
430
+ tmp_name = f".daytona-{uuid.uuid4().hex[:8]}.dockerfile"
431
+ tmp_path = ctx / tmp_name
432
+ try:
433
+ tmp_path.write_text(meta["stripped_content"])
434
+ daytona_image = Image.from_dockerfile(str(tmp_path))
435
+ finally:
436
+ tmp_path.unlink(missing_ok=True)
437
+
438
+ img_kwargs: Dict[str, Any] = {
439
+ "image": daytona_image,
440
+ **create_kwargs,
441
+ }
442
+ if self._resources is not None:
443
+ img_kwargs["resources"] = self._resources
444
+ params = CreateSandboxFromImageParams(**img_kwargs)
445
+ else:
446
+ from daytona import CreateSandboxFromImageParams
447
+
448
+ img_kwargs = {"image": image, **create_kwargs}
449
+ if self._resources is not None:
450
+ img_kwargs["resources"] = self._resources
451
+ params = CreateSandboxFromImageParams(**img_kwargs)
452
+
453
+ # Create sandbox
454
+ extra: Dict[str, Any] = dict(kwargs)
455
+ if self._on_snapshot_create_logs is not None:
456
+ extra["on_snapshot_create_logs"] = self._on_snapshot_create_logs
457
+
458
+ self._sandbox = self._daytona.create(
459
+ params, timeout=self._create_timeout, **extra
460
+ )
461
+
462
+ try:
463
+ # Discover server command from openenv.yaml if not explicitly set.
464
+ if cmd is None:
465
+ try:
466
+ cmd = self._discover_server_cmd(self._sandbox)
467
+ except ValueError:
468
+ # Fall back to CMD parsed from Dockerfile (if available).
469
+ if parsed_cmd:
470
+ cmd = parsed_cmd
471
+ else:
472
+ raise
473
+
474
+ # Wrap in bash -c so compound commands (cd ... && uvicorn ...)
475
+ # are handled correctly by nohup. Write PID so we can check
476
+ # if the process crashed later in wait_for_ready().
477
+ escaped_cmd = shlex.quote(cmd)
478
+ self._sandbox.process.exec(
479
+ f"nohup bash -c {escaped_cmd} > /tmp/openenv-server.log 2>&1 &"
480
+ " echo $! > /tmp/openenv-server.pid",
481
+ timeout=10,
482
+ )
483
+
484
+ # Get a signed preview URL for port 8000. The token is
485
+ # embedded in the URL itself so no extra headers are needed.
486
+ signed = self._sandbox.create_signed_preview_url(
487
+ 8000, expires_in_seconds=86400
488
+ )
489
+ self._preview_url = signed.url
490
+ except Exception:
491
+ self.stop_container()
492
+ raise
493
+
494
+ return self._preview_url
495
+
496
+ def refresh_preview_url(self) -> str:
497
+ """Get a fresh signed preview URL (valid for 24h).
498
+
499
+ Daytona signed URLs expire after at most 24 hours. Call this to
500
+ get a new one for long-running sessions. The returned URL points
501
+ to the same sandbox — clients will need to reconnect using it.
502
+ """
503
+ if self._sandbox is None:
504
+ raise RuntimeError("No active sandbox to refresh URL for.")
505
+ signed = self._sandbox.create_signed_preview_url(8000, expires_in_seconds=86400)
506
+ self._preview_url = signed.url
507
+ return self._preview_url
508
+
509
+ def stop_container(self) -> None:
510
+ """Delete the Daytona sandbox."""
511
+ if self._sandbox is None:
512
+ return
513
+
514
+ try:
515
+ self._daytona.delete(self._sandbox)
516
+ finally:
517
+ self._sandbox = None
518
+ self._preview_url = None
519
+
520
+ def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None:
521
+ """
522
+ Poll the /health endpoint until the sandbox is ready.
523
+
524
+ Uses a longer default timeout (120s) than Docker providers because
525
+ Daytona sandboxes may have cold-start latency.
526
+
527
+ Args:
528
+ base_url: Preview URL returned by ``start_container()``.
529
+ timeout_s: Maximum seconds to wait.
530
+
531
+ Raises:
532
+ TimeoutError: If the sandbox doesn't become ready in time.
533
+ RuntimeError: If the server process died (detected via PID check).
534
+ """
535
+ import requests
536
+
537
+ health_url = f"{base_url}/health"
538
+
539
+ deadline = time.time() + timeout_s
540
+ while time.time() < deadline:
541
+ try:
542
+ response = requests.get(health_url, timeout=5.0)
543
+ if response.status_code == 200:
544
+ return
545
+ except requests.RequestException:
546
+ pass
547
+
548
+ # Early exit: if the server process died, raise immediately
549
+ # instead of waiting for the full health-check timeout.
550
+ if self._sandbox is not None:
551
+ resp = self._sandbox.process.exec(
552
+ "kill -0 $(cat /tmp/openenv-server.pid) 2>/dev/null"
553
+ " && echo RUNNING || echo DEAD",
554
+ timeout=10,
555
+ )
556
+ out = resp.result if hasattr(resp, "result") else str(resp)
557
+ if "DEAD" in (out or ""):
558
+ log_resp = self._sandbox.process.exec(
559
+ "cat /tmp/openenv-server.log 2>/dev/null", timeout=10
560
+ )
561
+ log = (
562
+ log_resp.result
563
+ if hasattr(log_resp, "result")
564
+ else str(log_resp)
565
+ )
566
+ raise RuntimeError(f"Server process died.\nLog:\n{log}")
567
+
568
+ time.sleep(1.0)
569
+
570
+ raise TimeoutError(
571
+ f"Daytona sandbox at {base_url} did not become ready within {timeout_s}s"
572
+ )
src/core/containers/runtime/providers.py ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Container provider abstractions for running environment servers.
9
+
10
+ This module provides a pluggable architecture for different container providers
11
+ (local Docker, Kubernetes, cloud providers, etc.) to be used with EnvClient.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from abc import ABC, abstractmethod
17
+ from typing import Any, Dict, Optional, Sequence
18
+
19
+
20
+ class ContainerProvider(ABC):
21
+ """
22
+ Abstract base class for container providers.
23
+
24
+ Providers implement this interface to support different container platforms:
25
+ - LocalDockerProvider: Runs containers on local Docker daemon
26
+ - KubernetesProvider: Runs containers in Kubernetes cluster
27
+ - FargateProvider: Runs containers on AWS Fargate
28
+ - CloudRunProvider: Runs containers on Google Cloud Run
29
+
30
+ The provider manages a single container lifecycle and provides the base URL
31
+ for connecting to it.
32
+
33
+ Example:
34
+ >>> provider = LocalDockerProvider()
35
+ >>> base_url = provider.start_container("echo-env:latest")
36
+ >>> print(base_url) # http://localhost:8000
37
+ >>> # Use the environment via base_url
38
+ >>> provider.stop_container()
39
+ """
40
+
41
+ @abstractmethod
42
+ def start_container(
43
+ self,
44
+ image: str,
45
+ port: Optional[int] = None,
46
+ env_vars: Optional[Dict[str, str]] = None,
47
+ **kwargs: Any,
48
+ ) -> str:
49
+ """
50
+ Start a container from the specified image.
51
+
52
+ Args:
53
+ image: Container image name (e.g., "echo-env:latest")
54
+ port: Port to expose (if None, provider chooses)
55
+ env_vars: Environment variables to pass to container
56
+ **kwargs: Provider-specific options
57
+
58
+ Returns:
59
+ Base URL to connect to the container (e.g., "http://localhost:8000")
60
+
61
+ Raises:
62
+ RuntimeError: If container fails to start
63
+ """
64
+ pass
65
+
66
+ @abstractmethod
67
+ def stop_container(self) -> None:
68
+ """
69
+ Stop and remove the running container.
70
+
71
+ This cleans up the container that was started by start_container().
72
+ """
73
+ pass
74
+
75
+ @abstractmethod
76
+ def wait_for_ready(self, base_url: str, timeout_s: float = 30.0) -> None:
77
+ """
78
+ Wait for the container to be ready to accept requests.
79
+
80
+ This typically polls the /health endpoint until it returns 200.
81
+
82
+ Args:
83
+ base_url: Base URL of the container
84
+ timeout_s: Maximum time to wait
85
+
86
+ Raises:
87
+ TimeoutError: If container doesn't become ready in time
88
+ """
89
+ pass
90
+
91
+
92
+ class LocalDockerProvider(ContainerProvider):
93
+ """
94
+ Container provider for local Docker daemon.
95
+
96
+ This provider runs containers on the local machine using Docker.
97
+ Useful for development and testing.
98
+
99
+ Example:
100
+ >>> provider = LocalDockerProvider()
101
+ >>> base_url = provider.start_container("echo-env:latest")
102
+ >>> # Container running on http://localhost:<random-port>
103
+ >>> provider.stop_container()
104
+ """
105
+
106
+ def __init__(self):
107
+ """Initialize the local Docker provider."""
108
+ self._container_id: Optional[str] = None
109
+ self._container_name: Optional[str] = None
110
+
111
+ # Check if Docker is available
112
+ import subprocess
113
+
114
+ try:
115
+ subprocess.run(
116
+ ["docker", "version"],
117
+ check=True,
118
+ capture_output=True,
119
+ timeout=5,
120
+ )
121
+ except (
122
+ subprocess.CalledProcessError,
123
+ FileNotFoundError,
124
+ subprocess.TimeoutExpired,
125
+ ):
126
+ raise RuntimeError(
127
+ "Docker is not available. Please install Docker Desktop or Docker Engine."
128
+ )
129
+
130
+ def start_container(
131
+ self,
132
+ image: str,
133
+ port: Optional[int] = None,
134
+ env_vars: Optional[Dict[str, str]] = None,
135
+ **kwargs: Any,
136
+ ) -> str:
137
+ """
138
+ Start a Docker container locally.
139
+
140
+ Args:
141
+ image: Docker image name
142
+ port: Port to expose (if None, finds available port)
143
+ env_vars: Environment variables for the container
144
+ **kwargs: Additional Docker run options
145
+
146
+ Returns:
147
+ Base URL to connect to the container
148
+ """
149
+ import subprocess
150
+ import time
151
+
152
+ # Find available port if not specified
153
+ if port is None:
154
+ port = self._find_available_port()
155
+
156
+ # Generate container name
157
+ self._container_name = self._generate_container_name(image)
158
+
159
+ # Build docker run command
160
+ cmd = [
161
+ "docker",
162
+ "run",
163
+ "-d", # Detached
164
+ "--name",
165
+ self._container_name,
166
+ "-p",
167
+ f"{port}:8000", # Map port
168
+ ]
169
+
170
+ # Add environment variables
171
+ if env_vars:
172
+ for key, value in env_vars.items():
173
+ cmd.extend(["-e", f"{key}={value}"])
174
+
175
+ # Add image
176
+ cmd.append(image)
177
+
178
+ # Run container
179
+ try:
180
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
181
+ self._container_id = result.stdout.strip()
182
+ except subprocess.CalledProcessError as e:
183
+ error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}"
184
+ raise RuntimeError(error_msg) from e
185
+
186
+ # Wait a moment for container to start
187
+ time.sleep(1)
188
+
189
+ base_url = f"http://localhost:{port}"
190
+ return base_url
191
+
192
+ def stop_container(self) -> None:
193
+ """
194
+ Stop and remove the Docker container.
195
+ """
196
+ if self._container_id is None:
197
+ return
198
+
199
+ import subprocess
200
+
201
+ try:
202
+ # Stop container
203
+ subprocess.run(
204
+ ["docker", "stop", self._container_id],
205
+ capture_output=True,
206
+ check=True,
207
+ timeout=10,
208
+ )
209
+
210
+ # Remove container
211
+ subprocess.run(
212
+ ["docker", "rm", self._container_id],
213
+ capture_output=True,
214
+ check=True,
215
+ timeout=10,
216
+ )
217
+ except subprocess.CalledProcessError:
218
+ # Container might already be stopped/removed
219
+ pass
220
+ finally:
221
+ self._container_id = None
222
+ self._container_name = None
223
+
224
+ def wait_for_ready(self, base_url: str, timeout_s: float = 30.0) -> None:
225
+ """
226
+ Wait for container to be ready by polling /health endpoint.
227
+
228
+ Args:
229
+ base_url: Base URL of the container
230
+ timeout_s: Maximum time to wait
231
+
232
+ Raises:
233
+ TimeoutError: If container doesn't become ready
234
+ """
235
+ import time
236
+ import requests
237
+
238
+ start_time = time.time()
239
+ health_url = f"{base_url}/health"
240
+
241
+ # Bypass proxy for localhost to avoid proxy issues
242
+ proxies = {"http": None, "https": None}
243
+
244
+ while time.time() - start_time < timeout_s:
245
+ try:
246
+ response = requests.get(health_url, timeout=2.0, proxies=proxies)
247
+ if response.status_code == 200:
248
+ return
249
+ except requests.RequestException:
250
+ pass
251
+
252
+ time.sleep(0.5)
253
+
254
+ raise TimeoutError(
255
+ f"Container at {base_url} did not become ready within {timeout_s}s"
256
+ )
257
+
258
+ def _find_available_port(self) -> int:
259
+ """
260
+ Find an available port on localhost.
261
+
262
+ Returns:
263
+ An available port number
264
+ """
265
+ import socket
266
+
267
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
268
+ s.bind(("", 0))
269
+ s.listen(1)
270
+ port = s.getsockname()[1]
271
+ return port
272
+
273
+ def _generate_container_name(self, image: str) -> str:
274
+ """
275
+ Generate a unique container name based on image name and timestamp.
276
+
277
+ Args:
278
+ image: Docker image name
279
+
280
+ Returns:
281
+ A unique container name
282
+ """
283
+ import time
284
+
285
+ clean_image = image.split("/")[-1].split(":")[0]
286
+ timestamp = int(time.time() * 1000)
287
+ return f"{clean_image}-{timestamp}"
288
+
289
+
290
+ class DockerSwarmProvider(ContainerProvider):
291
+ """
292
+ Container provider that uses Docker Swarm services for local concurrency.
293
+
294
+ This provider creates a replicated Swarm service backed by the local Docker
295
+ engine. The built-in load-balancer fans requests across the replicas,
296
+ allowing multiple container instances to run concurrently on the developer
297
+ workstation (mirroring the workflow described in the Docker stack docs).
298
+ """
299
+
300
+ def __init__(
301
+ self,
302
+ *,
303
+ auto_init_swarm: bool = True,
304
+ overlay_network: Optional[str] = None,
305
+ ):
306
+ """
307
+ Args:
308
+ auto_init_swarm: Whether to call ``docker swarm init`` when Swarm
309
+ is not active. Otherwise, user must manually initialize Swarm.
310
+ overlay_network: Optional overlay network name for the service.
311
+ When provided, the network is created with
312
+ ``docker network create --driver overlay --attachable`` if it
313
+ does not already exist.
314
+ """
315
+ self._service_name: Optional[str] = None
316
+ self._service_id: Optional[str] = None
317
+ self._published_port: Optional[int] = None
318
+ self._overlay_network = overlay_network
319
+ self._auto_init_swarm = auto_init_swarm
320
+
321
+ self._ensure_docker_available()
322
+ self._ensure_swarm_initialized()
323
+ if self._overlay_network:
324
+ self._ensure_overlay_network(self._overlay_network)
325
+
326
+ def start_container(
327
+ self,
328
+ image: str,
329
+ port: Optional[int] = None,
330
+ env_vars: Optional[Dict[str, str]] = None,
331
+ **kwargs: Any,
332
+ ) -> str:
333
+ """
334
+ Start (or scale) a Swarm service for the given image.
335
+
336
+ Supported kwargs:
337
+ replicas (int): Number of container replicas (default: 2).
338
+ cpu_limit (float | str): CPU limit passed to ``--limit-cpu``.
339
+ memory_limit (str): Memory limit passed to ``--limit-memory``.
340
+ constraints (Sequence[str]): Placement constraints.
341
+ labels (Dict[str, str]): Service labels.
342
+ command (Sequence[str] | str): Override container command.
343
+ """
344
+ import shlex
345
+ import subprocess
346
+ import time
347
+
348
+ allowed_kwargs = {
349
+ "replicas",
350
+ "cpu_limit",
351
+ "memory_limit",
352
+ "constraints",
353
+ "labels",
354
+ "command",
355
+ }
356
+ unknown = set(kwargs) - allowed_kwargs
357
+ if unknown:
358
+ raise ValueError(f"Unsupported kwargs for DockerSwarmProvider: {unknown}")
359
+
360
+ replicas = int(kwargs.get("replicas", 2))
361
+ cpu_limit = kwargs.get("cpu_limit")
362
+ memory_limit = kwargs.get("memory_limit")
363
+ constraints: Optional[Sequence[str]] = kwargs.get("constraints")
364
+ labels: Optional[Dict[str, str]] = kwargs.get("labels")
365
+ command_override = kwargs.get("command")
366
+
367
+ if port is None:
368
+ port = self._find_available_port()
369
+
370
+ self._service_name = self._generate_service_name(image)
371
+ self._published_port = port
372
+
373
+ cmd = [
374
+ "docker",
375
+ "service",
376
+ "create",
377
+ "--detach",
378
+ "--name",
379
+ self._service_name,
380
+ "--replicas",
381
+ str(max(1, replicas)),
382
+ "--publish",
383
+ f"{port}:8000",
384
+ ]
385
+
386
+ if self._overlay_network:
387
+ cmd.extend(["--network", self._overlay_network])
388
+
389
+ if env_vars:
390
+ for key, value in env_vars.items():
391
+ cmd.extend(["--env", f"{key}={value}"])
392
+
393
+ if cpu_limit is not None:
394
+ cmd.extend(["--limit-cpu", str(cpu_limit)])
395
+
396
+ if memory_limit is not None:
397
+ cmd.extend(["--limit-memory", str(memory_limit)])
398
+
399
+ if constraints:
400
+ for constraint in constraints:
401
+ cmd.extend(["--constraint", constraint])
402
+
403
+ if labels:
404
+ for key, value in labels.items():
405
+ cmd.extend(["--label", f"{key}={value}"])
406
+
407
+ cmd.append(image)
408
+
409
+ if command_override:
410
+ if isinstance(command_override, str):
411
+ cmd.extend(shlex.split(command_override))
412
+ else:
413
+ cmd.extend(command_override)
414
+
415
+ try:
416
+ result = subprocess.run(
417
+ cmd,
418
+ capture_output=True,
419
+ text=True,
420
+ check=True,
421
+ )
422
+ self._service_id = result.stdout.strip()
423
+ except subprocess.CalledProcessError as e:
424
+ error_msg = (
425
+ "Failed to start Docker Swarm service.\n"
426
+ f"Command: {' '.join(cmd)}\n"
427
+ f"Exit code: {e.returncode}\n"
428
+ f"Stdout: {e.stdout}\n"
429
+ f"Stderr: {e.stderr}"
430
+ )
431
+ raise RuntimeError(error_msg) from e
432
+
433
+ # Give Swarm a brief moment to schedule the tasks.
434
+ time.sleep(1.0)
435
+
436
+ return f"http://localhost:{port}"
437
+
438
+ def stop_container(self) -> None:
439
+ """
440
+ Remove the Swarm service (and keep the Swarm manager running).
441
+ """
442
+ if not self._service_name:
443
+ return
444
+
445
+ import subprocess
446
+
447
+ try:
448
+ subprocess.run(
449
+ ["docker", "service", "rm", self._service_name],
450
+ capture_output=True,
451
+ check=True,
452
+ timeout=10,
453
+ )
454
+ except subprocess.CalledProcessError:
455
+ # Service may already be gone; ignore.
456
+ pass
457
+ finally:
458
+ self._service_name = None
459
+ self._service_id = None
460
+ self._published_port = None
461
+
462
+ def wait_for_ready(self, base_url: str, timeout_s: float = 30.0) -> None:
463
+ """
464
+ Wait for at least one replica to become healthy by polling /health.
465
+
466
+ Note: With Swarm's load balancer, requests round-robin across replicas,
467
+ so this only verifies that at least one replica is responding. Some
468
+ replicas may still be starting when this returns.
469
+ """
470
+ import time
471
+ import requests
472
+
473
+ deadline = time.time() + timeout_s
474
+ health_url = f"{base_url}/health"
475
+
476
+ # Bypass proxy for localhost to avoid proxy issues
477
+ proxies = {"http": None, "https": None}
478
+
479
+ while time.time() < deadline:
480
+ try:
481
+ response = requests.get(health_url, timeout=2.0, proxies=proxies)
482
+ if response.status_code == 200:
483
+ return
484
+ except requests.RequestException:
485
+ pass
486
+
487
+ time.sleep(0.5)
488
+
489
+ raise TimeoutError(
490
+ f"Swarm service at {base_url} did not become ready within {timeout_s}s"
491
+ )
492
+
493
+ def _ensure_docker_available(self) -> None:
494
+ import subprocess
495
+
496
+ try:
497
+ subprocess.run(
498
+ ["docker", "version"],
499
+ check=True,
500
+ capture_output=True,
501
+ timeout=5,
502
+ )
503
+ except (
504
+ subprocess.CalledProcessError,
505
+ FileNotFoundError,
506
+ subprocess.TimeoutExpired,
507
+ ) as exc:
508
+ raise RuntimeError(
509
+ "Docker is not available. Please install Docker Desktop or Docker Engine."
510
+ ) from exc
511
+
512
+ def _ensure_swarm_initialized(self) -> None:
513
+ import subprocess
514
+
515
+ try:
516
+ result = subprocess.run(
517
+ ["docker", "info", "--format", "{{.Swarm.LocalNodeState}}"],
518
+ capture_output=True,
519
+ text=True,
520
+ check=True,
521
+ timeout=5,
522
+ )
523
+ state = result.stdout.strip().lower()
524
+ if state == "active":
525
+ return
526
+ except subprocess.CalledProcessError:
527
+ state = "unknown"
528
+
529
+ if not self._auto_init_swarm:
530
+ raise RuntimeError(
531
+ f"Docker Swarm is not active (state={state}). Enable Swarm manually or pass auto_init_swarm=True."
532
+ )
533
+
534
+ try:
535
+ subprocess.run(
536
+ ["docker", "swarm", "init"],
537
+ check=True,
538
+ capture_output=True,
539
+ timeout=10,
540
+ )
541
+ except subprocess.CalledProcessError as e:
542
+ raise RuntimeError("Failed to initialize Docker Swarm") from e
543
+
544
+ def _ensure_overlay_network(self, network: str) -> None:
545
+ import subprocess
546
+
547
+ inspect = subprocess.run(
548
+ ["docker", "network", "inspect", network],
549
+ capture_output=True,
550
+ text=True,
551
+ check=False,
552
+ )
553
+ if inspect.returncode == 0:
554
+ return
555
+
556
+ try:
557
+ subprocess.run(
558
+ [
559
+ "docker",
560
+ "network",
561
+ "create",
562
+ "--driver",
563
+ "overlay",
564
+ "--attachable",
565
+ network,
566
+ ],
567
+ check=True,
568
+ capture_output=True,
569
+ timeout=10,
570
+ )
571
+ except subprocess.CalledProcessError as e:
572
+ raise RuntimeError(f"Failed to create overlay network '{network}'") from e
573
+
574
+ def _find_available_port(self) -> int:
575
+ import socket
576
+
577
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
578
+ s.bind(("", 0))
579
+ s.listen(1)
580
+ port = s.getsockname()[1]
581
+ return port
582
+
583
+ def _generate_service_name(self, image: str) -> str:
584
+ import time
585
+
586
+ clean_image = image.split("/")[-1].split(":")[0]
587
+ timestamp = int(time.time() * 1000)
588
+ return f"{clean_image}-swarm-{timestamp}"
589
+
590
+
591
+ class KubernetesProvider(ContainerProvider):
592
+ """
593
+ Container provider for Kubernetes clusters.
594
+
595
+ This provider creates pods in a Kubernetes cluster and exposes them
596
+ via services or port-forwarding.
597
+
598
+ Example:
599
+ >>> provider = KubernetesProvider(namespace="envtorch-dev")
600
+ >>> base_url = provider.start_container("echo-env:latest")
601
+ >>> # Pod running in k8s, accessible via service or port-forward
602
+ >>> provider.stop_container()
603
+ """
604
+
605
+ pass
606
+
607
+
608
+ class RuntimeProvider(ABC):
609
+ """
610
+ Abstract base class for runtime providers that are not container providers.
611
+ Providers implement this interface to support different runtime platforms:
612
+ - UVProvider: Runs environments via `uv run`
613
+
614
+ The provider manages a single runtime lifecycle and provides the base URL
615
+ for connecting to it.
616
+
617
+ Example:
618
+ >>> provider = UVProvider(project_path="/path/to/env")
619
+ >>> base_url = provider.start()
620
+ >>> print(base_url) # http://localhost:8000
621
+ >>> provider.stop()
622
+ """
623
+
624
+ @abstractmethod
625
+ def start(
626
+ self,
627
+ port: Optional[int] = None,
628
+ env_vars: Optional[Dict[str, str]] = None,
629
+ **kwargs: Any,
630
+ ) -> str:
631
+ """
632
+ Start a runtime from the specified image.
633
+
634
+ Args:
635
+ image: Runtime image name
636
+ port: Port to expose (if None, provider chooses)
637
+ env_vars: Environment variables for the runtime
638
+ **kwargs: Additional runtime options
639
+ """
640
+
641
+ @abstractmethod
642
+ def stop(self) -> None:
643
+ """
644
+ Stop the runtime.
645
+ """
646
+ pass
647
+
648
+ @abstractmethod
649
+ def wait_for_ready(self, timeout_s: float = 30.0) -> None:
650
+ """
651
+ Wait for the runtime to be ready to accept requests.
652
+ """
653
+ pass
654
+
655
+ def __enter__(self) -> "RuntimeProvider":
656
+ """
657
+ Enter the runtime provider.
658
+ """
659
+ self.start()
660
+ return self
661
+
662
+ def __exit__(self, exc_type, exc, tb) -> None:
663
+ """
664
+ Exit the runtime provider.
665
+ """
666
+ self.stop()
667
+ return False
src/core/containers/runtime/uv_provider.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Providers for launching ASGI applications via ``uv run``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import socket
7
+ import subprocess
8
+ import time
9
+ from typing import Dict, Optional
10
+
11
+ import requests
12
+
13
+ from .providers import RuntimeProvider
14
+
15
+
16
+ def _check_uv_installed() -> None:
17
+ try:
18
+ subprocess.check_output(["uv", "--version"])
19
+ except FileNotFoundError as exc:
20
+ raise RuntimeError(
21
+ "`uv` executable not found. Install uv from https://docs.astral.sh and ensure it is on PATH."
22
+ ) from exc
23
+
24
+
25
+ def _find_free_port() -> int:
26
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
27
+ sock.bind(("", 0))
28
+ sock.listen(1)
29
+ return sock.getsockname()[1]
30
+
31
+
32
+ def _create_uv_command(
33
+ *,
34
+ host: str,
35
+ port: int,
36
+ reload: bool,
37
+ workers: int,
38
+ app: str,
39
+ project_path: str,
40
+ ) -> list[str]:
41
+ command: list[str] = ["uv", "run", "--isolated", "--project", project_path]
42
+
43
+ command.append("--")
44
+ command.extend(
45
+ [
46
+ "uvicorn",
47
+ app,
48
+ "--host",
49
+ host,
50
+ "--port",
51
+ str(port),
52
+ "--workers",
53
+ str(workers),
54
+ ]
55
+ )
56
+
57
+ if reload:
58
+ command.append("--reload")
59
+
60
+ return command
61
+
62
+
63
+ def _poll_health(health_url: str, timeout_s: float) -> None:
64
+ """Poll a health endpoint until it returns HTTP 200 or times out."""
65
+
66
+ deadline = time.time() + timeout_s
67
+ while time.time() < deadline:
68
+ try:
69
+ timeout = max(0.0001, min(deadline - time.time(), 2.0))
70
+ response = requests.get(health_url, timeout=timeout)
71
+ if response.status_code == 200:
72
+ return
73
+ except requests.RequestException:
74
+ continue
75
+
76
+ time.sleep(0.5)
77
+
78
+ raise TimeoutError(f"Server did not become ready within {timeout_s:.1f} seconds")
79
+
80
+
81
+ class UVProvider(RuntimeProvider):
82
+ """
83
+ RuntimeProvider implementation backed by ``uv run``.
84
+
85
+ Args:
86
+ project_path: Local path to a uv project (passed to ``uv run --project``)
87
+ app: ASGI application path for uvicorn (defaults to ``server.app:app``)
88
+ host: Host interface to bind to (defaults to ``0.0.0.0``)
89
+ reload: Whether to enable uvicorn's reload mode
90
+ env_vars: Environment variables to pass through to the spawned process
91
+ context_timeout_s: How long to wait for the environment to become ready
92
+
93
+ Example:
94
+ >>> provider = UVProvider(project_path="/path/to/env")
95
+ >>> base_url = provider.start()
96
+ >>> print(base_url) # http://localhost:8000
97
+ >>> # Use the environment via base_url
98
+ >>> provider.stop()
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ *,
104
+ project_path: str,
105
+ app: str = "server.app:app",
106
+ host: str = "0.0.0.0",
107
+ reload: bool = False,
108
+ env_vars: Optional[Dict[str, str]] = None,
109
+ context_timeout_s: float = 60.0,
110
+ ):
111
+ """Initialize the UVProvider."""
112
+ self.project_path = os.path.abspath(project_path)
113
+ self.app = app
114
+ self.host = host
115
+ self.reload = reload
116
+ self.env_vars = env_vars
117
+ self.context_timeout_s = context_timeout_s
118
+ _check_uv_installed()
119
+ self._process = None
120
+ self._base_url = None
121
+
122
+ def start(
123
+ self,
124
+ port: Optional[int] = None,
125
+ env_vars: Optional[Dict[str, str]] = None,
126
+ workers: int = 1,
127
+ **_: Dict[str, str],
128
+ ) -> str:
129
+ """
130
+ Start the environment via `uv run`.
131
+
132
+ Args:
133
+ port: The port to bind the environment to
134
+ env_vars: Environment variables to pass to the environment
135
+ workers: The number of workers to use
136
+
137
+ Returns:
138
+ The base URL of the environment
139
+
140
+ Raises:
141
+ RuntimeError: If the environment is already running
142
+ """
143
+ if self._process is not None and self._process.poll() is None:
144
+ raise RuntimeError("UVProvider is already running")
145
+
146
+ bind_port = port or _find_free_port()
147
+
148
+ command = _create_uv_command(
149
+ host=self.host,
150
+ port=bind_port,
151
+ reload=self.reload,
152
+ workers=workers,
153
+ app=self.app,
154
+ project_path=self.project_path,
155
+ )
156
+
157
+ env = os.environ.copy()
158
+
159
+ if self.env_vars:
160
+ env.update(self.env_vars)
161
+ if env_vars:
162
+ env.update(env_vars)
163
+
164
+ try:
165
+ self._process = subprocess.Popen(command, env=env)
166
+ except OSError as exc:
167
+ raise RuntimeError(f"Failed to launch `uv run`: {exc}") from exc
168
+
169
+ client_host = "127.0.0.1" if self.host in {"0.0.0.0", "::"} else self.host
170
+ self._base_url = f"http://{client_host}:{bind_port}"
171
+ return self._base_url
172
+
173
+ def wait_for_ready(self, timeout_s: float = 60.0) -> None:
174
+ """
175
+ Wait for the environment to become ready.
176
+
177
+ Args:
178
+ timeout_s: The timeout to wait for the environment to become ready
179
+
180
+ Raises:
181
+ RuntimeError: If the environment is not running
182
+ TimeoutError: If the environment does not become ready within the timeout
183
+ """
184
+ if self._process and self._process.poll() is not None:
185
+ code = self._process.returncode
186
+ raise RuntimeError(f"uv process exited prematurely with code {code}")
187
+
188
+ _poll_health(f"{self._base_url}/health", timeout_s=timeout_s)
189
+
190
+ def stop(self) -> None:
191
+ """
192
+ Stop the environment.
193
+
194
+ Raises:
195
+ RuntimeError: If the environment is not running
196
+ """
197
+ if self._process is None:
198
+ return
199
+
200
+ if self._process.poll() is None:
201
+ self._process.terminate()
202
+ try:
203
+ self._process.wait(timeout=10.0)
204
+ except subprocess.TimeoutExpired:
205
+ self._process.kill()
206
+ self._process.wait(timeout=5.0)
207
+
208
+ self._process = None
209
+ self._base_url = None
210
+
211
+ @property
212
+ def base_url(self) -> str:
213
+ """
214
+ The base URL of the environment.
215
+
216
+ Returns:
217
+ The base URL of the environment
218
+
219
+ Raises:
220
+ RuntimeError: If the environment is not running
221
+ """
222
+ if self._base_url is None:
223
+ raise RuntimeError("UVProvider has not been started")
224
+ return self._base_url
src/core/containers/test_local_docker_provider.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ End-to-end test for LocalDockerProvider.
4
+
5
+ This script tests the complete flow:
6
+ 1. Start a container using LocalDockerProvider
7
+ 2. Wait for it to be ready
8
+ 3. Make HTTP requests to test the environment
9
+ 4. Clean up the container
10
+ """
11
+
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ # Add src to path
16
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
17
+
18
+ import requests
19
+
20
+ from openenv.core.containers.runtime import LocalDockerProvider
21
+
22
+
23
+ # TODO: Remove this test or make it a functional test sicne this will be tested in e2e test for echo env
24
+ def test_local_docker_provider():
25
+ """Test LocalDockerProvider end-to-end."""
26
+ print("=" * 60)
27
+ print("LocalDockerProvider End-to-End Test")
28
+ print("=" * 60)
29
+ print()
30
+
31
+ provider = None
32
+
33
+ try:
34
+ # Step 1: Create provider
35
+ print("Step 1: Creating LocalDockerProvider...")
36
+ provider = LocalDockerProvider()
37
+ print("✓ Provider created\n")
38
+
39
+ # Step 2: Start container
40
+ print("Step 2: Starting echo-env container...")
41
+ base_url = provider.start_container("echo-env:latest")
42
+ print(f"✓ Container started at: {base_url}")
43
+ if provider._container_id:
44
+ print(f" Container ID: {provider._container_id[:12]}...")
45
+ if provider._container_name:
46
+ print(f" Container name: {provider._container_name}\n")
47
+
48
+ # Step 3: Wait for ready
49
+ print("Step 3: Waiting for container to be ready...")
50
+ provider.wait_for_ready(base_url, timeout_s=30.0)
51
+ print("✓ Container is ready!\n")
52
+
53
+ # Step 4: Test health endpoint
54
+ print("Step 4: Testing /health endpoint...")
55
+ response = requests.get(f"{base_url}/health")
56
+ print(f" Status: {response.status_code}")
57
+ print(f" Response: {response.json()}")
58
+ assert response.status_code == 200
59
+ assert response.json()["status"] == "healthy"
60
+ print("✓ Health check passed\n")
61
+
62
+ # Step 5: Test reset endpoint
63
+ print("Step 5: Testing /reset endpoint...")
64
+ response = requests.post(
65
+ f"{base_url}/reset",
66
+ json={},
67
+ headers={"Content-Type": "application/json"},
68
+ )
69
+ print(f" Status: {response.status_code}")
70
+ data = response.json()
71
+ print(f" Message: {data['observation']['echoed_message']}")
72
+ print(f" Reward: {data['reward']}")
73
+ print(f" Done: {data['done']}")
74
+ assert response.status_code == 200
75
+ assert data["observation"]["echoed_message"] == "Echo environment ready!"
76
+ print("✓ Reset test passed\n")
77
+
78
+ # Step 6: Test step endpoint
79
+ print("Step 6: Testing /step endpoint...")
80
+ response = requests.post(
81
+ f"{base_url}/step",
82
+ json={"action": {"message": "Hello from LocalDockerProvider!"}},
83
+ headers={"Content-Type": "application/json"},
84
+ )
85
+ print(f" Status: {response.status_code}")
86
+ data = response.json()
87
+ print(f" Echoed: {data['observation']['echoed_message']}")
88
+ print(f" Length: {data['observation']['message_length']}")
89
+ print(f" Reward: {data['reward']}")
90
+ assert response.status_code == 200
91
+ assert (
92
+ data["observation"]["echoed_message"] == "Hello from LocalDockerProvider!"
93
+ )
94
+ assert data["observation"]["message_length"] == 31
95
+ print("✓ Step test passed\n")
96
+
97
+ # Step 7: Test state endpoint
98
+ print("Step 7: Testing /state endpoint...")
99
+ response = requests.get(f"{base_url}/state")
100
+ print(f" Status: {response.status_code}")
101
+ data = response.json()
102
+ print(f" Episode ID: {data['episode_id']}")
103
+ print(f" Step count: {data['step_count']}")
104
+ assert response.status_code == 200
105
+ assert data["step_count"] == 1 # One step from above
106
+ print("✓ State test passed\n")
107
+
108
+ # Step 8: Multiple steps
109
+ print("Step 8: Testing multiple steps...")
110
+ for i in range(3):
111
+ response = requests.post(
112
+ f"{base_url}/step",
113
+ json={"action": {"message": f"Message {i + 1}"}},
114
+ headers={"Content-Type": "application/json"},
115
+ )
116
+ assert response.status_code == 200
117
+ print(f" Step {i + 1}: ✓")
118
+
119
+ # Check state updated
120
+ response = requests.get(f"{base_url}/state")
121
+ data = response.json()
122
+ assert data["step_count"] == 4 # 1 + 3 more steps
123
+ print(f" Final step count: {data['step_count']}")
124
+ print("✓ Multiple steps test passed\n")
125
+
126
+ print("=" * 60)
127
+ print("✓ All tests passed!")
128
+ print("=" * 60)
129
+ print()
130
+
131
+ return True
132
+
133
+ except Exception as e:
134
+ print(f"\n❌ Test failed: {e}")
135
+ import traceback
136
+
137
+ traceback.print_exc()
138
+ return False
139
+
140
+ finally:
141
+ # Step 9: Cleanup
142
+ if provider is not None:
143
+ print("\nStep 9: Cleaning up container...")
144
+ try:
145
+ provider.stop_container()
146
+ print("✓ Container stopped and removed\n")
147
+ except Exception as e:
148
+ print(f"⚠️ Cleanup warning: {e}\n")
149
+
150
+
151
+ def test_provider_with_custom_port():
152
+ """Test provider with custom port."""
153
+ print("=" * 60)
154
+ print("LocalDockerProvider with Custom Port Test")
155
+ print("=" * 60)
156
+ print()
157
+
158
+ provider = None
159
+
160
+ try:
161
+ provider = LocalDockerProvider()
162
+
163
+ print("Starting container on custom port 8123...")
164
+ base_url = provider.start_container("echo-env:latest", port=8123)
165
+ print(f"✓ Started at: {base_url}")
166
+ assert ":8123" in base_url
167
+
168
+ print("Waiting for ready...")
169
+ provider.wait_for_ready(base_url)
170
+ print("✓ Ready!")
171
+
172
+ print("Testing health...")
173
+ response = requests.get(f"{base_url}/health")
174
+ assert response.status_code == 200
175
+ print("✓ Health check passed")
176
+
177
+ print("\n✓ Custom port test passed!\n")
178
+ return True
179
+
180
+ except Exception as e:
181
+ print(f"\n❌ Test failed: {e}")
182
+ return False
183
+
184
+ finally:
185
+ if provider is not None:
186
+ provider.stop_container()
187
+ print("✓ Cleaned up\n")
188
+
189
+
190
+ def test_provider_with_env_vars():
191
+ """Test provider with environment variables."""
192
+ print("=" * 60)
193
+ print("LocalDockerProvider with Environment Variables Test")
194
+ print("=" * 60)
195
+ print()
196
+
197
+ provider = None
198
+
199
+ try:
200
+ provider = LocalDockerProvider()
201
+
202
+ print("Starting container with environment variables...")
203
+ base_url = provider.start_container(
204
+ "echo-env:latest", env_vars={"DEBUG": "true", "LOG_LEVEL": "info"}
205
+ )
206
+ print(f"✓ Started at: {base_url}")
207
+
208
+ print("Waiting for ready...")
209
+ provider.wait_for_ready(base_url)
210
+ print("✓ Ready!")
211
+
212
+ print("Testing health...")
213
+ response = requests.get(f"{base_url}/health")
214
+ assert response.status_code == 200
215
+ print("✓ Health check passed")
216
+
217
+ print("\n✓ Environment variables test passed!\n")
218
+ return True
219
+
220
+ except Exception as e:
221
+ print(f"\n❌ Test failed: {e}")
222
+ return False
223
+
224
+ finally:
225
+ if provider is not None:
226
+ provider.stop_container()
227
+ print("✓ Cleaned up\n")
228
+
229
+
230
+ if __name__ == "__main__":
231
+ print()
232
+ print("🐳 LocalDockerProvider Test Suite")
233
+ print()
234
+
235
+ results = []
236
+
237
+ # Run basic test
238
+ results.append(("Basic End-to-End", test_local_docker_provider()))
239
+
240
+ # Run custom port test
241
+ results.append(("Custom Port", test_provider_with_custom_port()))
242
+
243
+ # Run environment variables test
244
+ results.append(("Environment Variables", test_provider_with_env_vars()))
245
+
246
+ # Summary
247
+ print("=" * 60)
248
+ print("Test Summary")
249
+ print("=" * 60)
250
+ for name, passed in results:
251
+ status = "✓ PASSED" if passed else "✗ FAILED"
252
+ print(f"{name:25} {status}")
253
+ print("=" * 60)
254
+
255
+ all_passed = all(result for _, result in results)
256
+ if all_passed:
257
+ print("\n🎉 All tests passed!")
258
+ exit(0)
259
+ else:
260
+ print("\n❌ Some tests failed")
261
+ exit(1)
src/core/env_client.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Environment client for persistent sessions.
9
+
10
+ This module provides a WebSocket-based client that maintains a persistent connection
11
+ to an environment server, enabling efficient multi-step interactions without
12
+ the overhead of HTTP request/response cycles.
13
+
14
+ The client is async by default. For synchronous usage, use the `.sync()` method
15
+ to get a `SyncEnvClient` wrapper.
16
+
17
+ Example (async):
18
+ >>> async with GenericEnvClient(base_url="ws://localhost:8000") as env:
19
+ ... result = await env.reset()
20
+ ... result = await env.step({"code": "print('hello')"})
21
+
22
+ Example (sync wrapper):
23
+ >>> env = GenericEnvClient(base_url="ws://localhost:8000").sync()
24
+ >>> with env:
25
+ ... result = env.reset()
26
+ ... result = env.step({"code": "print('hello')"})
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import json
33
+ import os
34
+ from abc import ABC, abstractmethod
35
+ from typing import Any, Dict, Generic, Optional, Type, TYPE_CHECKING, TypeVar
36
+
37
+ from .client_types import StepResult, StateT
38
+ from .containers.runtime import LocalDockerProvider, UVProvider
39
+ from .utils import convert_to_ws_url
40
+
41
+ if TYPE_CHECKING:
42
+ from .containers.runtime import ContainerProvider, RuntimeProvider
43
+ from .sync_client import SyncEnvClient
44
+ from websockets.asyncio.client import ClientConnection
45
+
46
+ from websockets.asyncio.client import connect as ws_connect
47
+
48
+ ActT = TypeVar("ActT")
49
+ ObsT = TypeVar("ObsT")
50
+ EnvClientT = TypeVar("EnvClientT", bound="EnvClient")
51
+
52
+
53
+ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
54
+ """
55
+ Async environment client for persistent sessions.
56
+
57
+ This client maintains a persistent WebSocket connection to an environment
58
+ server, enabling efficient multi-step interactions. Each client instance
59
+ corresponds to a dedicated environment session on the server.
60
+
61
+ The client is async by default. For synchronous usage, use the `.sync()`
62
+ method to get a `SyncEnvClient` wrapper.
63
+
64
+ Features:
65
+ - Lower latency for sequential interactions
66
+ - Session state is maintained server-side
67
+ - Better suited for long-running episodes
68
+ - Async by default for modern Python async/await patterns
69
+
70
+ Example (async):
71
+ >>> from envs.coding_env.client import CodingEnv
72
+ >>>
73
+ >>> # Connect to a server using async context manager
74
+ >>> async with CodingEnv(base_url="ws://localhost:8000") as env:
75
+ ... result = await env.reset(seed=42)
76
+ ... while not result.done:
77
+ ... action = agent.predict(result.observation)
78
+ ... result = await env.step(action)
79
+
80
+ Example (sync wrapper):
81
+ >>> env = CodingEnv(base_url="ws://localhost:8000").sync()
82
+ >>> with env:
83
+ ... result = env.reset(seed=42)
84
+ ... result = env.step(action)
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ base_url: str,
90
+ connect_timeout_s: float = 10.0,
91
+ message_timeout_s: float = 60.0,
92
+ max_message_size_mb: float = 100.0,
93
+ provider: Optional["ContainerProvider | RuntimeProvider"] = None,
94
+ mode: Optional[str] = None,
95
+ ):
96
+ """
97
+ Initialize environment client.
98
+
99
+ Args:
100
+ base_url: Base URL of the environment server (http:// or ws://).
101
+ Will be converted to ws:// if http:// is provided.
102
+ connect_timeout_s: Timeout for establishing WebSocket connection
103
+ message_timeout_s: Timeout for receiving responses to messages
104
+ max_message_size_mb: Maximum WebSocket message size in megabytes.
105
+ Default 100MB to handle large observations (screenshots, DOM, etc.)
106
+ provider: Optional container/runtime provider for lifecycle management.
107
+ Can be a ContainerProvider (Docker) or RuntimeProvider (UV).
108
+ mode: Communication mode: 'simulation' for Gym-style API (default) or
109
+ 'production' for MCP JSON-RPC protocol. Can also be set via the
110
+ OPENENV_CLIENT_MODE environment variable. Constructor parameter
111
+ takes precedence over environment variable. Case-insensitive.
112
+ """
113
+ # Determine mode (constructor > env var > default)
114
+ if mode is None:
115
+ mode = os.environ.get("OPENENV_CLIENT_MODE", "simulation")
116
+
117
+ # Normalize and validate mode
118
+ mode = mode.lower()
119
+ if mode not in ("simulation", "production"):
120
+ raise ValueError(
121
+ f"Invalid mode: '{mode}'. Must be 'simulation' or 'production'. "
122
+ f"Set via constructor parameter or OPENENV_CLIENT_MODE environment variable."
123
+ )
124
+
125
+ # Store mode (use object.__setattr__ to bypass immutability)
126
+ object.__setattr__(self, "_mode", mode)
127
+
128
+ # Convert HTTP URL to WebSocket URL
129
+ ws_url = convert_to_ws_url(base_url)
130
+
131
+ self._ws_url = f"{ws_url}/ws"
132
+ self._connect_timeout = connect_timeout_s
133
+ self._message_timeout = message_timeout_s
134
+ self._max_message_size = int(
135
+ max_message_size_mb * 1024 * 1024
136
+ ) # Convert MB to bytes
137
+ self._provider = provider
138
+ self._ws: Optional[ClientConnection] = None
139
+
140
+ def __setattr__(self, name: str, value: Any) -> None:
141
+ """Prevent modification of _mode after initialization."""
142
+ if name == "_mode" and hasattr(self, "_mode"):
143
+ raise AttributeError("Cannot modify mode after initialization")
144
+ super().__setattr__(name, value)
145
+
146
+ async def connect(self) -> "EnvClient":
147
+ """
148
+ Establish WebSocket connection to the server.
149
+
150
+ Returns:
151
+ self for method chaining
152
+
153
+ Raises:
154
+ ConnectionError: If connection cannot be established
155
+ """
156
+ if self._ws is not None:
157
+ return self
158
+
159
+ # Bypass proxy for localhost connections
160
+ ws_url_lower = self._ws_url.lower()
161
+ is_localhost = "localhost" in ws_url_lower or "127.0.0.1" in ws_url_lower
162
+
163
+ old_no_proxy = os.environ.get("NO_PROXY")
164
+ if is_localhost:
165
+ # Set NO_PROXY to bypass proxy for localhost
166
+ current_no_proxy = old_no_proxy or ""
167
+ if "localhost" not in current_no_proxy.lower():
168
+ os.environ["NO_PROXY"] = (
169
+ f"{current_no_proxy},localhost,127.0.0.1"
170
+ if current_no_proxy
171
+ else "localhost,127.0.0.1"
172
+ )
173
+
174
+ try:
175
+ self._ws = await ws_connect(
176
+ self._ws_url,
177
+ open_timeout=self._connect_timeout,
178
+ max_size=self._max_message_size,
179
+ )
180
+ except Exception as e:
181
+ raise ConnectionError(f"Failed to connect to {self._ws_url}: {e}") from e
182
+ finally:
183
+ # Restore original NO_PROXY value
184
+ if is_localhost:
185
+ if old_no_proxy is None:
186
+ os.environ.pop("NO_PROXY", None)
187
+ else:
188
+ os.environ["NO_PROXY"] = old_no_proxy
189
+
190
+ return self
191
+
192
+ async def disconnect(self) -> None:
193
+ """Close the WebSocket connection."""
194
+ if self._ws is not None:
195
+ try:
196
+ # Send close message
197
+ await self._send({"type": "close"})
198
+ except Exception:
199
+ pass # Best effort
200
+ try:
201
+ await self._ws.close()
202
+ except Exception:
203
+ pass
204
+ self._ws = None
205
+
206
+ async def _ensure_connected(self) -> None:
207
+ """Ensure WebSocket connection is established."""
208
+ if self._ws is None:
209
+ await self.connect()
210
+
211
+ async def _send(self, message: Dict[str, Any]) -> None:
212
+ """Send a message over the WebSocket."""
213
+ await self._ensure_connected()
214
+ assert self._ws is not None
215
+ await self._ws.send(json.dumps(message))
216
+
217
+ async def _receive(self) -> Dict[str, Any]:
218
+ """Receive and parse a message from the WebSocket."""
219
+ assert self._ws is not None
220
+ raw = await asyncio.wait_for(self._ws.recv(), timeout=self._message_timeout)
221
+ return json.loads(raw)
222
+
223
+ async def _send_and_receive(self, message: Dict[str, Any]) -> Dict[str, Any]:
224
+ """Send a message and wait for response."""
225
+ await self._send(message)
226
+ response = await self._receive()
227
+
228
+ # Check for error response
229
+ if response.get("type") == "error":
230
+ error_data = response.get("data", {})
231
+ raise RuntimeError(
232
+ f"Server error: {error_data.get('message', 'Unknown error')} "
233
+ f"(code: {error_data.get('code', 'UNKNOWN')})"
234
+ )
235
+
236
+ return response
237
+
238
+ @classmethod
239
+ async def from_docker_image(
240
+ cls: Type[EnvClientT],
241
+ image: str,
242
+ provider: Optional["ContainerProvider"] = None,
243
+ **kwargs: Any,
244
+ ) -> EnvClientT:
245
+ """
246
+ Create an environment client by spinning up a Docker container.
247
+
248
+ Args:
249
+ image: Docker image name to run (e.g., "coding-env:latest")
250
+ provider: Container provider to use (defaults to LocalDockerProvider)
251
+ **kwargs: Additional arguments to pass to provider.start_container()
252
+
253
+ Returns:
254
+ Connected client instance
255
+ """
256
+ if provider is None:
257
+ provider = LocalDockerProvider()
258
+
259
+ # Start container
260
+ base_url = provider.start_container(image, **kwargs)
261
+
262
+ # Wait for server to be ready
263
+ provider.wait_for_ready(base_url)
264
+
265
+ # Create and connect client
266
+ client = cls(base_url=base_url, provider=provider)
267
+ await client.connect()
268
+
269
+ return client
270
+
271
+ @classmethod
272
+ async def from_env(
273
+ cls: Type[EnvClientT],
274
+ repo_id: str,
275
+ *,
276
+ use_docker: bool = True,
277
+ provider: Optional["ContainerProvider | RuntimeProvider"] = None,
278
+ **provider_kwargs: Any,
279
+ ) -> EnvClientT:
280
+ """
281
+ Create a client from a Hugging Face Space.
282
+
283
+ Args:
284
+ repo_id: Hugging Face space identifier ``{org}/{space}``.
285
+ use_docker: When ``True`` (default) pull from the HF registry and
286
+ launch via :class:`LocalDockerProvider`. When ``False`` run the
287
+ space locally with :class:`UVProvider`.
288
+ provider: Optional provider instance to reuse. Must be a
289
+ :class:`ContainerProvider` when ``use_docker=True`` and a
290
+ :class:`RuntimeProvider` otherwise.
291
+ provider_kwargs: Additional keyword arguments forwarded to
292
+ either the container provider's ``start_container`` (docker)
293
+ or to the ``UVProvider`` constructor/start (uv). When
294
+ ``use_docker=False``, the ``project_path`` argument can be
295
+ used to override the default git URL
296
+ (``git+https://huggingface.co/spaces/{repo_id}``).
297
+
298
+ Returns:
299
+ Connected client instance
300
+
301
+ Examples:
302
+ >>> # Pull and run from HF Docker registry
303
+ >>> env = await MyEnv.from_env("openenv/echo-env")
304
+ >>>
305
+ >>> # Run locally with UV (clones the space)
306
+ >>> env = await MyEnv.from_env("openenv/echo-env", use_docker=False)
307
+ >>>
308
+ >>> # Run from a local checkout
309
+ >>> env = await MyEnv.from_env(
310
+ ... "openenv/echo-env",
311
+ ... use_docker=False,
312
+ ... project_path="/path/to/local/checkout"
313
+ ... )
314
+ """
315
+ # Extract start args that apply to both providers
316
+ start_args = {}
317
+ for key in ("port", "env_vars", "workers"):
318
+ if key in provider_kwargs:
319
+ start_args[key] = provider_kwargs.pop(key)
320
+
321
+ if use_docker:
322
+ # Docker mode: pull from HF registry
323
+ docker_provider = provider or LocalDockerProvider()
324
+ tag = provider_kwargs.pop("tag", "latest")
325
+ image = f"registry.hf.space/{repo_id.replace('/', '-')}:{tag}"
326
+ base_url = docker_provider.start_container(
327
+ image, **start_args, **provider_kwargs
328
+ )
329
+ docker_provider.wait_for_ready(base_url)
330
+
331
+ client = cls(base_url=base_url, provider=docker_provider)
332
+ await client.connect()
333
+ return client
334
+ else:
335
+ # UV mode: clone and run with uv
336
+ if provider is None:
337
+ uv_kwargs = dict(provider_kwargs)
338
+ project_path = uv_kwargs.pop("project_path", None)
339
+ if project_path is None:
340
+ project_path = f"git+https://huggingface.co/spaces/{repo_id}"
341
+
342
+ provider = UVProvider(project_path=project_path, **uv_kwargs)
343
+ else:
344
+ if provider_kwargs:
345
+ raise ValueError(
346
+ "provider_kwargs cannot be used when supplying a provider instance"
347
+ )
348
+
349
+ base_url = provider.start(**start_args)
350
+ provider.wait_for_ready()
351
+
352
+ client = cls(base_url=base_url, provider=provider)
353
+ await client.connect()
354
+ return client
355
+
356
+ @abstractmethod
357
+ def _step_payload(self, action: ActT) -> Dict[str, Any]:
358
+ """Convert an Action object to the JSON data expected by the env server."""
359
+ raise NotImplementedError
360
+
361
+ @abstractmethod
362
+ def _parse_result(self, payload: Dict[str, Any]) -> StepResult[ObsT]:
363
+ """Convert a JSON response from the env server to StepResult[ObsT]."""
364
+ raise NotImplementedError
365
+
366
+ @abstractmethod
367
+ def _parse_state(self, payload: Dict[str, Any]) -> StateT:
368
+ """Convert a JSON response from the state endpoint to a State object."""
369
+ raise NotImplementedError
370
+
371
+ async def reset(self, **kwargs: Any) -> StepResult[ObsT]:
372
+ """
373
+ Reset the environment with optional parameters.
374
+
375
+ Args:
376
+ **kwargs: Optional parameters passed to the environment's reset method.
377
+ Common parameters include:
378
+ - seed: Random seed for reproducibility
379
+ - episode_id: Custom episode identifier
380
+
381
+ Returns:
382
+ StepResult containing initial observation
383
+ """
384
+ message = {
385
+ "type": "reset",
386
+ "data": kwargs,
387
+ }
388
+ response = await self._send_and_receive(message)
389
+ return self._parse_result(response.get("data", {}))
390
+
391
+ async def step(self, action: ActT, **kwargs: Any) -> StepResult[ObsT]:
392
+ """
393
+ Execute an action in the environment.
394
+
395
+ Args:
396
+ action: The action to execute
397
+ **kwargs: Optional parameters (currently ignored)
398
+
399
+ Returns:
400
+ StepResult containing observation, reward, and done status
401
+ """
402
+ message = {
403
+ "type": "step",
404
+ "data": self._step_payload(action),
405
+ }
406
+ response = await self._send_and_receive(message)
407
+ return self._parse_result(response.get("data", {}))
408
+
409
+ async def state(self) -> StateT:
410
+ """
411
+ Get the current environment state from the server.
412
+
413
+ Returns:
414
+ State object with environment state information
415
+ """
416
+ message = {"type": "state"}
417
+ response = await self._send_and_receive(message)
418
+ return self._parse_state(response.get("data", {}))
419
+
420
+ async def close(self) -> None:
421
+ """
422
+ Close the WebSocket connection and clean up resources.
423
+
424
+ If this client was created via from_docker_image() or from_env(),
425
+ this will also stop and remove the associated container/process.
426
+ """
427
+ await self.disconnect()
428
+
429
+ if self._provider is not None:
430
+ # Handle both ContainerProvider and RuntimeProvider
431
+ if hasattr(self._provider, "stop_container"):
432
+ self._provider.stop_container()
433
+ elif hasattr(self._provider, "stop"):
434
+ self._provider.stop()
435
+
436
+ async def __aenter__(self) -> "EnvClient":
437
+ """Enter async context manager, ensuring connection is established."""
438
+ await self.connect()
439
+ return self
440
+
441
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
442
+ """Exit async context manager, closing connection."""
443
+ await self.close()
444
+
445
+ def __enter__(self) -> "EnvClient":
446
+ """Sync context manager entry - raises error suggesting async usage."""
447
+ raise TypeError(
448
+ "EnvClient is async by default. Use 'async with' instead of 'with', "
449
+ "or call .sync() to get a synchronous wrapper:\n"
450
+ " async with client: # async usage\n"
451
+ " with client.sync(): # sync wrapper"
452
+ )
453
+
454
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
455
+ """Sync context manager exit - should not be reached."""
456
+ pass # pragma: no cover
457
+
458
+ def sync(self) -> "SyncEnvClient":
459
+ """
460
+ Return a synchronous wrapper around this async client.
461
+
462
+ Use this method when you need synchronous access to the environment
463
+ without async/await syntax. This is useful for:
464
+ - Integration with synchronous codebases
465
+ - Interactive/REPL usage
466
+ - Stopping async from "infecting" the call stack
467
+
468
+ Returns:
469
+ SyncEnvClient wrapper that provides synchronous methods
470
+
471
+ Example:
472
+ >>> # Create async client and get sync wrapper
473
+ >>> async_client = GenericEnvClient(base_url="http://localhost:8000")
474
+ >>> sync_client = async_client.sync()
475
+ >>>
476
+ >>> # Use synchronous API
477
+ >>> with sync_client:
478
+ ... result = sync_client.reset()
479
+ ... result = sync_client.step({"code": "print('hello')"})
480
+ """
481
+ from .sync_client import SyncEnvClient
482
+
483
+ return SyncEnvClient(self)
src/core/env_server/__init__.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Core environment interfaces and types."""
8
+
9
+ from .base_transforms import CompositeTransform, NullTransform
10
+ from .http_server import HTTPEnvServer, create_app, create_fastapi_app
11
+ from .interfaces import Environment, Message, ModelTokenizer, Transform
12
+ from .route_config import GetEndpointConfig
13
+ from .serialization import (
14
+ deserialize_action,
15
+ deserialize_action_with_preprocessing,
16
+ serialize_observation,
17
+ )
18
+ from .types import (
19
+ Action,
20
+ Observation,
21
+ State,
22
+ SchemaResponse,
23
+ HealthResponse,
24
+ HealthStatus,
25
+ ServerMode,
26
+ WSErrorCode,
27
+ BaseMessage,
28
+ WSIncomingMessage,
29
+ WSResetMessage,
30
+ WSStepMessage,
31
+ WSStateMessage,
32
+ WSCloseMessage,
33
+ WSObservationResponse,
34
+ WSStateResponse,
35
+ WSErrorResponse,
36
+ ConcurrencyConfig,
37
+ ServerCapacityStatus,
38
+ SessionInfo,
39
+ )
40
+ from .exceptions import (
41
+ OpenEnvError,
42
+ ConcurrencyConfigurationError,
43
+ SessionCapacityError,
44
+ SessionNotFoundError,
45
+ SessionCreationError,
46
+ EnvironmentFactoryError,
47
+ )
48
+ from .web_interface import create_web_interface_app, WebInterfaceManager
49
+ from .mcp_types import (
50
+ Tool,
51
+ ToolError,
52
+ ToolErrorType,
53
+ ListToolsAction,
54
+ CallToolAction,
55
+ ListToolsObservation,
56
+ CallToolObservation,
57
+ WSMCPMessage,
58
+ WSMCPResponse,
59
+ RESERVED_TOOL_NAMES,
60
+ # JSON-RPC types
61
+ JsonRpcErrorCode,
62
+ JsonRpcError,
63
+ JsonRpcRequest,
64
+ JsonRpcResponse,
65
+ McpMethod,
66
+ )
67
+ from .mcp_environment import MCPEnvironment
68
+
69
+ __all__ = [
70
+ # Core interfaces
71
+ "Environment",
72
+ "Transform",
73
+ "Message",
74
+ "ModelTokenizer",
75
+ # Types
76
+ "Action",
77
+ "Observation",
78
+ "State",
79
+ "SchemaResponse",
80
+ "HealthResponse",
81
+ # Enums
82
+ "HealthStatus",
83
+ "ServerMode",
84
+ "WSErrorCode",
85
+ # WebSocket message types
86
+ "BaseMessage",
87
+ "WSIncomingMessage",
88
+ "WSResetMessage",
89
+ "WSStepMessage",
90
+ "WSStateMessage",
91
+ "WSCloseMessage",
92
+ "WSObservationResponse",
93
+ "WSStateResponse",
94
+ "WSErrorResponse",
95
+ # Concurrency types
96
+ "ConcurrencyConfig",
97
+ "ServerCapacityStatus",
98
+ "SessionInfo",
99
+ # Exceptions
100
+ "OpenEnvError",
101
+ "ConcurrencyConfigurationError",
102
+ "SessionCapacityError",
103
+ "SessionNotFoundError",
104
+ "SessionCreationError",
105
+ "EnvironmentFactoryError",
106
+ # Base transforms
107
+ "CompositeTransform",
108
+ "NullTransform",
109
+ # HTTP Server
110
+ "HTTPEnvServer",
111
+ "create_app",
112
+ "create_fastapi_app",
113
+ # Web Interface
114
+ "create_web_interface_app",
115
+ "WebInterfaceManager",
116
+ # Serialization utilities
117
+ "deserialize_action",
118
+ "deserialize_action_with_preprocessing",
119
+ "serialize_observation",
120
+ # Route configuration
121
+ "GetEndpointConfig",
122
+ # MCP types
123
+ "Tool",
124
+ "ToolError",
125
+ "ToolErrorType",
126
+ "ListToolsAction",
127
+ "CallToolAction",
128
+ "ListToolsObservation",
129
+ "CallToolObservation",
130
+ "WSMCPMessage",
131
+ "WSMCPResponse",
132
+ "RESERVED_TOOL_NAMES",
133
+ "MCPEnvironment",
134
+ # JSON-RPC types
135
+ "JsonRpcErrorCode",
136
+ "JsonRpcError",
137
+ "JsonRpcRequest",
138
+ "JsonRpcResponse",
139
+ "McpMethod",
140
+ ]
src/core/env_server/base_transforms.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Base transform implementations for composing environment-specific transforms."""
8
+
9
+ from .interfaces import Transform
10
+ from .types import Observation
11
+
12
+
13
+ class CompositeTransform(Transform):
14
+ """Combines multiple transforms into a single transform."""
15
+
16
+ def __init__(self, transforms: list[Transform]):
17
+ self.transforms = transforms
18
+
19
+ def __call__(self, observation: Observation) -> Observation:
20
+ for transform in self.transforms:
21
+ observation = transform(observation)
22
+ return observation
23
+
24
+
25
+ class NullTransform(Transform):
26
+ """Default transform that passes through unchanged."""
27
+
28
+ def __call__(self, observation: Observation) -> Observation:
29
+ return observation
src/core/env_server/exceptions.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Custom exceptions for environment server operations."""
8
+
9
+ from typing import Optional
10
+
11
+
12
+ class OpenEnvError(Exception):
13
+ """Base exception for all OpenEnv errors."""
14
+
15
+ pass
16
+
17
+
18
+ class ConcurrencyConfigurationError(OpenEnvError):
19
+ """
20
+ Raised when an environment is misconfigured for concurrent sessions.
21
+
22
+ This error is raised during server startup when max_concurrent_envs > 1
23
+ is specified for an environment that is not marked as SUPPORTS_CONCURRENT_SESSIONS.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ environment_name: str,
29
+ max_concurrent_envs: int,
30
+ message: Optional[str] = None,
31
+ ):
32
+ self.environment_name = environment_name
33
+ self.max_concurrent_envs = max_concurrent_envs
34
+
35
+ if message is None:
36
+ message = (
37
+ f"Environment '{environment_name}' is not marked as SUPPORTS_CONCURRENT_SESSIONS. "
38
+ f"Cannot run with max_concurrent_envs={max_concurrent_envs}. "
39
+ f"Either set max_concurrent_envs=1 or ensure the environment "
40
+ f"properly isolates session state and set SUPPORTS_CONCURRENT_SESSIONS=True."
41
+ )
42
+
43
+ super().__init__(message)
44
+
45
+
46
+ class SessionCapacityError(OpenEnvError):
47
+ """
48
+ Raised when the server cannot accept new sessions due to capacity limits.
49
+
50
+ This error is raised when a new WebSocket connection is attempted but
51
+ the server has already reached max_concurrent_envs active sessions.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ active_sessions: int,
57
+ max_sessions: int,
58
+ message: Optional[str] = None,
59
+ ):
60
+ self.active_sessions = active_sessions
61
+ self.max_sessions = max_sessions
62
+
63
+ if message is None:
64
+ message = (
65
+ f"Server at capacity: {active_sessions}/{max_sessions} sessions active. "
66
+ f"Cannot accept new connections."
67
+ )
68
+
69
+ super().__init__(message)
70
+
71
+
72
+ class SessionNotFoundError(OpenEnvError):
73
+ """Raised when attempting to access a session that does not exist."""
74
+
75
+ def __init__(self, session_id: str, message: Optional[str] = None):
76
+ self.session_id = session_id
77
+
78
+ if message is None:
79
+ message = f"Session '{session_id}' not found."
80
+
81
+ super().__init__(message)
82
+
83
+
84
+ class SessionCreationError(OpenEnvError):
85
+ """Raised when a session cannot be created."""
86
+
87
+ def __init__(self, reason: str, message: Optional[str] = None):
88
+ self.reason = reason
89
+
90
+ if message is None:
91
+ message = f"Failed to create session: {reason}"
92
+
93
+ super().__init__(message)
94
+
95
+
96
+ class EnvironmentFactoryError(OpenEnvError):
97
+ """Raised when the environment factory fails to create an instance."""
98
+
99
+ def __init__(self, factory_name: str, message: Optional[str] = None):
100
+ self.factory_name = factory_name
101
+
102
+ if message is None:
103
+ message = f"Environment factory '{factory_name}' failed to create instance."
104
+
105
+ super().__init__(message)
src/core/env_server/gradio_theme.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Unified terminal-style theme for OpenEnv Gradio UI (light/dark)."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import gradio as gr
12
+
13
+ _MONO_FONTS = (
14
+ "JetBrains Mono",
15
+ "Fira Code",
16
+ "Cascadia Code",
17
+ "Consolas",
18
+ "ui-monospace",
19
+ "monospace",
20
+ )
21
+
22
+ _CORE_FONT = (
23
+ "Lato",
24
+ "Inter",
25
+ "Arial",
26
+ "Helvetica",
27
+ "sans-serif",
28
+ )
29
+
30
+ _ZERO_RADIUS = gr.themes.Size(
31
+ xxs="0px",
32
+ xs="0px",
33
+ sm="0px",
34
+ md="0px",
35
+ lg="0px",
36
+ xl="0px",
37
+ xxl="0px",
38
+ )
39
+
40
+ _GREEN_HUE = gr.themes.Color(
41
+ c50="#e6f4ea",
42
+ c100="#ceead6",
43
+ c200="#a8dab5",
44
+ c300="#6fcc8b",
45
+ c400="#3fb950",
46
+ c500="#238636",
47
+ c600="#1a7f37",
48
+ c700="#116329",
49
+ c800="#0a4620",
50
+ c900="#033a16",
51
+ c950="#04200d",
52
+ )
53
+
54
+ _NEUTRAL_HUE = gr.themes.Color(
55
+ c50="#f6f8fa",
56
+ c100="#eaeef2",
57
+ c200="#d0d7de",
58
+ c300="#afb8c1",
59
+ c400="#8c959f",
60
+ c500="#6e7781",
61
+ c600="#57606a",
62
+ c700="#424a53",
63
+ c800="#32383f",
64
+ c900="#24292f",
65
+ c950="#1b1f24",
66
+ )
67
+
68
+ OPENENV_GRADIO_THEME = gr.themes.Base(
69
+ primary_hue=_GREEN_HUE,
70
+ secondary_hue=_NEUTRAL_HUE,
71
+ neutral_hue=_NEUTRAL_HUE,
72
+ font=_CORE_FONT,
73
+ font_mono=_MONO_FONTS,
74
+ radius_size=_ZERO_RADIUS,
75
+ ).set(
76
+ body_background_fill="#ffffff",
77
+ background_fill_primary="#ffffff",
78
+ background_fill_secondary="#f6f8fa",
79
+ block_background_fill="#ffffff",
80
+ block_border_color="#ffffff",
81
+ block_label_text_color="#57606a",
82
+ block_title_text_color="#24292f",
83
+ border_color_primary="#d0d7de",
84
+ input_background_fill="#ffffff",
85
+ input_border_color="#d0d7de",
86
+ button_primary_background_fill="#1a7f37",
87
+ button_primary_background_fill_hover="#116329",
88
+ button_primary_text_color="#ffffff",
89
+ button_secondary_background_fill="#f6f8fa",
90
+ button_secondary_background_fill_hover="#eaeef2",
91
+ button_secondary_text_color="#24292f",
92
+ button_secondary_border_color="#d0d7de",
93
+ body_background_fill_dark="#0d1117",
94
+ background_fill_primary_dark="#0d1117",
95
+ background_fill_secondary_dark="#0d1117",
96
+ block_background_fill_dark="#0d1117",
97
+ block_border_color_dark="#0d1117",
98
+ block_label_text_color_dark="#8b949e",
99
+ block_title_text_color_dark="#c9d1d9",
100
+ border_color_primary_dark="#30363d",
101
+ input_background_fill_dark="#0d1117",
102
+ input_border_color_dark="#30363d",
103
+ button_primary_background_fill_dark="#30363d",
104
+ button_primary_background_fill_hover_dark="#484f58",
105
+ button_primary_text_color_dark="#c9d1d9",
106
+ button_secondary_background_fill_dark="#21262d",
107
+ button_secondary_background_fill_hover_dark="#30363d",
108
+ button_secondary_text_color_dark="#c9d1d9",
109
+ button_secondary_border_color_dark="#30363d",
110
+ )
111
+
112
+ OPENENV_GRADIO_CSS = """
113
+ * { border-radius: 0 !important; }
114
+ .col-left { padding: 16px !important; }
115
+ .col-right { padding: 16px !important; }
116
+ .prose, .markdown-text, .md,
117
+ .prose > *, .markdown-text > * {
118
+ background: transparent !important;
119
+ border: none !important;
120
+ box-shadow: none !important;
121
+ }
122
+ .dark .col-left {
123
+ border-left-color: rgba(139, 148, 158, 0.4) !important;
124
+ }
125
+ .dark .col-right {
126
+ border-left-color: rgba(201, 209, 217, 0.3) !important;
127
+ }
128
+ """
src/core/env_server/gradio_ui.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Gradio-based web UI for OpenEnv environments.
9
+
10
+ Replaces the legacy HTML/JavaScript interface when ENABLE_WEB_INTERFACE is set.
11
+ Mount at /web via gr.mount_gradio_app() from create_web_interface_app().
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from typing import Any, Dict, List, Optional
19
+
20
+ import gradio as gr
21
+
22
+ from .types import EnvironmentMetadata
23
+
24
+
25
+ def _escape_md(text: str) -> str:
26
+ """Escape Markdown special characters in user-controlled content."""
27
+ return re.sub(r"([\\`*_\{\}\[\]()#+\-.!|~>])", r"\\\1", str(text))
28
+
29
+
30
+ def _format_observation(data: Dict[str, Any]) -> str:
31
+ """Format reset/step response for Markdown display."""
32
+ lines: List[str] = []
33
+ obs = data.get("observation", {})
34
+ if isinstance(obs, dict):
35
+ if obs.get("prompt"):
36
+ lines.append(f"**Prompt:**\n\n{_escape_md(obs['prompt'])}\n")
37
+ messages = obs.get("messages", [])
38
+ if messages:
39
+ lines.append("**Messages:**\n")
40
+ for msg in messages:
41
+ sender = _escape_md(str(msg.get("sender_id", "?")))
42
+ content = _escape_md(str(msg.get("content", "")))
43
+ cat = _escape_md(str(msg.get("category", "")))
44
+ lines.append(f"- `[{cat}]` Player {sender}: {content}")
45
+ lines.append("")
46
+ reward = data.get("reward")
47
+ done = data.get("done")
48
+ if reward is not None:
49
+ lines.append(f"**Reward:** `{reward}`")
50
+ if done is not None:
51
+ lines.append(f"**Done:** `{done}`")
52
+ return "\n".join(lines) if lines else "*No observation data*"
53
+
54
+
55
+ def _readme_section(metadata: Optional[EnvironmentMetadata]) -> str:
56
+ """README content for the left panel."""
57
+ if not metadata or not metadata.readme_content:
58
+ return "*No README available.*"
59
+ return metadata.readme_content
60
+
61
+
62
+ def get_gradio_display_title(
63
+ metadata: Optional[EnvironmentMetadata],
64
+ fallback: str = "OpenEnv Environment",
65
+ ) -> str:
66
+ """Return the title used for the Gradio app (browser tab and Blocks)."""
67
+ name = metadata.name if metadata else fallback
68
+ return f"OpenEnv Agentic Environment: {name}"
69
+
70
+
71
+ def build_gradio_app(
72
+ web_manager: Any,
73
+ action_fields: List[Dict[str, Any]],
74
+ metadata: Optional[EnvironmentMetadata],
75
+ is_chat_env: bool,
76
+ title: str = "OpenEnv Environment",
77
+ quick_start_md: Optional[str] = None,
78
+ ) -> gr.Blocks:
79
+ """
80
+ Build a Gradio Blocks app for the OpenEnv web interface.
81
+
82
+ Args:
83
+ web_manager: WebInterfaceManager (reset/step_environment, get_state).
84
+ action_fields: Field dicts from _extract_action_fields(action_cls).
85
+ metadata: Environment metadata for README/name.
86
+ is_chat_env: If True, single message textbox; else form from action_fields.
87
+ title: App title (overridden by metadata.name when present; see get_gradio_display_title).
88
+ quick_start_md: Optional Quick Start markdown (class names already replaced).
89
+
90
+ Returns:
91
+ gr.Blocks to mount with gr.mount_gradio_app(app, blocks, path="/web").
92
+ """
93
+ readme_content = _readme_section(metadata)
94
+ display_title = get_gradio_display_title(metadata, fallback=title)
95
+
96
+ async def reset_env():
97
+ try:
98
+ data = await web_manager.reset_environment()
99
+ obs_md = _format_observation(data)
100
+ return (
101
+ obs_md,
102
+ json.dumps(data, indent=2),
103
+ "Environment reset successfully.",
104
+ )
105
+ except Exception as e:
106
+ return ("", "", f"Error: {e}")
107
+
108
+ def _step_with_action(action_data: Dict[str, Any]):
109
+ async def _run():
110
+ try:
111
+ data = await web_manager.step_environment(action_data)
112
+ obs_md = _format_observation(data)
113
+ return (
114
+ obs_md,
115
+ json.dumps(data, indent=2),
116
+ "Step complete.",
117
+ )
118
+ except Exception as e:
119
+ return ("", "", f"Error: {e}")
120
+
121
+ return _run
122
+
123
+ async def step_chat(message: str):
124
+ if not (message or str(message).strip()):
125
+ return ("", "", "Please enter an action message.")
126
+ action = {"message": str(message).strip()}
127
+ return await _step_with_action(action)()
128
+
129
+ def get_state_sync():
130
+ try:
131
+ data = web_manager.get_state()
132
+ return json.dumps(data, indent=2)
133
+ except Exception as e:
134
+ return f"Error: {e}"
135
+
136
+ with gr.Blocks(title=display_title) as demo:
137
+ with gr.Row():
138
+ with gr.Column(scale=1, elem_classes="col-left"):
139
+ if quick_start_md:
140
+ with gr.Accordion("Quick Start", open=True):
141
+ gr.Markdown(quick_start_md)
142
+ with gr.Accordion("README", open=False):
143
+ gr.Markdown(readme_content)
144
+
145
+ with gr.Column(scale=2, elem_classes="col-right"):
146
+ obs_display = gr.Markdown(
147
+ value=("# Playground\n\nClick **Reset** to start a new episode."),
148
+ )
149
+ with gr.Group():
150
+ if is_chat_env:
151
+ action_input = gr.Textbox(
152
+ label="Action message",
153
+ placeholder="e.g. Enter your message...",
154
+ )
155
+ step_inputs = [action_input]
156
+ step_fn = step_chat
157
+ else:
158
+ step_inputs = []
159
+ for field in action_fields:
160
+ name = field["name"]
161
+ field_type = field.get("type", "text")
162
+ label = name.replace("_", " ").title()
163
+ placeholder = field.get("placeholder", "")
164
+ if field_type == "checkbox":
165
+ inp = gr.Checkbox(label=label)
166
+ elif field_type == "number":
167
+ inp = gr.Number(label=label)
168
+ elif field_type == "select":
169
+ choices = field.get("choices") or []
170
+ inp = gr.Dropdown(
171
+ choices=choices,
172
+ label=label,
173
+ allow_custom_value=False,
174
+ )
175
+ elif field_type in ("textarea", "tensor"):
176
+ inp = gr.Textbox(
177
+ label=label,
178
+ placeholder=placeholder,
179
+ lines=3,
180
+ )
181
+ else:
182
+ inp = gr.Textbox(
183
+ label=label,
184
+ placeholder=placeholder,
185
+ )
186
+ step_inputs.append(inp)
187
+
188
+ async def step_form(*values):
189
+ if not action_fields:
190
+ return await _step_with_action({})()
191
+ action_data = {}
192
+ for i, field in enumerate(action_fields):
193
+ if i >= len(values):
194
+ break
195
+ name = field["name"]
196
+ val = values[i]
197
+ if field.get("type") == "checkbox":
198
+ action_data[name] = bool(val)
199
+ elif val is not None and val != "":
200
+ action_data[name] = val
201
+ return await _step_with_action(action_data)()
202
+
203
+ step_fn = step_form
204
+
205
+ with gr.Row():
206
+ step_btn = gr.Button("Step", variant="primary")
207
+ reset_btn = gr.Button("Reset", variant="secondary")
208
+ state_btn = gr.Button("Get state", variant="secondary")
209
+ with gr.Row():
210
+ status = gr.Textbox(
211
+ label="Status",
212
+ interactive=False,
213
+ )
214
+ raw_json = gr.Code(
215
+ label="Raw JSON response",
216
+ language="json",
217
+ interactive=False,
218
+ )
219
+
220
+ reset_btn.click(
221
+ fn=reset_env,
222
+ outputs=[obs_display, raw_json, status],
223
+ )
224
+ step_btn.click(
225
+ fn=step_fn,
226
+ inputs=step_inputs,
227
+ outputs=[obs_display, raw_json, status],
228
+ )
229
+ if is_chat_env:
230
+ action_input.submit(
231
+ fn=step_fn,
232
+ inputs=step_inputs,
233
+ outputs=[obs_display, raw_json, status],
234
+ )
235
+ state_btn.click(
236
+ fn=get_state_sync,
237
+ outputs=[raw_json],
238
+ )
239
+
240
+ return demo
src/core/env_server/http_server.py ADDED
@@ -0,0 +1,1396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ HTTP server wrapper for Environment instances.
9
+
10
+ This module provides utilities to wrap any Environment subclass and expose it
11
+ over HTTP and WebSocket endpoints that EnvClient can consume.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import inspect
18
+ import json
19
+ import os
20
+ import time
21
+ import uuid
22
+ from concurrent.futures import ThreadPoolExecutor
23
+ from typing import Any, Callable, Dict, Optional, Type
24
+
25
+ from fastapi import (
26
+ Body,
27
+ FastAPI,
28
+ HTTPException,
29
+ Request,
30
+ WebSocket,
31
+ WebSocketDisconnect,
32
+ status,
33
+ )
34
+ from pydantic import ValidationError
35
+
36
+ from .interfaces import Environment
37
+ from .route_config import (
38
+ GetEndpointConfig,
39
+ register_get_endpoints,
40
+ )
41
+ from .serialization import deserialize_action, serialize_observation
42
+ from .types import (
43
+ Action,
44
+ Observation,
45
+ ResetRequest,
46
+ ResetResponse,
47
+ State,
48
+ StepRequest,
49
+ StepResponse,
50
+ EnvironmentMetadata,
51
+ SchemaResponse,
52
+ HealthResponse,
53
+ HealthStatus,
54
+ ServerMode,
55
+ WSErrorCode,
56
+ WSResetMessage,
57
+ WSStepMessage,
58
+ WSStateMessage,
59
+ WSCloseMessage,
60
+ WSObservationResponse,
61
+ WSStateResponse,
62
+ WSErrorResponse,
63
+ ConcurrencyConfig,
64
+ ServerCapacityStatus,
65
+ SessionInfo,
66
+ )
67
+ from .mcp_types import (
68
+ JsonRpcErrorCode,
69
+ JsonRpcRequest,
70
+ JsonRpcResponse,
71
+ McpMethod,
72
+ WSMCPMessage,
73
+ WSMCPResponse,
74
+ )
75
+
76
+
77
+ def _make_json_serializable(obj: Any) -> Any:
78
+ """
79
+ Convert an object to a JSON-serializable form.
80
+
81
+ Handles Pydantic models, dataclasses, and other common types.
82
+
83
+ Args:
84
+ obj: The object to convert
85
+
86
+ Returns:
87
+ A JSON-serializable representation of the object
88
+ """
89
+ if obj is None:
90
+ return None
91
+ if isinstance(obj, (str, int, float, bool)):
92
+ return obj
93
+ if isinstance(obj, (list, tuple)):
94
+ return [_make_json_serializable(item) for item in obj]
95
+ if isinstance(obj, dict):
96
+ return {k: _make_json_serializable(v) for k, v in obj.items()}
97
+ if hasattr(obj, "model_dump"):
98
+ # Pydantic model
99
+ return obj.model_dump()
100
+ if hasattr(obj, "__dict__"):
101
+ # Object with __dict__
102
+ return {k: _make_json_serializable(v) for k, v in obj.__dict__.items()}
103
+ # Fallback to string representation
104
+ return str(obj)
105
+
106
+
107
+ from .exceptions import (
108
+ ConcurrencyConfigurationError,
109
+ SessionCapacityError,
110
+ EnvironmentFactoryError,
111
+ )
112
+
113
+
114
+ class HTTPEnvServer:
115
+ """
116
+ HTTP server wrapper for Environment instances.
117
+
118
+ This class wraps an Environment and exposes its reset(), step(), and state
119
+ methods as HTTP and WebSocket endpoints compatible with EnvClient.
120
+
121
+ The server expects:
122
+ - Action deserialization: Converts JSON dict to Action subclass
123
+ - Observation serialization: Converts Observation subclass to JSON dict
124
+
125
+ Example:
126
+ >>> from core.env_server import HTTPEnvServer
127
+ >>> from envs.coding_env.server import CodeExecutionEnvironment
128
+ >>> from envs.coding_env.models import CodeAction, CodeObservation
129
+ >>>
130
+ >>> # Pass environment class (factory pattern)
131
+ >>> server = HTTPEnvServer(
132
+ ... env=CodeExecutionEnvironment,
133
+ ... action_cls=CodeAction,
134
+ ... observation_cls=CodeObservation,
135
+ ... max_concurrent_envs=4,
136
+ ... )
137
+ >>>
138
+ >>> # Register routes with FastAPI
139
+ >>> from fastapi import FastAPI
140
+ >>> app = FastAPI()
141
+ >>> server.register_routes(app)
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ env: Callable[[], Environment],
147
+ action_cls: Type[Action],
148
+ observation_cls: Type[Observation],
149
+ max_concurrent_envs: Optional[int] = None,
150
+ concurrency_config: Optional[ConcurrencyConfig] = None,
151
+ ):
152
+ """
153
+ Initialize HTTP server wrapper.
154
+
155
+ Args:
156
+ env: Environment factory (callable) that creates new instances.
157
+ Will be called to create a new environment for each WebSocket session.
158
+ action_cls: The Action subclass this environment expects
159
+ observation_cls: The Observation subclass this environment returns
160
+ max_concurrent_envs: Maximum number of concurrent WebSocket sessions.
161
+ Mutually exclusive with concurrency_config.
162
+ concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings.
163
+ Mutually exclusive with max_concurrent_envs.
164
+
165
+ Raises:
166
+ ValueError: If both max_concurrent_envs and concurrency_config are provided.
167
+ ConcurrencyConfigurationError: If max_concurrent_envs > 1 for an
168
+ environment that is not marked as SUPPORTS_CONCURRENT_SESSIONS.
169
+ """
170
+ # Validate that env is callable
171
+ if not callable(env):
172
+ raise TypeError(
173
+ f"env must be a callable (class or factory function), got {type(env)}. "
174
+ f"Pass the environment class (e.g., MyEnvironment) not an instance (e.g., MyEnvironment())."
175
+ )
176
+
177
+ self._env_factory: Callable[[], Environment] = env
178
+
179
+ # Handle concurrency configuration
180
+ if max_concurrent_envs is not None and concurrency_config is not None:
181
+ raise ValueError(
182
+ "Cannot specify both 'max_concurrent_envs' and 'concurrency_config'. "
183
+ "Please use only one method to configure concurrency."
184
+ )
185
+
186
+ if concurrency_config is not None:
187
+ self._concurrency_config = concurrency_config
188
+ elif max_concurrent_envs is not None:
189
+ self._concurrency_config = ConcurrencyConfig(
190
+ max_concurrent_envs=max_concurrent_envs,
191
+ session_timeout=None,
192
+ )
193
+ else:
194
+ # Default configuration
195
+ self._concurrency_config = ConcurrencyConfig(
196
+ max_concurrent_envs=1,
197
+ session_timeout=None,
198
+ )
199
+
200
+ self._max_concurrent_envs = self._concurrency_config.max_concurrent_envs
201
+
202
+ # Validate concurrency configuration
203
+ self._validate_concurrency_safety()
204
+
205
+ self.action_cls = action_cls
206
+ self.observation_cls = observation_cls
207
+
208
+ # Session management for WebSocket connections
209
+ self._sessions: Dict[str, Environment] = {}
210
+ self._session_executors: Dict[str, ThreadPoolExecutor] = {}
211
+ self._session_info: Dict[str, SessionInfo] = {}
212
+ self._session_lock = asyncio.Lock()
213
+
214
+ # Create thread pool for running sync code in async context
215
+ # This is needed for environments using sync libraries (e.g., Playwright)
216
+ self._executor = ThreadPoolExecutor(max_workers=32)
217
+
218
+ def _validate_concurrency_safety(self) -> None:
219
+ """
220
+ Validate that the environment supports the configured concurrency level.
221
+
222
+ Raises:
223
+ ConcurrencyConfigurationError: If max_concurrent_envs > 1 for an
224
+ environment that is not marked as SUPPORTS_CONCURRENT_SESSIONS.
225
+ """
226
+ if self._max_concurrent_envs <= 1:
227
+ return
228
+
229
+ if inspect.isclass(self._env_factory):
230
+ env_cls = self._env_factory
231
+ else:
232
+ _temp_env = self._env_factory()
233
+ env_cls = type(_temp_env)
234
+ _temp_env.close()
235
+ del _temp_env
236
+
237
+ if not getattr(env_cls, "SUPPORTS_CONCURRENT_SESSIONS", False):
238
+ raise ConcurrencyConfigurationError(
239
+ environment_name=env_cls.__name__,
240
+ max_concurrent_envs=self._max_concurrent_envs,
241
+ )
242
+
243
+ def get_capacity_status(self) -> ServerCapacityStatus:
244
+ """
245
+ Get the current capacity status of the server.
246
+
247
+ Returns:
248
+ ServerCapacityStatus with current session counts and availability.
249
+ """
250
+ return ServerCapacityStatus.from_counts(
251
+ active=len(self._sessions),
252
+ max_sessions=self._max_concurrent_envs,
253
+ )
254
+
255
+ async def _run_sync_in_thread_pool(
256
+ self, func: Callable[..., Observation], *args, **kwargs
257
+ ) -> Observation:
258
+ """Run a synchronous function in the thread pool executor."""
259
+ loop = asyncio.get_event_loop()
260
+ return await loop.run_in_executor(self._executor, lambda: func(*args, **kwargs))
261
+
262
+ def _get_valid_kwargs(
263
+ self,
264
+ sig: inspect.Signature,
265
+ kwargs: Dict[str, Any],
266
+ skip_params: Optional[set[str]] = None,
267
+ ) -> Dict[str, Any]:
268
+ """Filter kwargs to only include parameters accepted by the function signature."""
269
+ if skip_params is None:
270
+ skip_params = set()
271
+
272
+ valid_kwargs = {}
273
+
274
+ has_kwargs = any(
275
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
276
+ )
277
+
278
+ for k, v in kwargs.items():
279
+ if k in sig.parameters or has_kwargs:
280
+ if k not in skip_params:
281
+ valid_kwargs[k] = v
282
+
283
+ return valid_kwargs
284
+
285
+ async def _create_session(self) -> tuple[str, Environment]:
286
+ """
287
+ Create a new WebSocket session with its own environment instance.
288
+
289
+ Returns:
290
+ Tuple of (session_id, environment)
291
+
292
+ Raises:
293
+ SessionCapacityError: If max concurrent sessions reached
294
+ EnvironmentFactoryError: If the factory fails to create an environment
295
+ """
296
+ async with self._session_lock:
297
+ if len(self._sessions) >= self._max_concurrent_envs:
298
+ raise SessionCapacityError(
299
+ active_sessions=len(self._sessions),
300
+ max_sessions=self._max_concurrent_envs,
301
+ )
302
+
303
+ session_id = str(uuid.uuid4())
304
+ current_time = time.time()
305
+
306
+ # Create executor and reserve slot so capacity is not exceeded while
307
+ # we create the env outside the lock (avoids blocking other sessions)
308
+ executor = ThreadPoolExecutor(max_workers=1)
309
+ self._session_executors[session_id] = executor
310
+ self._sessions[session_id] = None # placeholder until env is ready
311
+
312
+ try:
313
+ # Create environment in the executor thread (outside lock)
314
+ loop = asyncio.get_event_loop()
315
+ env = await loop.run_in_executor(executor, self._env_factory)
316
+ except Exception as e:
317
+ async with self._session_lock:
318
+ executor.shutdown(wait=False)
319
+ self._session_executors.pop(session_id, None)
320
+ self._sessions.pop(session_id, None)
321
+ factory_name = getattr(
322
+ self._env_factory, "__name__", str(self._env_factory)
323
+ )
324
+ raise EnvironmentFactoryError(factory_name) from e
325
+
326
+ async with self._session_lock:
327
+ self._sessions[session_id] = env
328
+ self._session_info[session_id] = SessionInfo(
329
+ session_id=session_id,
330
+ created_at=current_time,
331
+ last_activity_at=current_time,
332
+ step_count=0,
333
+ environment_type=type(env).__name__,
334
+ )
335
+
336
+ return session_id, env
337
+
338
+ async def _destroy_session(self, session_id: str) -> None:
339
+ """
340
+ Destroy a WebSocket session and cleanup resources.
341
+
342
+ Args:
343
+ session_id: The session ID to destroy
344
+ """
345
+ async with self._session_lock:
346
+ env = self._sessions.pop(session_id, None)
347
+ executor = self._session_executors.pop(session_id, None)
348
+ self._session_info.pop(session_id, None)
349
+
350
+ # Run close() in the same executor where the env was created
351
+ # This is required for thread-sensitive libraries like Playwright/greenlet
352
+ if env is not None:
353
+ if executor is not None:
354
+ try:
355
+ loop = asyncio.get_event_loop()
356
+ await loop.run_in_executor(executor, env.close)
357
+ except Exception:
358
+ # If executor close fails, try direct close as fallback
359
+ try:
360
+ env.close()
361
+ except Exception:
362
+ pass # Best effort cleanup
363
+ else:
364
+ try:
365
+ env.close()
366
+ except Exception:
367
+ pass # Best effort cleanup
368
+
369
+ # Shutdown executor after close is done
370
+ if executor is not None:
371
+ executor.shutdown(wait=False)
372
+
373
+ def _update_session_activity(
374
+ self, session_id: str, increment_step: bool = False
375
+ ) -> None:
376
+ """
377
+ Update session activity timestamp and optionally increment step count.
378
+
379
+ Args:
380
+ session_id: The session ID to update
381
+ increment_step: If True, increment the step count
382
+ """
383
+ if session_id in self._session_info:
384
+ self._session_info[session_id].last_activity_at = time.time()
385
+ if increment_step:
386
+ self._session_info[session_id].step_count += 1
387
+
388
+ def get_session_info(self, session_id: str) -> Optional[SessionInfo]:
389
+ """
390
+ Get information about a specific session.
391
+
392
+ Args:
393
+ session_id: The session ID to query
394
+
395
+ Returns:
396
+ SessionInfo if the session exists, None otherwise
397
+ """
398
+ return self._session_info.get(session_id)
399
+
400
+ async def _run_in_session_executor(
401
+ self, session_id: str, func: Callable[..., Observation], *args, **kwargs
402
+ ) -> Observation:
403
+ """Run a synchronous function in the session's thread pool executor."""
404
+ executor = self._session_executors.get(session_id, self._executor)
405
+ loop = asyncio.get_event_loop()
406
+ return await loop.run_in_executor(executor, lambda: func(*args, **kwargs))
407
+
408
+ @property
409
+ def active_sessions(self) -> int:
410
+ """Return the number of active WebSocket sessions."""
411
+ return len(self._sessions)
412
+
413
+ @property
414
+ def max_concurrent_envs(self) -> int:
415
+ """Return the maximum number of concurrent environments."""
416
+ return self._max_concurrent_envs
417
+
418
+ @property
419
+ def is_concurrency_safe(self) -> bool:
420
+ """Return whether the environment is marked as concurrency safe."""
421
+ import inspect
422
+
423
+ if inspect.isclass(self._env_factory):
424
+ return getattr(self._env_factory, "SUPPORTS_CONCURRENT_SESSIONS", False)
425
+ else:
426
+ _temp_env = self._env_factory()
427
+ result = getattr(_temp_env, "SUPPORTS_CONCURRENT_SESSIONS", False)
428
+ _temp_env.close()
429
+ del _temp_env
430
+ return result
431
+
432
+ @property
433
+ def concurrency_config(self) -> ConcurrencyConfig:
434
+ """Return the concurrency configuration."""
435
+ return self._concurrency_config
436
+
437
+ def register_routes(
438
+ self, app: FastAPI, mode: ServerMode | str = ServerMode.SIMULATION
439
+ ) -> None:
440
+ """
441
+ Register HTTP routes on a FastAPI application.
442
+
443
+ Args:
444
+ app: FastAPI application instance
445
+ mode: Server mode - either SIMULATION or PRODUCTION (or string equivalents).
446
+ In production mode, simulation control endpoints (/reset, /step, /state)
447
+ are NOT registered. Only safe endpoints (/health, /schema, /metadata, /ws)
448
+ are available. Defaults to SIMULATION for backwards compatibility.
449
+
450
+ Raises:
451
+ ValueError: If mode is not a valid ServerMode or string equivalent.
452
+ """
453
+ # Convert string to ServerMode enum for backwards compatibility
454
+ if isinstance(mode, str):
455
+ try:
456
+ mode = ServerMode(mode.lower())
457
+ except ValueError:
458
+ valid_modes = [m.value for m in ServerMode]
459
+ raise ValueError(
460
+ f"Invalid mode: '{mode}'. Must be one of: {valid_modes}"
461
+ )
462
+
463
+ # Helper function to handle reset endpoint
464
+ async def reset_handler(
465
+ request: ResetRequest = Body(default_factory=ResetRequest),
466
+ ) -> ResetResponse:
467
+ """Reset endpoint - returns initial observation."""
468
+ _env = self._env_factory()
469
+
470
+ try:
471
+ kwargs = request.model_dump(exclude_unset=True)
472
+
473
+ is_async = _env.reset_async.__func__ is not Environment.reset_async
474
+
475
+ if is_async:
476
+ sig = inspect.signature(_env.reset_async)
477
+ else:
478
+ sig = inspect.signature(_env.reset)
479
+ valid_kwargs = self._get_valid_kwargs(sig, kwargs)
480
+
481
+ if is_async:
482
+ observation = await _env.reset_async(**valid_kwargs)
483
+ else:
484
+ observation = await self._run_sync_in_thread_pool(
485
+ _env.reset, **valid_kwargs
486
+ )
487
+ return ResetResponse(**serialize_observation(observation))
488
+ finally:
489
+ _env.close()
490
+
491
+ # Helper function to handle step endpoint
492
+ async def step_handler(request: StepRequest) -> StepResponse:
493
+ """Step endpoint - executes action and returns observation."""
494
+ action_data = request.action
495
+
496
+ try:
497
+ action = deserialize_action(action_data, self.action_cls)
498
+ except ValidationError as e:
499
+ raise HTTPException(
500
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=e.errors()
501
+ )
502
+
503
+ _env = self._env_factory()
504
+
505
+ try:
506
+ kwargs = request.model_dump(exclude_unset=True, exclude={"action"})
507
+
508
+ is_async = _env.step_async.__func__ is not Environment.step_async
509
+
510
+ if is_async:
511
+ sig = inspect.signature(_env.step_async)
512
+ else:
513
+ sig = inspect.signature(_env.step)
514
+ valid_kwargs = self._get_valid_kwargs(
515
+ sig, kwargs, skip_params={"action"}
516
+ )
517
+
518
+ if is_async:
519
+ observation = await _env.step_async(action, **valid_kwargs)
520
+ else:
521
+ observation = await self._run_sync_in_thread_pool(
522
+ _env.step, action, **valid_kwargs
523
+ )
524
+
525
+ return StepResponse(**serialize_observation(observation))
526
+ finally:
527
+ _env.close()
528
+
529
+ # Helper function to handle MCP endpoint
530
+ async def mcp_handler(
531
+ request: JsonRpcRequest, session_env: Optional[Environment] = None
532
+ ) -> JsonRpcResponse:
533
+ """
534
+ Handle MCP JSON-RPC requests.
535
+
536
+ Supports tools/list and tools/call methods in JSON-RPC 2.0 format.
537
+ """
538
+ method = request.method
539
+ request_id = request.id
540
+
541
+ # Use provided session environment or create temporary one
542
+ if session_env is not None:
543
+ _env = session_env
544
+ should_close = False
545
+ else:
546
+ _env = self._env_factory()
547
+ should_close = True
548
+ try:
549
+ if method == McpMethod.TOOLS_LIST:
550
+ # Check if environment is MCP-enabled
551
+ if not hasattr(_env, "mcp_client"):
552
+ return JsonRpcResponse.error_response(
553
+ JsonRpcErrorCode.INTERNAL_ERROR,
554
+ "Environment does not support MCP",
555
+ request_id=request_id,
556
+ )
557
+
558
+ # Use async context manager for MCP client
559
+ async with _env.mcp_client:
560
+ tools = await _env.mcp_client.list_tools()
561
+
562
+ return JsonRpcResponse.success(
563
+ result={
564
+ "tools": [
565
+ t.model_dump() if hasattr(t, "model_dump") else dict(t)
566
+ for t in tools
567
+ ]
568
+ },
569
+ request_id=request_id,
570
+ )
571
+
572
+ elif method == McpMethod.TOOLS_CALL:
573
+ params = request.params
574
+ tool_name = params.get("name")
575
+ arguments = params.get("arguments", {})
576
+
577
+ if not hasattr(_env, "mcp_client"):
578
+ return JsonRpcResponse.error_response(
579
+ JsonRpcErrorCode.INTERNAL_ERROR,
580
+ "Environment does not support MCP",
581
+ request_id=request_id,
582
+ )
583
+
584
+ if not tool_name:
585
+ return JsonRpcResponse.error_response(
586
+ JsonRpcErrorCode.INVALID_REQUEST,
587
+ "Missing 'name' in params",
588
+ request_id=request_id,
589
+ )
590
+
591
+ # Use async context manager for MCP client
592
+ async with _env.mcp_client:
593
+ result = await _env.mcp_client.call_tool(
594
+ name=tool_name, arguments=arguments
595
+ )
596
+
597
+ # Ensure result is JSON serializable
598
+ serializable_result = _make_json_serializable(result)
599
+
600
+ return JsonRpcResponse.success(
601
+ result=serializable_result,
602
+ request_id=request_id,
603
+ )
604
+
605
+ else:
606
+ return JsonRpcResponse.error_response(
607
+ JsonRpcErrorCode.METHOD_NOT_FOUND,
608
+ f"Method not found: {method}",
609
+ request_id=request_id,
610
+ )
611
+
612
+ except Exception as e:
613
+ return JsonRpcResponse.error_response(
614
+ JsonRpcErrorCode.INTERNAL_ERROR,
615
+ str(e),
616
+ request_id=request_id,
617
+ )
618
+ finally:
619
+ if should_close:
620
+ _env.close()
621
+
622
+ # Register MCP WebSocket endpoint (available in both production and simulation modes)
623
+ @app.websocket("/mcp")
624
+ async def mcp_websocket_endpoint(websocket: WebSocket):
625
+ """
626
+ WebSocket endpoint for MCP JSON-RPC requests.
627
+
628
+ Each WebSocket connection gets its own environment instance for MCP operations.
629
+
630
+ Message Protocol:
631
+ - Client sends: JSON-RPC 2.0 request (tools/list, tools/call)
632
+ - Server responds: JSON-RPC 2.0 response (result or error)
633
+ """
634
+ await websocket.accept()
635
+
636
+ session_id = None
637
+ session_env = None
638
+
639
+ try:
640
+ # Create session with dedicated environment
641
+ session_id, session_env = await self._create_session()
642
+
643
+ while True:
644
+ # Receive message from client
645
+ raw_message = await websocket.receive_text()
646
+
647
+ try:
648
+ jsonrpc_dict = json.loads(raw_message)
649
+ jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)
650
+ except json.JSONDecodeError as e:
651
+ error_resp = JsonRpcResponse.error_response(
652
+ JsonRpcErrorCode.PARSE_ERROR,
653
+ f"Parse error: {e}",
654
+ )
655
+ await websocket.send_text(error_resp.model_dump_json())
656
+ continue
657
+ except ValidationError as e:
658
+ error_resp = JsonRpcResponse.error_response(
659
+ JsonRpcErrorCode.INVALID_REQUEST,
660
+ f"Invalid request: {e}",
661
+ )
662
+ await websocket.send_text(error_resp.model_dump_json())
663
+ continue
664
+
665
+ try:
666
+ # Call mcp_handler with session environment
667
+ response = await mcp_handler(
668
+ jsonrpc_request, session_env=session_env
669
+ )
670
+ await websocket.send_text(response.model_dump_json())
671
+ except Exception as e:
672
+ error_resp = JsonRpcResponse.error_response(
673
+ JsonRpcErrorCode.INTERNAL_ERROR,
674
+ str(e),
675
+ request_id=jsonrpc_request.id,
676
+ )
677
+ await websocket.send_text(error_resp.model_dump_json())
678
+
679
+ except WebSocketDisconnect:
680
+ pass
681
+ except SessionCapacityError as e:
682
+ error_resp = JsonRpcResponse.error_response(
683
+ JsonRpcErrorCode.SERVER_ERROR,
684
+ str(e),
685
+ data={
686
+ "active_sessions": e.active_sessions,
687
+ "max_sessions": e.max_sessions,
688
+ },
689
+ )
690
+ await websocket.send_text(error_resp.model_dump_json())
691
+ except EnvironmentFactoryError as e:
692
+ error_resp = JsonRpcResponse.error_response(
693
+ JsonRpcErrorCode.SERVER_ERROR,
694
+ str(e),
695
+ data={"factory_name": e.factory_name},
696
+ )
697
+ await websocket.send_text(error_resp.model_dump_json())
698
+ except Exception as e:
699
+ error_resp = JsonRpcResponse.error_response(
700
+ JsonRpcErrorCode.SERVER_ERROR,
701
+ str(e),
702
+ )
703
+ await websocket.send_text(error_resp.model_dump_json())
704
+ finally:
705
+ if session_id:
706
+ await self._destroy_session(session_id)
707
+ try:
708
+ await websocket.close()
709
+ except RuntimeError:
710
+ pass
711
+
712
+ # Register simulation control routes only in simulation mode
713
+ if mode == ServerMode.SIMULATION:
714
+
715
+ @app.post(
716
+ "/reset",
717
+ response_model=ResetResponse,
718
+ tags=["Environment Control"],
719
+ summary="Reset the environment",
720
+ description="""
721
+ Reset the environment to its initial state and return the first observation.
722
+
723
+ You can optionally provide a seed for reproducibility and an episode_id for tracking.
724
+ """,
725
+ responses={
726
+ 200: {
727
+ "description": "Environment reset successfully",
728
+ "content": {
729
+ "application/json": {
730
+ "example": {
731
+ "observation": {"status": "ready", "data": {}},
732
+ "reward": None,
733
+ "done": False,
734
+ }
735
+ }
736
+ },
737
+ }
738
+ },
739
+ )
740
+ async def reset(
741
+ request: ResetRequest = Body(default_factory=ResetRequest),
742
+ ) -> ResetResponse:
743
+ return await reset_handler(request)
744
+
745
+ @app.post(
746
+ "/step",
747
+ response_model=StepResponse,
748
+ tags=["Environment Control"],
749
+ summary="Execute an action in the environment",
750
+ description="""
751
+ Execute an action in the environment and receive the resulting observation.
752
+
753
+ The action must conform to the environment's action schema, which can be
754
+ retrieved from the `/schema` endpoint. If the action is invalid,
755
+ the endpoint will return HTTP 422 with detailed validation errors.
756
+
757
+ The response includes:
758
+ - **observation**: The environment's response to the action
759
+ - **reward**: Optional reward signal (float or None)
760
+ - **done**: Boolean indicating if the episode has terminated
761
+ """,
762
+ responses={
763
+ 200: {
764
+ "description": "Action executed successfully",
765
+ "content": {
766
+ "application/json": {
767
+ "example": {
768
+ "observation": {"status": "success", "data": {}},
769
+ "reward": 1.0,
770
+ "done": False,
771
+ }
772
+ }
773
+ },
774
+ },
775
+ 422: {
776
+ "description": "Validation error - invalid action format or values",
777
+ "content": {
778
+ "application/json": {
779
+ "example": {
780
+ "detail": [
781
+ {
782
+ "type": "string_too_short",
783
+ "loc": ["body", "action", "message"],
784
+ "msg": "String should have at least 1 character",
785
+ "input": "",
786
+ }
787
+ ]
788
+ }
789
+ }
790
+ },
791
+ },
792
+ 500: {
793
+ "description": "Internal server error during action execution"
794
+ },
795
+ },
796
+ )
797
+ async def step(request: StepRequest) -> StepResponse:
798
+ return await step_handler(request)
799
+
800
+ def get_state_handler() -> State:
801
+ _env = self._env_factory()
802
+ try:
803
+ return _env.state
804
+ finally:
805
+ _env.close()
806
+
807
+ def get_metadata_handler() -> EnvironmentMetadata:
808
+ _env = self._env_factory()
809
+ try:
810
+ return _env.get_metadata()
811
+ finally:
812
+ _env.close()
813
+
814
+ # Build list of GET endpoints based on mode
815
+ get_endpoints = [
816
+ GetEndpointConfig(
817
+ path="/metadata",
818
+ handler=get_metadata_handler,
819
+ response_model=EnvironmentMetadata,
820
+ tag="Environment Info",
821
+ summary="Get environment metadata",
822
+ description="""
823
+ Get metadata about this environment.
824
+
825
+ Returns information about the environment including name, description,
826
+ version, author, and documentation links.
827
+ """,
828
+ ),
829
+ GetEndpointConfig(
830
+ path="/health",
831
+ handler=lambda: HealthResponse(status=HealthStatus.HEALTHY),
832
+ response_model=HealthResponse,
833
+ tag="Health",
834
+ summary="Health check",
835
+ description="Check if the environment server is running and healthy.",
836
+ ),
837
+ ]
838
+
839
+ # Only register /state endpoint in simulation mode
840
+ if mode == ServerMode.SIMULATION:
841
+ get_endpoints.insert(
842
+ 0,
843
+ GetEndpointConfig(
844
+ path="/state",
845
+ handler=get_state_handler,
846
+ response_model=State,
847
+ tag="State Management",
848
+ summary="Get current environment state",
849
+ description="""
850
+ Retrieve the current internal state of the environment.
851
+
852
+ The structure of the state object is defined by the environment's State model.
853
+ """,
854
+ ),
855
+ )
856
+
857
+ register_get_endpoints(app, get_endpoints)
858
+
859
+ # Register combined schema endpoint
860
+ @app.get(
861
+ "/schema",
862
+ response_model=SchemaResponse,
863
+ tags=["Schema"],
864
+ summary="Get all JSON schemas",
865
+ description="""
866
+ Get JSON schemas for actions, observations, and state in a single response.
867
+
868
+ Returns a combined schema object containing:
869
+ - **action**: JSON schema for actions accepted by this environment
870
+ - **observation**: JSON schema for observations returned by this environment
871
+ - **state**: JSON schema for environment state objects
872
+
873
+ This is more efficient than calling individual schema endpoints and provides
874
+ all schema information needed to interact with the environment.
875
+ """,
876
+ responses={
877
+ 200: {
878
+ "description": "Combined schemas retrieved successfully",
879
+ "content": {
880
+ "application/json": {
881
+ "example": {
882
+ "action": {
883
+ "type": "object",
884
+ "properties": {"message": {"type": "string"}},
885
+ },
886
+ "observation": {
887
+ "type": "object",
888
+ "properties": {"response": {"type": "string"}},
889
+ },
890
+ "state": {
891
+ "type": "object",
892
+ "properties": {"step_count": {"type": "integer"}},
893
+ },
894
+ }
895
+ }
896
+ },
897
+ }
898
+ },
899
+ )
900
+ async def get_schemas() -> SchemaResponse:
901
+ """Return all schemas in one response."""
902
+ return SchemaResponse(
903
+ action=self.action_cls.model_json_schema(),
904
+ observation=self.observation_cls.model_json_schema(),
905
+ state=State.model_json_schema(),
906
+ )
907
+
908
+ # Register MCP endpoint for production mode (direct MCP access)
909
+ @app.post("/mcp")
910
+ async def mcp_endpoint(request_raw: Request) -> Dict[str, Any]:
911
+ """
912
+ MCP JSON-RPC endpoint for production mode.
913
+
914
+ Bypasses step() overhead and provides direct access to MCP tools.
915
+ Supports tools/list and tools/call methods.
916
+ """
917
+ # Parse JSON manually to handle parse errors gracefully
918
+ try:
919
+ body = await request_raw.body()
920
+ request_dict = json.loads(body)
921
+ request = JsonRpcRequest(**request_dict)
922
+ except json.JSONDecodeError:
923
+ return JsonRpcResponse.error_response(
924
+ JsonRpcErrorCode.PARSE_ERROR
925
+ ).model_dump()
926
+ except ValidationError as e:
927
+ return JsonRpcResponse.error_response(
928
+ JsonRpcErrorCode.INVALID_REQUEST,
929
+ f"Invalid request: {e}",
930
+ ).model_dump()
931
+ except Exception:
932
+ return JsonRpcResponse.error_response(
933
+ JsonRpcErrorCode.PARSE_ERROR
934
+ ).model_dump()
935
+
936
+ method = request.method
937
+ params = request.params
938
+ request_id = request.id
939
+
940
+ # Create a temporary environment for MCP access
941
+ _env = self._env_factory()
942
+
943
+ try:
944
+ # Check if environment supports MCP
945
+ if not hasattr(_env, "mcp_client") and not hasattr(_env, "mcp_server"):
946
+ return JsonRpcResponse.error_response(
947
+ JsonRpcErrorCode.INTERNAL_ERROR,
948
+ "Environment does not support MCP",
949
+ request_id=request_id,
950
+ ).model_dump()
951
+
952
+ if method == McpMethod.TOOLS_LIST:
953
+ # List tools from MCP server
954
+ if hasattr(_env, "mcp_client") and _env.mcp_client:
955
+ async with _env.mcp_client:
956
+ tools = await _env.mcp_client.list_tools()
957
+ return JsonRpcResponse.success(
958
+ result={
959
+ "tools": [
960
+ t.model_dump()
961
+ if hasattr(t, "model_dump")
962
+ else dict(t)
963
+ for t in tools
964
+ ]
965
+ },
966
+ request_id=request_id,
967
+ ).model_dump()
968
+ elif hasattr(_env, "mcp_server") and _env.mcp_server:
969
+ # Use server directly
970
+ tools = []
971
+ if hasattr(_env.mcp_server, "_tool_manager"):
972
+ tool_manager = _env.mcp_server._tool_manager
973
+ if hasattr(tool_manager, "_tools"):
974
+ for tool_name, tool in tool_manager._tools.items():
975
+ tool_dict = {
976
+ "name": tool.name,
977
+ "description": tool.description or "",
978
+ "inputSchema": tool.parameters or {},
979
+ }
980
+ tools.append(tool_dict)
981
+ return JsonRpcResponse.success(
982
+ result={"tools": tools},
983
+ request_id=request_id,
984
+ ).model_dump()
985
+ else:
986
+ return JsonRpcResponse.error_response(
987
+ JsonRpcErrorCode.INTERNAL_ERROR,
988
+ "MCP server not available",
989
+ request_id=request_id,
990
+ ).model_dump()
991
+
992
+ elif method == McpMethod.TOOLS_CALL:
993
+ tool_name = params.get("name")
994
+ arguments = params.get("arguments", {})
995
+
996
+ if not tool_name:
997
+ return JsonRpcResponse.error_response(
998
+ JsonRpcErrorCode.INVALID_PARAMS,
999
+ "Invalid params - 'name' is required",
1000
+ request_id=request_id,
1001
+ ).model_dump()
1002
+
1003
+ # Call tool via MCP
1004
+ if hasattr(_env, "mcp_client") and _env.mcp_client:
1005
+ async with _env.mcp_client:
1006
+ result = await _env.mcp_client.call_tool(
1007
+ name=tool_name, arguments=arguments
1008
+ )
1009
+ elif hasattr(_env, "mcp_server") and hasattr(
1010
+ _env.mcp_server, "_tool_manager"
1011
+ ):
1012
+ # Call tool directly on FastMCP server
1013
+ tool_manager = _env.mcp_server._tool_manager
1014
+ if tool_name in tool_manager._tools:
1015
+ tool = tool_manager._tools[tool_name]
1016
+ result = tool.fn(**arguments)
1017
+ else:
1018
+ return JsonRpcResponse.error_response(
1019
+ JsonRpcErrorCode.INVALID_PARAMS,
1020
+ f"Tool not found: {tool_name}",
1021
+ request_id=request_id,
1022
+ ).model_dump()
1023
+ else:
1024
+ return JsonRpcResponse.error_response(
1025
+ JsonRpcErrorCode.INTERNAL_ERROR,
1026
+ "MCP server not available",
1027
+ request_id=request_id,
1028
+ ).model_dump()
1029
+
1030
+ # Make result JSON serializable
1031
+ serializable_result = _make_json_serializable(result)
1032
+
1033
+ return JsonRpcResponse.success(
1034
+ result=serializable_result,
1035
+ request_id=request_id,
1036
+ ).model_dump()
1037
+
1038
+ else:
1039
+ return JsonRpcResponse.error_response(
1040
+ JsonRpcErrorCode.METHOD_NOT_FOUND,
1041
+ f"Method not found: {method}",
1042
+ request_id=request_id,
1043
+ ).model_dump()
1044
+
1045
+ except Exception as e:
1046
+ return JsonRpcResponse.error_response(
1047
+ JsonRpcErrorCode.INTERNAL_ERROR,
1048
+ str(e),
1049
+ request_id=request_id,
1050
+ ).model_dump()
1051
+ finally:
1052
+ _env.close()
1053
+
1054
+ # Register WebSocket endpoint for persistent sessions
1055
+ @app.websocket("/ws")
1056
+ async def websocket_endpoint(websocket: WebSocket):
1057
+ """
1058
+ WebSocket endpoint for persistent environment sessions.
1059
+
1060
+ Each WebSocket connection gets its own environment instance.
1061
+
1062
+ Message Protocol:
1063
+ - Client sends: WSResetMessage | WSStepMessage | WSStateMessage | WSCloseMessage
1064
+ - Server responds: WSObservationResponse | WSStateResponse | WSErrorResponse
1065
+ """
1066
+ await websocket.accept()
1067
+
1068
+ session_id = None
1069
+ session_env = None
1070
+
1071
+ try:
1072
+ # Create session with dedicated environment
1073
+ session_id, session_env = await self._create_session()
1074
+
1075
+ while True:
1076
+ # Receive message from client
1077
+ raw_message = await websocket.receive_text()
1078
+
1079
+ try:
1080
+ message_dict = json.loads(raw_message)
1081
+ except json.JSONDecodeError as e:
1082
+ error_resp = WSErrorResponse(
1083
+ data={
1084
+ "message": f"Invalid JSON: {e}",
1085
+ "code": WSErrorCode.INVALID_JSON,
1086
+ }
1087
+ )
1088
+ await websocket.send_text(error_resp.model_dump_json())
1089
+ continue
1090
+
1091
+ msg_type = message_dict.get("type", "")
1092
+
1093
+ try:
1094
+ match msg_type:
1095
+ case "reset":
1096
+ msg = WSResetMessage(**message_dict)
1097
+
1098
+ is_async = (
1099
+ session_env.reset_async.__func__
1100
+ is not Environment.reset_async
1101
+ )
1102
+
1103
+ if is_async:
1104
+ sig = inspect.signature(session_env.reset_async)
1105
+ valid_kwargs = self._get_valid_kwargs(sig, msg.data)
1106
+ observation = await session_env.reset_async(
1107
+ **valid_kwargs
1108
+ )
1109
+ else:
1110
+ sig = inspect.signature(session_env.reset)
1111
+ valid_kwargs = self._get_valid_kwargs(sig, msg.data)
1112
+ observation = await self._run_in_session_executor(
1113
+ session_id, session_env.reset, **valid_kwargs
1114
+ )
1115
+
1116
+ self._update_session_activity(session_id)
1117
+
1118
+ response = WSObservationResponse(
1119
+ data=serialize_observation(observation),
1120
+ )
1121
+
1122
+ case "step":
1123
+ msg = WSStepMessage(**message_dict)
1124
+ action = deserialize_action(msg.data, self.action_cls)
1125
+
1126
+ is_async = (
1127
+ session_env.step_async.__func__
1128
+ is not Environment.step_async
1129
+ )
1130
+
1131
+ if is_async:
1132
+ observation = await session_env.step_async(action)
1133
+ else:
1134
+ observation = await self._run_in_session_executor(
1135
+ session_id, session_env.step, action
1136
+ )
1137
+
1138
+ self._update_session_activity(
1139
+ session_id, increment_step=True
1140
+ )
1141
+
1142
+ response = WSObservationResponse(
1143
+ data=serialize_observation(observation)
1144
+ )
1145
+
1146
+ case "state":
1147
+ msg = WSStateMessage(**message_dict)
1148
+ state = session_env.state
1149
+ if hasattr(state, "model_dump"):
1150
+ state_data = state.model_dump()
1151
+ else:
1152
+ state_data = dict(state) if state else {}
1153
+
1154
+ response = WSStateResponse(data=state_data)
1155
+
1156
+ case "close":
1157
+ msg = WSCloseMessage(**message_dict)
1158
+ break
1159
+
1160
+ case "mcp":
1161
+ msg = WSMCPMessage(**message_dict)
1162
+ try:
1163
+ rpc_request = JsonRpcRequest(**msg.data)
1164
+ except (ValidationError, Exception) as e:
1165
+ rpc_response = JsonRpcResponse.error_response(
1166
+ JsonRpcErrorCode.INVALID_REQUEST,
1167
+ f"Invalid request: {e}",
1168
+ )
1169
+ else:
1170
+ rpc_response = await mcp_handler(
1171
+ rpc_request,
1172
+ session_env=session_env,
1173
+ )
1174
+ response = WSMCPResponse(data=rpc_response.model_dump())
1175
+
1176
+ case _:
1177
+ response = WSErrorResponse(
1178
+ data={
1179
+ "message": f"Unknown message type: {msg_type}",
1180
+ "code": WSErrorCode.UNKNOWN_TYPE,
1181
+ }
1182
+ )
1183
+
1184
+ await websocket.send_text(response.model_dump_json())
1185
+
1186
+ except ValidationError as e:
1187
+ error_resp = WSErrorResponse(
1188
+ data={
1189
+ "message": "Invalid message",
1190
+ "code": WSErrorCode.VALIDATION_ERROR,
1191
+ "errors": e.errors(),
1192
+ }
1193
+ )
1194
+ await websocket.send_text(error_resp.model_dump_json())
1195
+ except Exception as e:
1196
+ error_resp = WSErrorResponse(
1197
+ data={
1198
+ "message": str(e),
1199
+ "code": WSErrorCode.EXECUTION_ERROR,
1200
+ }
1201
+ )
1202
+ await websocket.send_text(error_resp.model_dump_json())
1203
+
1204
+ except WebSocketDisconnect:
1205
+ pass
1206
+ except SessionCapacityError as e:
1207
+ error_resp = WSErrorResponse(
1208
+ data={
1209
+ "message": str(e),
1210
+ "code": WSErrorCode.CAPACITY_REACHED,
1211
+ "active_sessions": e.active_sessions,
1212
+ "max_sessions": e.max_sessions,
1213
+ }
1214
+ )
1215
+ await websocket.send_text(error_resp.model_dump_json())
1216
+ except EnvironmentFactoryError as e:
1217
+ error_resp = WSErrorResponse(
1218
+ data={
1219
+ "message": str(e),
1220
+ "code": WSErrorCode.FACTORY_ERROR,
1221
+ "factory_name": e.factory_name,
1222
+ }
1223
+ )
1224
+ await websocket.send_text(error_resp.model_dump_json())
1225
+ except Exception as e:
1226
+ error_resp = WSErrorResponse(
1227
+ data={"message": str(e), "code": WSErrorCode.SESSION_ERROR}
1228
+ )
1229
+ await websocket.send_text(error_resp.model_dump_json())
1230
+ finally:
1231
+ if session_id:
1232
+ await self._destroy_session(session_id)
1233
+ try:
1234
+ await websocket.close()
1235
+ except RuntimeError:
1236
+ pass
1237
+
1238
+
1239
+ def create_app(
1240
+ env: Callable[[], Environment],
1241
+ action_cls: Type[Action],
1242
+ observation_cls: Type[Observation],
1243
+ env_name: Optional[str] = None,
1244
+ max_concurrent_envs: Optional[int] = None,
1245
+ concurrency_config: Optional[ConcurrencyConfig] = None,
1246
+ gradio_builder: Optional[Callable[..., Any]] = None,
1247
+ ) -> FastAPI:
1248
+ """
1249
+ Create a FastAPI application with or without web interface.
1250
+
1251
+ This function creates a FastAPI app with the web interface enabled by default,
1252
+ including README integration for better user experience.
1253
+
1254
+ Args:
1255
+ env: Environment factory (callable) that creates new instances
1256
+ action_cls: The Action subclass this environment expects
1257
+ observation_cls: The Observation subclass this environment returns
1258
+ env_name: Optional environment name for README loading
1259
+ max_concurrent_envs: Maximum concurrent WebSocket sessions.
1260
+ Mutually exclusive with concurrency_config.
1261
+ concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings.
1262
+ Mutually exclusive with max_concurrent_envs.
1263
+ gradio_builder: Optional callable to build a custom Gradio UI at /web.
1264
+ Signature: (web_manager, action_fields, metadata, is_chat_env, title,
1265
+ quick_start_md) -> gr.Blocks. When None, the default Gradio app is used.
1266
+ See docs/customizing-web-ui.md.
1267
+
1268
+ Returns:
1269
+ FastAPI application instance with or without web interface and README integration
1270
+ """
1271
+ # Check if web interface should be enabled
1272
+ # This can be controlled via environment variable or build argument
1273
+ enable_web = os.getenv("ENABLE_WEB_INTERFACE", "false").lower() in (
1274
+ "true",
1275
+ "1",
1276
+ "yes",
1277
+ )
1278
+
1279
+ if enable_web:
1280
+ # Gradio-based web UI (gradio is a core dependency)
1281
+ from .web_interface import create_web_interface_app
1282
+
1283
+ return create_web_interface_app(
1284
+ env,
1285
+ action_cls,
1286
+ observation_cls,
1287
+ env_name,
1288
+ max_concurrent_envs,
1289
+ concurrency_config,
1290
+ gradio_builder=gradio_builder,
1291
+ )
1292
+ else:
1293
+ # Use standard FastAPI app without web interface
1294
+ return create_fastapi_app(
1295
+ env, action_cls, observation_cls, max_concurrent_envs, concurrency_config
1296
+ )
1297
+
1298
+
1299
+ def create_fastapi_app(
1300
+ env: Callable[[], Environment],
1301
+ action_cls: Type[Action],
1302
+ observation_cls: Type[Observation],
1303
+ max_concurrent_envs: Optional[int] = None,
1304
+ concurrency_config: Optional[ConcurrencyConfig] = None,
1305
+ ) -> FastAPI:
1306
+ """
1307
+ Create a FastAPI application with comprehensive documentation.
1308
+
1309
+ Args:
1310
+ env: Environment factory (callable) that creates new instances
1311
+ action_cls: The Action subclass this environment expects
1312
+ observation_cls: The Observation subclass this environment returns
1313
+ max_concurrent_envs: Maximum concurrent WebSocket sessions.
1314
+ Mutually exclusive with concurrency_config.
1315
+ concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings.
1316
+ Mutually exclusive with max_concurrent_envs.
1317
+
1318
+ Returns:
1319
+ FastAPI application instance
1320
+ """
1321
+ try:
1322
+ from fastapi import FastAPI
1323
+ except ImportError:
1324
+ raise ImportError(
1325
+ "FastAPI is required. Install with: pip install fastapi uvicorn"
1326
+ )
1327
+
1328
+ app = FastAPI(
1329
+ title="OpenEnv Environment HTTP API",
1330
+ version="1.0.0",
1331
+ description="""
1332
+ # OpenEnv Environment HTTP API
1333
+
1334
+ HTTP API for interacting with OpenEnv environments through a standardized interface.
1335
+
1336
+ ## Features
1337
+
1338
+ * **Environment Reset**: Initialize or restart episodes
1339
+ * **Action Execution**: Send actions and receive observations
1340
+ * **State Inspection**: Query current environment state
1341
+ * **Schema Access**: Retrieve JSON schemas for actions and observations
1342
+
1343
+ ## Workflow
1344
+
1345
+ 1. Call `/reset` to start a new episode and get initial observation
1346
+ 2. Call `/step` repeatedly with actions to interact with environment
1347
+ 3. Episode ends when observation returns `done: true`
1348
+ 4. Call `/state` anytime to inspect current environment state
1349
+
1350
+ ## Documentation
1351
+
1352
+ * **Swagger UI**: Available at `/docs`
1353
+ * **ReDoc**: Available at `/redoc`
1354
+ * **OpenAPI Schema**: Available at `/openapi.json`
1355
+ """,
1356
+ openapi_tags=[
1357
+ {
1358
+ "name": "Environment Control",
1359
+ "description": "Core operations for environment interaction (reset, step)",
1360
+ },
1361
+ {
1362
+ "name": "State Management",
1363
+ "description": "Operations for inspecting environment state",
1364
+ },
1365
+ {
1366
+ "name": "Environment Info",
1367
+ "description": "Information about the environment",
1368
+ },
1369
+ {
1370
+ "name": "Schema",
1371
+ "description": "JSON Schema endpoints for actions, observations, and state",
1372
+ },
1373
+ {"name": "Health", "description": "Service health and status checks"},
1374
+ ],
1375
+ docs_url="/docs",
1376
+ redoc_url="/redoc",
1377
+ openapi_url="/openapi.json",
1378
+ contact={
1379
+ "name": "OpenEnv Team",
1380
+ "url": "https://github.com/meta-pytorch/OpenEnv",
1381
+ },
1382
+ license_info={
1383
+ "name": "BSD-3-Clause",
1384
+ "url": "https://github.com/meta-pytorch/OpenEnv/blob/main/LICENSE",
1385
+ },
1386
+ )
1387
+
1388
+ server = HTTPEnvServer(
1389
+ env,
1390
+ action_cls,
1391
+ observation_cls,
1392
+ max_concurrent_envs,
1393
+ concurrency_config=concurrency_config,
1394
+ )
1395
+ server.register_routes(app)
1396
+ return app
src/core/env_server/interfaces.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import inspect
8
+ from abc import ABC, abstractmethod
9
+ from typing import Any, Generic, Optional, Protocol, TypedDict, TypeVar, TYPE_CHECKING
10
+
11
+ from .types import Action, Observation, State, EnvironmentMetadata
12
+
13
+ if TYPE_CHECKING:
14
+ from openenv.core.rubrics import Rubric
15
+
16
+ ActT = TypeVar("ActT", bound=Action)
17
+ ObsT = TypeVar("ObsT", bound=Observation)
18
+ StateT = TypeVar("StateT", bound=State)
19
+
20
+
21
+ class Message(TypedDict):
22
+ """A message in a conversation.
23
+
24
+ Compatible with Huggingface chat template format.
25
+ """
26
+
27
+ role: str
28
+ content: str
29
+
30
+
31
+ class ModelTokenizer(Protocol):
32
+ """Protocol for tokenizers that support chat templates.
33
+
34
+ This protocol defines the interface that tokenizers must implement
35
+ to work with chat-based environments. It's compatible with
36
+ Huggingface transformers tokenizers.
37
+ """
38
+
39
+ def apply_chat_template(
40
+ self,
41
+ conversation: list[Message],
42
+ tokenize: bool = True,
43
+ return_tensors: str | None = None,
44
+ **kwargs: Any,
45
+ ) -> Any:
46
+ """Apply a chat template to format and optionally tokenize a conversation.
47
+
48
+ Args:
49
+ conversation: List of message dictionaries with 'role' and 'content'
50
+ tokenize: Whether to tokenize the output
51
+ return_tensors: Format for returned tensors ('pt' for PyTorch)
52
+ **kwargs: Additional arguments
53
+
54
+ Returns:
55
+ Formatted and optionally tokenized conversation
56
+ """
57
+ ...
58
+
59
+ def decode(
60
+ self, token_ids: Any, skip_special_tokens: bool = False, **kwargs: Any
61
+ ) -> str:
62
+ """Decode token IDs back to text.
63
+
64
+ Args:
65
+ token_ids: Token IDs to decode
66
+ skip_special_tokens: Whether to skip special tokens in output
67
+ **kwargs: Additional arguments
68
+
69
+ Returns:
70
+ Decoded text string
71
+ """
72
+ ...
73
+
74
+
75
+ class Transform(ABC, Generic[ObsT]):
76
+ """Transform observations to add rewards, metrics, or other modifications.
77
+
78
+ Transforms follow the TorchRL pattern where they take an observation
79
+ and return a (potentially modified) observation. This allows for
80
+ flexible reward computation and observation augmentation.
81
+ """
82
+
83
+ @abstractmethod
84
+ def __call__(self, observation: ObsT) -> ObsT:
85
+ """Transform an observation.
86
+
87
+ Args:
88
+ observation: The input observation
89
+
90
+ Returns:
91
+ The transformed observation
92
+ """
93
+ pass
94
+
95
+
96
+ class Environment(ABC, Generic[ActT, ObsT, StateT]):
97
+ """Base class for all environment servers following Gym/Gymnasium API.
98
+
99
+ Args:
100
+ transform: Optional transform to apply to observations
101
+ rubric: Optional rubric for reward computation. When provided, the
102
+ rubric's output can be used to set the observation's reward in step().
103
+
104
+ Class Attributes:
105
+ SUPPORTS_CONCURRENT_SESSIONS: Whether this environment supports concurrent sessions.
106
+ When True, multiple WebSocket connections can each have their own
107
+ environment instance (up to max_concurrent_envs). When False (default),
108
+ the environment should only be used with a single session at a time.
109
+
110
+ Set this to True in your Environment subclass if:
111
+ - The environment uses proper session isolation (e.g., unique working dirs)
112
+ - No shared mutable state exists between instances
113
+ - External resources (databases, APIs) can handle concurrent access
114
+
115
+ Attributes:
116
+ rubric: Optional rubric for computing rewards. Environments can set this
117
+ in __init__ and use it in step() to compute observation rewards.
118
+ Training infrastructure can access it for introspection:
119
+ for name, r in env.rubric.named_rubrics():
120
+ print(f"{name}: {r.last_score}")
121
+
122
+ See RFC 004 for rubric design: rfcs/004-rubrics.md
123
+ """
124
+
125
+ # Class-level flag indicating whether this environment supports concurrent sessions
126
+ SUPPORTS_CONCURRENT_SESSIONS: bool = False
127
+
128
+ # Optional rubric for reward computation
129
+ rubric: Optional["Rubric"]
130
+
131
+ def __init__(
132
+ self,
133
+ transform: Optional[Transform[ObsT]] = None,
134
+ rubric: Optional["Rubric"] = None,
135
+ ):
136
+ self.transform = transform
137
+ self.rubric = rubric
138
+
139
+ @abstractmethod
140
+ def reset(
141
+ self,
142
+ seed: Optional[int] = None,
143
+ episode_id: Optional[str] = None,
144
+ **kwargs: Any,
145
+ ) -> ObsT:
146
+ """Reset the environment and return initial observation."""
147
+ pass
148
+
149
+ async def reset_async(
150
+ self,
151
+ seed: Optional[int] = None,
152
+ episode_id: Optional[str] = None,
153
+ **kwargs: Any,
154
+ ) -> ObsT:
155
+ """Async version of reset. Default implementation calls sync reset.
156
+
157
+ Override to provide true async implementation.
158
+ """
159
+ return self.reset(seed=seed, episode_id=episode_id, **kwargs)
160
+
161
+ @abstractmethod
162
+ def step(
163
+ self,
164
+ action: ActT,
165
+ timeout_s: Optional[float] = None,
166
+ **kwargs: Any,
167
+ ) -> ObsT:
168
+ """Take a step in the environment."""
169
+ pass
170
+
171
+ async def step_async(
172
+ self,
173
+ action: ActT,
174
+ timeout_s: Optional[float] = None,
175
+ **kwargs: Any,
176
+ ) -> ObsT:
177
+ """Async version of step. Default implementation calls sync step.
178
+
179
+ Override to provide true async implementation.
180
+ """
181
+ return self.step(action, timeout_s=timeout_s, **kwargs)
182
+
183
+ @property
184
+ @abstractmethod
185
+ def state(self) -> StateT:
186
+ """Get the current environment state."""
187
+ pass
188
+
189
+ def get_metadata(self) -> EnvironmentMetadata:
190
+ """
191
+ Get metadata about this environment.
192
+
193
+ Override this method to provide custom metadata for the environment.
194
+ Default implementation returns basic metadata derived from class name.
195
+
196
+ Returns:
197
+ EnvironmentMetadata with environment information
198
+ """
199
+ return EnvironmentMetadata(
200
+ name=self.__class__.__name__,
201
+ description=f"{self.__class__.__name__} environment",
202
+ version="1.0.0",
203
+ )
204
+
205
+ def _apply_transform(self, observation: ObsT) -> ObsT:
206
+ """Apply transform if one is provided."""
207
+ if self.transform is not None:
208
+ return self.transform(observation)
209
+ return observation
210
+
211
+ def _apply_rubric(self, action: ActT, observation: ObsT) -> float:
212
+ """Apply rubric if one is provided.
213
+
214
+ Args:
215
+ action: The action taken by the agent.
216
+ observation: The resulting observation.
217
+
218
+ Returns:
219
+ Reward value from the rubric, or 0.0 if no rubric is set.
220
+
221
+ Usage in step():
222
+ def step(self, action: MyAction, ...) -> MyObservation:
223
+ # ... execute action and create observation ...
224
+ observation.reward = self._apply_rubric(action, observation)
225
+ return observation
226
+ """
227
+ if self.rubric is not None:
228
+ return self.rubric(action, observation)
229
+ return 0.0
230
+
231
+ async def _apply_rubric_async(self, action: ActT, observation: ObsT) -> float:
232
+ """Apply rubric asynchronously if one is provided.
233
+
234
+ Args:
235
+ action: The action taken by the agent.
236
+ observation: The resulting observation.
237
+
238
+ Returns:
239
+ Reward value from the rubric, or 0.0 if no rubric is set.
240
+
241
+ Usage in step_async():
242
+ async def step_async(self, action: MyAction, ...) -> MyObservation:
243
+ # ... execute action and create observation ...
244
+ observation.reward = await self._apply_rubric_async(action, observation)
245
+ return observation
246
+ """
247
+ if self.rubric is not None:
248
+ result = self.rubric(action, observation)
249
+ # If rubric returns a coroutine, await it
250
+ if inspect.iscoroutine(result):
251
+ return await result
252
+ return result
253
+ return 0.0
254
+
255
+ def _reset_rubric(self) -> None:
256
+ """Reset the rubric state if one is provided.
257
+
258
+ Call this in reset() to clear any trajectory state in the rubric.
259
+
260
+ Usage in reset():
261
+ def reset(self, ...) -> MyObservation:
262
+ self._reset_rubric()
263
+ # ... create initial observation ...
264
+ return observation
265
+ """
266
+ if self.rubric is not None:
267
+ self.rubric.reset()
268
+
269
+ async def _reset_rubric_async(self) -> None:
270
+ """Reset the rubric state asynchronously if one is provided.
271
+
272
+ Call this in reset_async() to clear any trajectory state in the rubric.
273
+
274
+ Usage in reset_async():
275
+ async def reset_async(self, ...) -> MyObservation:
276
+ await self._reset_rubric_async()
277
+ # ... create initial observation ...
278
+ return observation
279
+ """
280
+ if self.rubric is not None:
281
+ # Check if rubric has async reset method
282
+ if hasattr(self.rubric, "reset_async"):
283
+ result = self.rubric.reset_async()
284
+ if inspect.iscoroutine(result):
285
+ await result
286
+ else:
287
+ self.rubric.reset()
288
+
289
+ def close(self) -> None:
290
+ """Clean up resources used by the environment.
291
+
292
+ Override this method to implement custom cleanup logic.
293
+ Called when the environment is being destroyed or reset.
294
+ """
295
+ pass
src/core/env_server/mcp_environment.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ MCP Environment base class for OpenEnv.
9
+
10
+ This module provides the MCPEnvironment base class that integrates FastMCP servers
11
+ with OpenEnv's Gym-style Environment interface. It handles MCP tool discovery
12
+ and invocation through the step() API, following RFC 003.
13
+
14
+ Key features:
15
+ - Automatic routing of ListToolsAction and CallToolAction to MCP server
16
+ - Reserved tool name validation (reset, step, state, close are protected)
17
+ - Timeout handling for tool calls
18
+ - Proper error categorization (tool not found, execution errors, timeouts)
19
+ - Mode-aware tool registration (production vs simulation)
20
+ - Code mode support via get_callables() and execute_code()
21
+
22
+ Usage:
23
+ from fastmcp import FastMCP
24
+ from openenv.core.env_server.mcp_environment import MCPEnvironment
25
+
26
+ class MyMCPEnv(MCPEnvironment):
27
+ def __init__(self):
28
+ mcp = FastMCP("my-server")
29
+
30
+ # Register mode-specific tools
31
+ @self.tool(mode="production")
32
+ def my_tool(arg: str) -> str:
33
+ return f"Production: {arg}"
34
+
35
+ @self.tool(mode="simulation")
36
+ def my_tool(arg: str) -> str:
37
+ return f"Simulation: {arg}"
38
+
39
+ super().__init__(mcp)
40
+
41
+ def reset(self, seed=None, episode_id=None, **kwargs):
42
+ # Reset logic here
43
+ ...
44
+
45
+ def _step_impl(self, action):
46
+ # Handle non-MCP actions
47
+ ...
48
+
49
+ @property
50
+ def state(self):
51
+ # Return current state
52
+ ...
53
+ """
54
+
55
+ import asyncio
56
+ import inspect
57
+ from abc import abstractmethod
58
+ from collections import defaultdict
59
+ from typing import Any, Callable, Dict, Optional
60
+
61
+ from fastmcp import Client
62
+ from fastmcp.client.client import CallToolResult
63
+ from mcp.types import TextContent
64
+
65
+ from ..utils import run_async_safely
66
+ from .interfaces import Environment
67
+ from .mcp_types import (
68
+ CallToolAction,
69
+ CallToolObservation,
70
+ ListToolsAction,
71
+ ListToolsObservation,
72
+ RESERVED_TOOL_NAMES,
73
+ Tool,
74
+ ToolError,
75
+ ToolErrorType,
76
+ )
77
+ from .types import Action, Observation
78
+
79
+
80
+ # Default timeout for MCP tool calls in seconds
81
+ MCP_TOOL_CALL_TIMEOUT = 30.0
82
+
83
+ # Valid modes for tool registration
84
+ VALID_MODES = {"production", "simulation"}
85
+
86
+
87
+ class MCPEnvironment(Environment):
88
+ """
89
+ Base class for environments that expose tools via MCP (Model Context Protocol).
90
+
91
+ MCPEnvironment bridges FastMCP servers with OpenEnv's Gym-style API, allowing
92
+ agents to discover and invoke MCP tools through the standard step() interface.
93
+
94
+ The class automatically handles:
95
+ - ListToolsAction: Returns available tools from the MCP server
96
+ - CallToolAction: Invokes a specific tool with arguments
97
+
98
+ All other actions are delegated to the abstract _step_impl() method,
99
+ which subclasses must implement.
100
+
101
+ Args:
102
+ mcp_server: A FastMCP server instance containing tool definitions.
103
+ The server's tools will be validated against reserved names.
104
+ transform: Optional transform to apply to observations (inherited from Environment).
105
+
106
+ Raises:
107
+ ValueError: If any tool in the MCP server uses a reserved name
108
+ (reset, step, state, close).
109
+
110
+ Example:
111
+ >>> from fastmcp import FastMCP
112
+ >>> mcp = FastMCP("calculator")
113
+ >>> @mcp.tool()
114
+ ... def add(a: int, b: int) -> int:
115
+ ... return a + b
116
+ >>> env = MyMCPEnvironment(mcp)
117
+ >>> obs = env.step(ListToolsAction())
118
+ >>> obs.tools[0].name
119
+ 'add'
120
+ """
121
+
122
+ def __init__(self, mcp_server: Any, transform: Optional[Any] = None) -> None:
123
+ """
124
+ Initialize the MCP environment.
125
+
126
+ Args:
127
+ mcp_server: A FastMCP server instance with tool definitions.
128
+ transform: Optional transform to apply to observations.
129
+
130
+ Raises:
131
+ ValueError: If any tool uses a reserved name (reset, step, state, close).
132
+ """
133
+ super().__init__(transform=transform)
134
+
135
+ # Validate tool names before storing
136
+ self._validate_tool_names(mcp_server)
137
+
138
+ self.mcp_server = mcp_server
139
+ self.mcp_client = Client(mcp_server)
140
+
141
+ # Track mode-specific tools: {tool_name: {mode: func}}
142
+ # mode can be "production", "simulation", or None (available in all modes)
143
+ self._mode_tools = defaultdict(dict)
144
+
145
+ # Track tool schemas for list_tools: {tool_name: {mode: schema}}
146
+ self._mode_tool_schemas = defaultdict(dict)
147
+
148
+ @property
149
+ def supports_code_mode(self) -> bool:
150
+ """Check if this environment supports code mode (execute_code)."""
151
+ return True
152
+
153
+ def get_callables(self) -> Dict[str, Callable]:
154
+ """
155
+ Get callable functions for code mode.
156
+
157
+ Returns tool functions as direct Python callables, enabling code mode
158
+ where agents write Python code that calls tools directly (no JSON-RPC
159
+ overhead). Mode-specific tools are filtered by the current mode.
160
+
161
+ Returns:
162
+ Dictionary mapping tool names to callables.
163
+ """
164
+ callables: Dict[str, Callable] = {}
165
+ current_mode = getattr(self, "_mode", None)
166
+
167
+ # Extract callables from FastMCP server's tool manager
168
+ if (
169
+ hasattr(self.mcp_server, "_tool_manager")
170
+ and hasattr(self.mcp_server._tool_manager, "_tools")
171
+ and isinstance(getattr(self.mcp_server._tool_manager, "_tools", None), dict)
172
+ ):
173
+ for tool_name, tool in self.mcp_server._tool_manager._tools.items():
174
+ if hasattr(tool, "fn") and callable(tool.fn):
175
+ callables[tool_name] = tool.fn
176
+
177
+ # Add mode-specific tools available in current mode
178
+ for tool_name, mode_funcs in self._mode_tools.items():
179
+ if None in mode_funcs:
180
+ # Tool available in all modes (already in FastMCP if registered there)
181
+ if tool_name not in callables:
182
+ callables[tool_name] = mode_funcs[None]
183
+ elif current_mode in mode_funcs:
184
+ # Tool available in current mode only
185
+ callables[tool_name] = mode_funcs[current_mode]
186
+
187
+ return callables
188
+
189
+ def execute_code(self, code: str) -> Observation:
190
+ """
191
+ Execute Python code with tools available as callables.
192
+
193
+ This enables the CodeAct pattern where agents write Python code
194
+ that calls tools directly as functions, avoiding JSON-RPC overhead.
195
+
196
+ Args:
197
+ code: Python code to execute. Tools are available as functions
198
+ in the execution namespace. Set a variable named 'result'
199
+ to capture the return value.
200
+
201
+ Returns:
202
+ Observation with result in metadata["result"] or error in
203
+ metadata["error"].
204
+ """
205
+ namespace = self.get_callables()
206
+
207
+ result_dict: Dict[str, Any] = {}
208
+ try:
209
+ exec(code, namespace, result_dict)
210
+ result = result_dict.get("result")
211
+ return Observation(done=False, reward=0.0, metadata={"result": result})
212
+ except SyntaxError as e:
213
+ return Observation(
214
+ done=False, reward=0.0, metadata={"error": f"Syntax error: {str(e)}"}
215
+ )
216
+ except Exception as e:
217
+ return Observation(done=False, reward=0.0, metadata={"error": str(e)})
218
+
219
+ def _validate_tool_names(self, mcp_server: Any) -> None:
220
+ """
221
+ Validate that no tools use reserved names.
222
+
223
+ Reserved names (reset, step, state, close) are protected to maintain
224
+ the dual API boundary between infrastructure and agent APIs.
225
+
226
+ Args:
227
+ mcp_server: The FastMCP server to validate.
228
+
229
+ Raises:
230
+ ValueError: If any tool uses a reserved name.
231
+ """
232
+ # FastMCP stores tools in _tool_manager._tools dict
233
+ if hasattr(mcp_server, "_tool_manager"):
234
+ tool_manager = mcp_server._tool_manager
235
+ # Check both possible attribute names for tools storage
236
+ tools_dict = None
237
+ if hasattr(tool_manager, "_tools"):
238
+ tools_dict = tool_manager._tools
239
+ elif hasattr(tool_manager, "tools"):
240
+ tools_dict = tool_manager.tools
241
+
242
+ if tools_dict:
243
+ tool_names = set(tools_dict.keys())
244
+ conflicts = tool_names & RESERVED_TOOL_NAMES
245
+ if conflicts:
246
+ raise ValueError(
247
+ f"MCP tools cannot use reserved names: {sorted(conflicts)}. "
248
+ f"Reserved names are: {sorted(RESERVED_TOOL_NAMES)}"
249
+ )
250
+
251
+ def tool(self, mode: Optional[str] = None) -> Callable:
252
+ """
253
+ Decorator for registering mode-aware tools.
254
+
255
+ Args:
256
+ mode: Optional mode for the tool ("production" or "simulation").
257
+ If None, tool is available in all modes.
258
+
259
+ Returns:
260
+ A decorator function for registering tools.
261
+
262
+ Raises:
263
+ ValueError: If mode is not None, "production", or "simulation".
264
+ """
265
+ if mode is not None and mode not in VALID_MODES:
266
+ raise ValueError(
267
+ f"Invalid mode '{mode}'. Mode must be 'production', 'simulation', or None."
268
+ )
269
+
270
+ def decorator(func: Callable) -> Callable:
271
+ tool_name = func.__name__
272
+ # Validate tool name is not reserved
273
+ if tool_name in RESERVED_TOOL_NAMES:
274
+ raise ValueError(
275
+ f"Tool name '{tool_name}' is reserved and cannot be used. "
276
+ f"Reserved names are: {sorted(RESERVED_TOOL_NAMES)}"
277
+ )
278
+
279
+ # If mode is None, register with FastMCP as usual
280
+ if mode is None:
281
+ decorated_func = self.mcp_server.tool()(func)
282
+ self._mode_tools[tool_name][None] = func
283
+ return decorated_func
284
+
285
+ # For mode-specific tools, don't register with FastMCP
286
+ # Instead, track them ourselves
287
+ self._mode_tools[tool_name][mode] = func
288
+
289
+ # Extract schema information from function signature
290
+ sig = inspect.signature(func)
291
+ schema = {
292
+ "type": "object",
293
+ "properties": {},
294
+ "required": [],
295
+ }
296
+
297
+ for param_name, param in sig.parameters.items():
298
+ # Get type annotation
299
+ param_type = param.annotation
300
+ json_type = "string" # default
301
+ if param_type in (int, "int"):
302
+ json_type = "integer"
303
+ elif param_type in (float, "float"):
304
+ json_type = "number"
305
+ elif param_type in (bool, "bool"):
306
+ json_type = "boolean"
307
+
308
+ schema["properties"][param_name] = {"type": json_type}
309
+
310
+ # If no default value, it's required
311
+ if param.default == inspect.Parameter.empty:
312
+ schema["required"].append(param_name)
313
+
314
+ # Store the schema for this mode-specific tool
315
+ self._mode_tool_schemas[tool_name][mode] = {
316
+ "name": tool_name,
317
+ "description": func.__doc__ or "",
318
+ "input_schema": schema,
319
+ }
320
+
321
+ return func
322
+
323
+ return decorator
324
+
325
+ def step(
326
+ self,
327
+ action: Action,
328
+ timeout_s: Optional[float] = None,
329
+ **kwargs: Any,
330
+ ) -> Observation:
331
+ """
332
+ Execute an action in the environment.
333
+
334
+ This method routes MCP-specific actions (ListToolsAction, CallToolAction)
335
+ to the appropriate handlers, while delegating all other actions to
336
+ the subclass's _step_impl() method.
337
+
338
+ Args:
339
+ action: The action to execute. Can be:
340
+ - ListToolsAction: Returns available MCP tools
341
+ - CallToolAction: Invokes a specific MCP tool
342
+ - Any other Action: Delegated to _step_impl()
343
+ timeout_s: Optional timeout in seconds for the action.
344
+ Defaults to MCP_TOOL_CALL_TIMEOUT (30s) for MCP actions.
345
+ **kwargs: Additional arguments passed to handlers.
346
+
347
+ Returns:
348
+ Observation appropriate to the action type:
349
+ - ListToolsObservation for ListToolsAction
350
+ - CallToolObservation for CallToolAction
351
+ - Subclass-defined Observation for other actions
352
+ """
353
+ if isinstance(action, ListToolsAction):
354
+ return self._handle_list_tools()
355
+ elif isinstance(action, CallToolAction):
356
+ return self._handle_call_tool(action, timeout_s=timeout_s)
357
+ else:
358
+ return self._step_impl(action, timeout_s=timeout_s, **kwargs)
359
+
360
+ def _handle_list_tools(self) -> ListToolsObservation:
361
+ """
362
+ Handle a ListToolsAction by querying the MCP server.
363
+
364
+ Returns:
365
+ ListToolsObservation containing all available tools with their
366
+ names, descriptions, and input schemas, filtered by current mode.
367
+ """
368
+ try:
369
+ # Get current mode
370
+ current_mode = getattr(self, "_mode", None)
371
+
372
+ # Start with tools from FastMCP server (mode=None tools)
373
+ tools_result = run_async_safely(self._async_list_tools())
374
+
375
+ # Build list of Tool objects
376
+ tools = []
377
+
378
+ # Add FastMCP tools that are not mode-specific
379
+ for tool in tools_result:
380
+ if tool.name not in self._mode_tool_schemas:
381
+ tools.append(
382
+ Tool(
383
+ name=tool.name,
384
+ description=tool.description or "",
385
+ input_schema=tool.inputSchema
386
+ if hasattr(tool, "inputSchema")
387
+ else {},
388
+ )
389
+ )
390
+
391
+ # Add mode-specific tools available in current mode
392
+ for tool_name, mode_schemas in self._mode_tool_schemas.items():
393
+ if None in mode_schemas:
394
+ # Tool available in all modes
395
+ schema = mode_schemas[None]
396
+ tools.append(
397
+ Tool(
398
+ name=schema["name"],
399
+ description=schema["description"],
400
+ input_schema=schema["input_schema"],
401
+ )
402
+ )
403
+ elif current_mode in mode_schemas:
404
+ # Tool available in current mode
405
+ schema = mode_schemas[current_mode]
406
+ tools.append(
407
+ Tool(
408
+ name=schema["name"],
409
+ description=schema["description"],
410
+ input_schema=schema["input_schema"],
411
+ )
412
+ )
413
+
414
+ return ListToolsObservation(tools=tools)
415
+
416
+ except Exception as e:
417
+ # Return an observation with error in metadata
418
+ return ListToolsObservation(
419
+ tools=[],
420
+ metadata={
421
+ "error": str(e),
422
+ "error_type": "list_tools_failed",
423
+ },
424
+ )
425
+
426
+ async def _async_list_tools(self) -> list:
427
+ """
428
+ Async helper to list tools from the MCP client.
429
+
430
+ Returns:
431
+ List of tool objects from the MCP server.
432
+ """
433
+ async with self.mcp_client:
434
+ return await self.mcp_client.list_tools()
435
+
436
+ def _handle_call_tool(
437
+ self,
438
+ action: CallToolAction,
439
+ timeout_s: Optional[float] = None,
440
+ ) -> CallToolObservation:
441
+ """
442
+ Handle a CallToolAction by invoking the specified tool.
443
+
444
+ Args:
445
+ action: The CallToolAction containing tool_name and arguments.
446
+ timeout_s: Timeout in seconds. Defaults to MCP_TOOL_CALL_TIMEOUT (30s).
447
+
448
+ Returns:
449
+ CallToolObservation with the tool's result or an error.
450
+ """
451
+ timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUT
452
+
453
+ # Check if this is a mode-specific tool
454
+ tool_name = action.tool_name
455
+ current_mode = getattr(self, "_mode", None)
456
+
457
+ if tool_name in self._mode_tools:
458
+ mode_info = self._mode_tools[tool_name]
459
+
460
+ # Check if tool is available in current mode
461
+ # Tool is available if:
462
+ # 1. It has a None mode (available in all modes), OR
463
+ # 2. It has an implementation for the current mode
464
+ if None in mode_info:
465
+ # Use the mode-agnostic version
466
+ func = mode_info[None]
467
+ elif current_mode in mode_info:
468
+ # Use the mode-specific version
469
+ func = mode_info[current_mode]
470
+ else:
471
+ # Tool not available in current mode
472
+ return CallToolObservation(
473
+ tool_name=tool_name,
474
+ result=None,
475
+ error=ToolError(
476
+ error_type=ToolErrorType.TOOL_NOT_FOUND,
477
+ message=f"Tool '{tool_name}' not available in {current_mode} mode",
478
+ ),
479
+ )
480
+
481
+ # Call the mode-specific function directly
482
+ try:
483
+ # Check if function is async and await if necessary
484
+ if inspect.iscoroutinefunction(func):
485
+ result = run_async_safely(func(**action.arguments))
486
+ else:
487
+ result = func(**action.arguments)
488
+
489
+ # Wrap result in CallToolResult format to match FastMCP behavior
490
+ return CallToolObservation(
491
+ tool_name=tool_name,
492
+ result=CallToolResult(
493
+ content=[TextContent(type="text", text=str(result))],
494
+ structured_content={"result": result},
495
+ meta=None,
496
+ data=result,
497
+ is_error=False,
498
+ ),
499
+ )
500
+ except Exception as e:
501
+ return CallToolObservation(
502
+ tool_name=tool_name,
503
+ result=None,
504
+ error=ToolError(
505
+ error_type=ToolErrorType.EXECUTION_ERROR,
506
+ message=str(e),
507
+ ),
508
+ )
509
+
510
+ # Not a mode-specific tool, use FastMCP
511
+ try:
512
+ # Run the async call_tool with timeout
513
+ # Use run_async_safely to handle both sync and async contexts
514
+ result = run_async_safely(
515
+ asyncio.wait_for(
516
+ self._async_call_tool(action.tool_name, action.arguments),
517
+ timeout=timeout,
518
+ )
519
+ )
520
+
521
+ return CallToolObservation(
522
+ tool_name=action.tool_name,
523
+ result=result,
524
+ )
525
+
526
+ except asyncio.TimeoutError:
527
+ return CallToolObservation(
528
+ tool_name=action.tool_name,
529
+ result=None,
530
+ error=ToolError(
531
+ error_type=ToolErrorType.TIMEOUT,
532
+ message=f"Tool '{action.tool_name}' timed out after {timeout} seconds",
533
+ ),
534
+ )
535
+
536
+ except Exception as e:
537
+ error_message = str(e)
538
+
539
+ # Determine error type based on the exception
540
+ if (
541
+ "not found" in error_message.lower()
542
+ or "unknown tool" in error_message.lower()
543
+ ):
544
+ error_type = ToolErrorType.TOOL_NOT_FOUND
545
+ elif (
546
+ "invalid" in error_message.lower()
547
+ or "argument" in error_message.lower()
548
+ ):
549
+ error_type = ToolErrorType.INVALID_ARGS
550
+ else:
551
+ error_type = ToolErrorType.EXECUTION_ERROR
552
+
553
+ return CallToolObservation(
554
+ tool_name=action.tool_name,
555
+ result=None,
556
+ error=ToolError(
557
+ error_type=error_type,
558
+ message=error_message,
559
+ ),
560
+ )
561
+
562
+ async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:
563
+ """
564
+ Async helper to call a tool on the MCP server.
565
+
566
+ Args:
567
+ tool_name: Name of the tool to invoke.
568
+ arguments: Dictionary of arguments to pass to the tool.
569
+
570
+ Returns:
571
+ The result from the tool execution.
572
+ """
573
+ async with self.mcp_client:
574
+ return await self.mcp_client.call_tool(tool_name, arguments)
575
+
576
+ @abstractmethod
577
+ def _step_impl(
578
+ self,
579
+ action: Action,
580
+ timeout_s: Optional[float] = None,
581
+ **kwargs: Any,
582
+ ) -> Observation:
583
+ """
584
+ Handle non-MCP actions in the environment.
585
+
586
+ Subclasses must implement this method to handle any actions that are
587
+ not ListToolsAction or CallToolAction. This is where environment-specific
588
+ action processing should occur.
589
+
590
+ Args:
591
+ action: The action to execute (guaranteed not to be an MCP action).
592
+ timeout_s: Optional timeout in seconds.
593
+ **kwargs: Additional arguments.
594
+
595
+ Returns:
596
+ An Observation appropriate for the action.
597
+ """
598
+ pass
599
+
600
+ def close(self) -> None:
601
+ """
602
+ Clean up resources used by the environment.
603
+
604
+ This method cleans up the MCP client and any other resources.
605
+ Subclasses should call super().close() if they override this method.
606
+ """
607
+ # The MCP client uses async context manager, so cleanup happens
608
+ # automatically when the context exits. We just clear references.
609
+ self.mcp_client = None
610
+ self.mcp_server = None
src/core/env_server/mcp_types.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ MCP (Model Context Protocol) type definitions for OpenEnv.
9
+
10
+ This module defines strongly typed models for MCP tool discovery and invocation,
11
+ following RFC 003. These types map MCP's REST-like API (tools/list, tools/call)
12
+ to Gym-style action types.
13
+
14
+ Key design decisions:
15
+ - Tool discovery (list_tools) does NOT require reset() first
16
+ - Reserved tool names (reset, step, state, close) are prohibited
17
+ - Both step() and WebSocket /mcp paths are supported
18
+ """
19
+
20
+ from enum import Enum
21
+ from typing import Any, Dict, List, Literal, Optional, Union
22
+
23
+ from pydantic import BaseModel, ConfigDict, Field
24
+
25
+ from .types import Action, Observation, BaseMessage
26
+
27
+
28
+ # =============================================================================
29
+ # JSON-RPC 2.0 Types
30
+ # =============================================================================
31
+
32
+
33
+ class JsonRpcErrorCode(int, Enum):
34
+ """
35
+ Standard JSON-RPC 2.0 error codes.
36
+
37
+ See: https://www.jsonrpc.org/specification#error_object
38
+ """
39
+
40
+ # Standard JSON-RPC errors
41
+ PARSE_ERROR = -32700 # Invalid JSON was received
42
+ INVALID_REQUEST = -32600 # JSON is not a valid Request object
43
+ METHOD_NOT_FOUND = -32601 # Method does not exist / is not available
44
+ INVALID_PARAMS = -32602 # Invalid method parameter(s)
45
+ INTERNAL_ERROR = -32603 # Internal JSON-RPC error
46
+
47
+ # Server errors (reserved for implementation-defined errors)
48
+ SERVER_ERROR = -32000 # Generic server error
49
+
50
+
51
+ class McpMethod(str, Enum):
52
+ """Supported MCP method names."""
53
+
54
+ TOOLS_LIST = "tools/list"
55
+ TOOLS_CALL = "tools/call"
56
+
57
+
58
+ class JsonRpcError(BaseModel):
59
+ """
60
+ JSON-RPC 2.0 error object.
61
+
62
+ See: https://www.jsonrpc.org/specification#error_object
63
+ """
64
+
65
+ model_config = ConfigDict(extra="forbid")
66
+
67
+ code: int = Field(description="Error code indicating the error type")
68
+ message: str = Field(description="Short description of the error")
69
+ data: Optional[Any] = Field(
70
+ default=None, description="Additional error information"
71
+ )
72
+
73
+ @classmethod
74
+ def from_code(
75
+ cls, code: JsonRpcErrorCode, message: Optional[str] = None, data: Any = None
76
+ ) -> "JsonRpcError":
77
+ """Create an error from a standard error code."""
78
+ default_messages = {
79
+ JsonRpcErrorCode.PARSE_ERROR: "Parse error",
80
+ JsonRpcErrorCode.INVALID_REQUEST: "Invalid Request",
81
+ JsonRpcErrorCode.METHOD_NOT_FOUND: "Method not found",
82
+ JsonRpcErrorCode.INVALID_PARAMS: "Invalid params",
83
+ JsonRpcErrorCode.INTERNAL_ERROR: "Internal error",
84
+ JsonRpcErrorCode.SERVER_ERROR: "Server error",
85
+ }
86
+ return cls(
87
+ code=code.value,
88
+ message=message or default_messages.get(code, "Unknown error"),
89
+ data=data,
90
+ )
91
+
92
+
93
+ class JsonRpcRequest(BaseModel):
94
+ """
95
+ JSON-RPC 2.0 request object.
96
+
97
+ See: https://www.jsonrpc.org/specification#request_object
98
+ """
99
+
100
+ model_config = ConfigDict(extra="forbid")
101
+
102
+ jsonrpc: Literal["2.0"] = Field(description="JSON-RPC version, must be '2.0'")
103
+ method: str = Field(description="Name of the method to be invoked")
104
+ params: Dict[str, Any] = Field(
105
+ default_factory=dict, description="Parameter values for the method"
106
+ )
107
+ id: Optional[Union[str, int]] = Field(
108
+ default=None, description="Request identifier established by the client"
109
+ )
110
+
111
+
112
+ class JsonRpcResponse(BaseModel):
113
+ """
114
+ JSON-RPC 2.0 response object.
115
+
116
+ Per JSON-RPC 2.0 spec, a response has either 'result' or 'error', not both.
117
+ This model excludes None values during serialization to comply with the spec.
118
+
119
+ See: https://www.jsonrpc.org/specification#response_object
120
+ """
121
+
122
+ model_config = ConfigDict(extra="forbid")
123
+
124
+ jsonrpc: Literal["2.0"] = Field(default="2.0", description="JSON-RPC version")
125
+ result: Optional[Any] = Field(
126
+ default=None, description="Result of the method invocation"
127
+ )
128
+ error: Optional[JsonRpcError] = Field(
129
+ default=None, description="Error object if method invocation failed"
130
+ )
131
+ id: Optional[Union[str, int]] = Field(
132
+ default=None, description="Request identifier from the request"
133
+ )
134
+
135
+ def model_dump(self, **kwargs) -> Dict[str, Any]:
136
+ """Serialize to dict, excluding result or error when None (JSON-RPC compliance)."""
137
+ # Always include jsonrpc and id, but only include result OR error
138
+ data: Dict[str, Any] = {"jsonrpc": self.jsonrpc, "id": self.id}
139
+ if self.error is not None:
140
+ data["error"] = (
141
+ self.error.model_dump()
142
+ if hasattr(self.error, "model_dump")
143
+ else self.error
144
+ )
145
+ else:
146
+ # Only include result if there's no error
147
+ data["result"] = self.result
148
+ return data
149
+
150
+ def model_dump_json(self, **kwargs) -> str:
151
+ """Serialize to JSON string, excluding result or error when None (JSON-RPC compliance)."""
152
+ import json
153
+
154
+ return json.dumps(self.model_dump())
155
+
156
+ @classmethod
157
+ def success(
158
+ cls, result: Any, request_id: Optional[Union[str, int]] = None
159
+ ) -> "JsonRpcResponse":
160
+ """Create a success response."""
161
+ return cls(result=result, id=request_id)
162
+
163
+ @classmethod
164
+ def error_response(
165
+ cls,
166
+ code: JsonRpcErrorCode,
167
+ message: Optional[str] = None,
168
+ data: Any = None,
169
+ request_id: Optional[Union[str, int]] = None,
170
+ ) -> "JsonRpcResponse":
171
+ """Create an error response from a standard error code."""
172
+ return cls(
173
+ error=JsonRpcError.from_code(code, message, data),
174
+ id=request_id,
175
+ )
176
+
177
+
178
+ # =============================================================================
179
+ # MCP Tool Types
180
+ # =============================================================================
181
+
182
+
183
+ class Tool(BaseModel):
184
+ """
185
+ Strongly typed MCP tool specification.
186
+
187
+ Follows the MCP ToolSpec format for tool discovery.
188
+ See: https://modelcontextprotocol.io/specification/2025-06-18/server/tools
189
+ """
190
+
191
+ model_config = ConfigDict(extra="forbid")
192
+
193
+ name: str = Field(description="Unique identifier for the tool")
194
+ description: str = Field(
195
+ description="Human-readable description of what the tool does"
196
+ )
197
+ input_schema: Dict[str, Any] = Field(
198
+ description="JSON Schema for the tool's input parameters"
199
+ )
200
+
201
+
202
+ class ToolErrorType(str, Enum):
203
+ """Types of errors that can occur during tool execution."""
204
+
205
+ EXECUTION_ERROR = "execution_error" # Tool ran but failed
206
+ INVALID_ARGS = "invalid_args" # Invalid arguments provided
207
+ TRANSPORT_ERROR = "transport_error" # Communication failure
208
+ TOOL_NOT_FOUND = "tool_not_found" # Tool doesn't exist
209
+ TIMEOUT = "timeout" # Operation timed out
210
+
211
+
212
+ class ToolError(BaseModel):
213
+ """
214
+ Structured error for tool execution failures.
215
+
216
+ This is used for transport/framework errors, NOT for errors returned
217
+ by the tool itself (those go in the result field).
218
+ """
219
+
220
+ model_config = ConfigDict(extra="forbid")
221
+
222
+ error_type: ToolErrorType = Field(description="Category of the error")
223
+ message: str = Field(description="Human-readable error message")
224
+
225
+
226
+ # --- MCP Actions ---
227
+
228
+
229
+ class ListToolsAction(Action):
230
+ """
231
+ Request list of available tools from the environment.
232
+
233
+ This action triggers MCP's tools/list operation and returns
234
+ all available tools with their schemas.
235
+
236
+ Note: Does NOT require reset() to be called first.
237
+ """
238
+
239
+ type: Literal["list_tools"] = Field(
240
+ default="list_tools", description="Action type discriminator"
241
+ )
242
+
243
+
244
+ class CallToolAction(Action):
245
+ """
246
+ Call a specific tool via MCP.
247
+
248
+ This action triggers MCP's tools/call operation with the
249
+ specified tool name and arguments.
250
+ """
251
+
252
+ type: Literal["call_tool"] = Field(
253
+ default="call_tool", description="Action type discriminator"
254
+ )
255
+ tool_name: str = Field(description="Name of the tool to call")
256
+ arguments: Dict[str, Any] = Field(
257
+ default_factory=dict, description="Arguments to pass to the tool"
258
+ )
259
+
260
+
261
+ # --- MCP Observations ---
262
+
263
+
264
+ class ListToolsObservation(Observation):
265
+ """
266
+ Response containing available tools.
267
+
268
+ Returned when processing a ListToolsAction.
269
+ """
270
+
271
+ tools: List[Tool] = Field(description="List of available tools with their schemas")
272
+
273
+
274
+ class CallToolObservation(Observation):
275
+ """
276
+ Response from tool execution.
277
+
278
+ Contains the tool's result or an error if the call failed.
279
+ Tool-specific errors (from the tool itself) are included in the result.
280
+ Transport/framework errors use the error field.
281
+ """
282
+
283
+ tool_name: str = Field(description="Name of the tool that was called")
284
+ result: Any = Field(
285
+ default=None, description="Tool-specific result (may include tool errors)"
286
+ )
287
+ error: Optional[ToolError] = Field(
288
+ default=None, description="Transport/framework error if call failed"
289
+ )
290
+
291
+
292
+ # --- WebSocket Message Types for MCP ---
293
+
294
+
295
+ class WSMCPMessage(BaseMessage):
296
+ """
297
+ WebSocket message for MCP JSON-RPC requests.
298
+
299
+ Allows direct MCP access via WebSocket for production inference,
300
+ bypassing the step() API.
301
+ """
302
+
303
+ type: Literal["mcp"] = Field(default="mcp", description="Message type")
304
+ data: Dict[str, Any] = Field(description="JSON-RPC payload (method, params, id)")
305
+
306
+
307
+ class WSMCPResponse(BaseModel):
308
+ """
309
+ WebSocket response for MCP JSON-RPC.
310
+
311
+ Contains the JSON-RPC response from the MCP server.
312
+ """
313
+
314
+ model_config = ConfigDict(extra="forbid")
315
+
316
+ type: str = Field(default="mcp", description="Response type")
317
+ data: Dict[str, Any] = Field(description="JSON-RPC response payload")
318
+
319
+
320
+ # Reserved tool names that cannot be used (protects dual API boundary)
321
+ RESERVED_TOOL_NAMES = frozenset(["reset", "step", "state", "close"])
src/core/env_server/route_config.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Route configuration utilities for declarative FastAPI route registration.
9
+
10
+ This module provides utilities to reduce boilerplate in route registration
11
+ by using configuration objects instead of repeated function calls.
12
+ """
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Callable, List, Type
16
+
17
+ from fastapi import FastAPI
18
+ from pydantic import BaseModel
19
+
20
+
21
+ @dataclass
22
+ class GetEndpointConfig:
23
+ """Configuration for a simple GET endpoint."""
24
+
25
+ path: str
26
+ handler: Callable[[], BaseModel | dict]
27
+ response_model: Type[BaseModel] | type[dict]
28
+ tag: str
29
+ summary: str
30
+ description: str
31
+
32
+
33
+ def register_get_endpoints(app: FastAPI, configs: List[GetEndpointConfig]) -> None:
34
+ """
35
+ Register multiple GET endpoints from configuration.
36
+
37
+ Args:
38
+ app: FastAPI application instance
39
+ configs: List of GET endpoint configurations
40
+ """
41
+ for config in configs:
42
+ # Capture handler in a closure to avoid non-serializable default parameter
43
+ def make_endpoint(
44
+ handler: Callable[[], BaseModel | dict],
45
+ ) -> Callable[[], BaseModel | dict]:
46
+ async def endpoint() -> BaseModel | dict:
47
+ return handler()
48
+
49
+ return endpoint
50
+
51
+ app.get(
52
+ config.path,
53
+ response_model=config.response_model,
54
+ tags=[config.tag],
55
+ summary=config.summary,
56
+ description=config.description,
57
+ )(make_endpoint(config.handler))
src/core/env_server/serialization.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Shared serialization and deserialization utilities for OpenEnv HTTP servers.
9
+
10
+ This module provides common utilities for converting between JSON dictionaries
11
+ and Pydantic models (Action/Observation) to eliminate code duplication across
12
+ HTTP server and web interface implementations.
13
+ """
14
+
15
+ from typing import Any, Dict, Type
16
+
17
+ from .types import Action, Observation
18
+
19
+
20
+ def deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:
21
+ """
22
+ Convert JSON dict to Action instance using Pydantic validation.
23
+
24
+ This is a basic deserialization that works for most environments.
25
+ For special cases (e.g., tensor fields, custom type conversions),
26
+ use deserialize_action_with_preprocessing().
27
+
28
+ Args:
29
+ action_data: Dictionary containing action data
30
+ action_cls: The Action subclass to instantiate
31
+
32
+ Returns:
33
+ Action instance
34
+
35
+ Raises:
36
+ ValidationError: If action_data is invalid for the action class
37
+
38
+ Note:
39
+ This uses Pydantic's model_validate() for automatic validation.
40
+ """
41
+ return action_cls.model_validate(action_data)
42
+
43
+
44
+ def deserialize_action_with_preprocessing(
45
+ action_data: Dict[str, Any], action_cls: Type[Action]
46
+ ) -> Action:
47
+ """
48
+ Convert JSON dict to Action instance with preprocessing for special types.
49
+
50
+ This version handles common type conversions needed for web interfaces:
51
+ - Converting lists/strings to tensors for 'tokens' field
52
+ - Converting string action_id to int
53
+ - Other custom preprocessing as needed
54
+
55
+ Args:
56
+ action_data: Dictionary containing action data
57
+ action_cls: The Action subclass to instantiate
58
+
59
+ Returns:
60
+ Action instance
61
+
62
+ Raises:
63
+ ValidationError: If action_data is invalid for the action class
64
+ """
65
+ processed_data = {}
66
+
67
+ for key, value in action_data.items():
68
+ if key == "tokens" and isinstance(value, (list, str)):
69
+ # Convert list or string to tensor
70
+ if isinstance(value, str):
71
+ # If it's a string, try to parse it as a list of numbers
72
+ try:
73
+ import json
74
+
75
+ value = json.loads(value)
76
+ except Exception:
77
+ # If parsing fails, treat as empty list
78
+ value = []
79
+ if isinstance(value, list):
80
+ try:
81
+ import torch # type: ignore
82
+
83
+ processed_data[key] = torch.tensor(value, dtype=torch.long)
84
+ except ImportError:
85
+ # If torch not available, keep as list
86
+ processed_data[key] = value
87
+ else:
88
+ processed_data[key] = value
89
+ elif key == "action_id" and isinstance(value, str):
90
+ # Convert action_id from string to int
91
+ try:
92
+ processed_data[key] = int(value)
93
+ except ValueError:
94
+ # If conversion fails, keep original value
95
+ processed_data[key] = value
96
+ else:
97
+ processed_data[key] = value
98
+
99
+ return action_cls.model_validate(processed_data)
100
+
101
+
102
+ def serialize_observation(observation: Observation) -> Dict[str, Any]:
103
+ """
104
+ Convert Observation instance to JSON-compatible dict using Pydantic.
105
+
106
+ Args:
107
+ observation: Observation instance
108
+
109
+ Returns:
110
+ Dictionary compatible with EnvClient._parse_result()
111
+
112
+ The format matches what EnvClient expects:
113
+ {
114
+ "observation": {...}, # Observation fields
115
+ "reward": float | None,
116
+ "done": bool,
117
+ }
118
+ """
119
+ # Use Pydantic's model_dump() for serialization
120
+ obs_dict = observation.model_dump(
121
+ exclude={
122
+ "reward",
123
+ "done",
124
+ "metadata",
125
+ } # Exclude these from observation dict
126
+ )
127
+
128
+ # Extract reward and done directly from the observation
129
+ reward = observation.reward
130
+ done = observation.done
131
+
132
+ # Return in EnvClient expected format
133
+ return {
134
+ "observation": obs_dict,
135
+ "reward": reward,
136
+ "done": done,
137
+ }
src/core/env_server/types.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from enum import Enum
8
+ from typing import Any, Dict, Optional, Union, Literal, Annotated
9
+ from pydantic import BaseModel, Field, ConfigDict, model_validator
10
+
11
+
12
+ # Type aliases
13
+ Scalar = Union[int, float, bool]
14
+
15
+
16
+ # =============================================================================
17
+ # Enums for Type Safety
18
+ # =============================================================================
19
+
20
+
21
+ class ServerMode(str, Enum):
22
+ """Server operation mode."""
23
+
24
+ SIMULATION = "simulation"
25
+ PRODUCTION = "production"
26
+
27
+
28
+ class HealthStatus(str, Enum):
29
+ """Server health status values."""
30
+
31
+ HEALTHY = "healthy"
32
+ UNHEALTHY = "unhealthy"
33
+ DEGRADED = "degraded"
34
+
35
+
36
+ class WSErrorCode(str, Enum):
37
+ """WebSocket error codes for structured error handling."""
38
+
39
+ INVALID_JSON = "INVALID_JSON"
40
+ UNKNOWN_TYPE = "UNKNOWN_TYPE"
41
+ VALIDATION_ERROR = "VALIDATION_ERROR"
42
+ EXECUTION_ERROR = "EXECUTION_ERROR"
43
+ CAPACITY_REACHED = "CAPACITY_REACHED"
44
+ FACTORY_ERROR = "FACTORY_ERROR"
45
+ SESSION_ERROR = "SESSION_ERROR"
46
+
47
+
48
+ # =============================================================================
49
+ # Core Types
50
+ # =============================================================================
51
+
52
+
53
+ class Action(BaseModel):
54
+ """Base class for all environment actions.
55
+
56
+ All action subclasses should inherit from this base class.
57
+ Uses Pydantic for automatic validation and serialization.
58
+ """
59
+
60
+ model_config = ConfigDict(
61
+ extra="forbid", # Reject unknown fields
62
+ validate_assignment=True, # Validate on field assignment
63
+ arbitrary_types_allowed=True, # Allow numpy arrays, torch tensors, etc.
64
+ )
65
+
66
+ metadata: Dict[str, Any] = Field(
67
+ default_factory=dict, description="Additional metadata for the action"
68
+ )
69
+
70
+
71
+ class Observation(BaseModel):
72
+ """Base class for all environment observations.
73
+
74
+ All observation subclasses should inherit from this base class.
75
+ Uses Pydantic for automatic validation and serialization.
76
+ """
77
+
78
+ model_config = ConfigDict(
79
+ extra="forbid",
80
+ validate_assignment=True,
81
+ arbitrary_types_allowed=True,
82
+ )
83
+
84
+ done: bool = Field(default=False, description="Whether the episode has terminated")
85
+ reward: bool | int | float | None = Field(
86
+ default=None, description="Reward signal from the last action"
87
+ )
88
+ metadata: Dict[str, Any] = Field(
89
+ default_factory=dict, description="Additional metadata for the observation"
90
+ )
91
+
92
+
93
+ class ResetRequest(BaseModel):
94
+ """Request model for environment reset."""
95
+
96
+ model_config = ConfigDict(
97
+ extra="allow", # Allow extra fields for custom reset parameters
98
+ json_schema_extra={"examples": [{"seed": 42, "episode_id": "episode-001"}, {}]},
99
+ )
100
+
101
+ seed: Optional[int] = Field(
102
+ default=None, ge=0, description="Random seed for reproducible episodes"
103
+ )
104
+ episode_id: Optional[str] = Field(
105
+ default=None, max_length=255, description="Custom episode identifier"
106
+ )
107
+
108
+
109
+ class ResetResponse(BaseModel):
110
+ """Response model for environment reset."""
111
+
112
+ model_config = ConfigDict(extra="forbid")
113
+
114
+ observation: Dict[str, Any] = Field(
115
+ ..., description="Initial observation from the environment"
116
+ )
117
+ reward: Optional[float] = Field(
118
+ default=None, description="Initial reward (typically None at reset)"
119
+ )
120
+ done: bool = Field(
121
+ default=False, description="Whether episode is already done (typically False)"
122
+ )
123
+
124
+
125
+ class StepRequest(BaseModel):
126
+ """Request model for environment step."""
127
+
128
+ model_config = ConfigDict(
129
+ extra="allow", # Allow extra fields for custom step parameters
130
+ json_schema_extra={
131
+ "examples": [
132
+ {"action": {"value": 1}, "timeout_s": 30.0},
133
+ {"action": {"value": 1}, "render": True, "verbose": False},
134
+ ]
135
+ },
136
+ )
137
+
138
+ action: Dict[str, Any] = Field(
139
+ ...,
140
+ description="Action to execute, must conform to environment's action schema",
141
+ )
142
+ timeout_s: Optional[float] = Field(
143
+ default=None,
144
+ gt=0,
145
+ description="Optional timeout in seconds for action execution",
146
+ )
147
+ request_id: Optional[str] = Field(
148
+ default=None,
149
+ max_length=255,
150
+ description="Optional request identifier for tracking",
151
+ )
152
+
153
+
154
+ class StepResponse(BaseModel):
155
+ """Response model for environment step."""
156
+
157
+ model_config = ConfigDict(extra="forbid")
158
+
159
+ observation: Dict[str, Any] = Field(
160
+ ..., description="Observation resulting from the action"
161
+ )
162
+ reward: Optional[float] = Field(
163
+ default=None, description="Reward signal from the action"
164
+ )
165
+ done: bool = Field(default=False, description="Whether the episode has terminated")
166
+
167
+
168
+ class BaseMessage(BaseModel):
169
+ """Base class for WebSocket messages with shared configuration."""
170
+
171
+ model_config = ConfigDict(
172
+ extra="forbid",
173
+ validate_assignment=True,
174
+ )
175
+
176
+
177
+ class State(BaseModel):
178
+ """Base class for environment state.
179
+
180
+ Represents internal environment state, separate from observations.
181
+ """
182
+
183
+ model_config = ConfigDict(
184
+ extra="allow", # Allow extra fields for flexibility
185
+ validate_assignment=True,
186
+ arbitrary_types_allowed=True,
187
+ )
188
+
189
+ episode_id: Optional[str] = Field(
190
+ default=None, description="Unique identifier for the current episode"
191
+ )
192
+ step_count: int = Field(
193
+ default=0,
194
+ ge=0, # Greater than or equal to 0
195
+ description="Number of steps taken in the current episode",
196
+ )
197
+
198
+
199
+ class CodeExecResult(BaseMessage):
200
+ """Result of code execution containing stdout, stderr, and exit code."""
201
+
202
+ stdout: str = Field(description="Standard output from code execution")
203
+ stderr: str = Field(description="Standard error from code execution")
204
+ exit_code: int = Field(description="Exit code from code execution")
205
+
206
+
207
+ class EnvironmentMetadata(BaseMessage):
208
+ """Metadata about an environment for documentation and UI purposes."""
209
+
210
+ name: str = Field(description="Name of the environment")
211
+ description: str = Field(description="Description of what the environment does")
212
+ readme_content: Optional[str] = Field(
213
+ default=None, description="Content of the README file for the environment"
214
+ )
215
+ version: Optional[str] = Field(
216
+ default=None, description="Version of the environment"
217
+ )
218
+ author: Optional[str] = Field(default=None, description="Author of the environment")
219
+ documentation_url: Optional[str] = Field(
220
+ default=None, description="URL to the environment's documentation"
221
+ )
222
+
223
+
224
+ class SchemaResponse(BaseMessage):
225
+ """Response model for the combined schema endpoint."""
226
+
227
+ action: Dict[str, Any] = Field(
228
+ description="JSON schema for actions accepted by this environment"
229
+ )
230
+ observation: Dict[str, Any] = Field(
231
+ description="JSON schema for observations returned by this environment"
232
+ )
233
+ state: Dict[str, Any] = Field(
234
+ description="JSON schema for environment state objects"
235
+ )
236
+
237
+
238
+ class HealthResponse(BaseMessage):
239
+ """Response model for health check endpoint."""
240
+
241
+ status: HealthStatus = Field(
242
+ default=HealthStatus.HEALTHY,
243
+ description="Health status of the environment server",
244
+ )
245
+
246
+
247
+ class WSResetMessage(BaseMessage):
248
+ """WebSocket message to reset the environment."""
249
+
250
+ type: Literal["reset"] = Field(default="reset", description="Message type")
251
+ data: Dict[str, Any] = Field(
252
+ default_factory=dict,
253
+ description="Optional reset parameters (seed, episode_id, etc.)",
254
+ )
255
+
256
+
257
+ class WSStepMessage(BaseMessage):
258
+ """WebSocket message to execute a step."""
259
+
260
+ type: Literal["step"] = Field(default="step", description="Message type")
261
+ data: Dict[str, Any] = Field(
262
+ ..., description="Action data conforming to environment's action schema"
263
+ )
264
+
265
+
266
+ class WSStateMessage(BaseMessage):
267
+ """WebSocket message to request current state."""
268
+
269
+ type: Literal["state"] = Field(default="state", description="Message type")
270
+
271
+
272
+ class WSCloseMessage(BaseMessage):
273
+ """WebSocket message to close the session."""
274
+
275
+ type: Literal["close"] = Field(default="close", description="Message type")
276
+
277
+
278
+ # Discriminated union for incoming WebSocket messages
279
+ # Note: WSMCPMessage is defined in mcp_types.py to avoid circular imports
280
+ # The union here covers the core message types; MCP messages are handled separately
281
+ WSIncomingMessage = Annotated[
282
+ WSResetMessage | WSStepMessage | WSStateMessage | WSCloseMessage,
283
+ Field(discriminator="type"),
284
+ ]
285
+
286
+
287
+ class WSObservationResponse(BaseModel):
288
+ """WebSocket response containing an observation."""
289
+
290
+ model_config = ConfigDict(extra="forbid")
291
+
292
+ type: Literal["observation"] = Field(
293
+ default="observation", description="Response type"
294
+ )
295
+ data: Dict[str, Any] = Field(description="Observation data")
296
+
297
+
298
+ class WSStateResponse(BaseModel):
299
+ """WebSocket response containing environment state."""
300
+
301
+ model_config = ConfigDict(extra="forbid")
302
+
303
+ type: Literal["state"] = Field(default="state", description="Response type")
304
+ data: Dict[str, Any] = Field(description="State data")
305
+
306
+
307
+ class WSErrorResponse(BaseModel):
308
+ """WebSocket response for errors."""
309
+
310
+ model_config = ConfigDict(extra="forbid")
311
+
312
+ type: Literal["error"] = Field(default="error", description="Response type")
313
+ data: Dict[str, Any] = Field(description="Error details including message and code")
314
+
315
+
316
+ class ConcurrencyConfig(BaseMessage):
317
+ """Configuration for concurrent environment sessions."""
318
+
319
+ max_concurrent_envs: int = Field(
320
+ default=1,
321
+ ge=1,
322
+ description="Maximum number of concurrent WebSocket sessions allowed",
323
+ )
324
+ session_timeout: Optional[float] = Field(
325
+ default=None,
326
+ gt=0,
327
+ description="Timeout in seconds for inactive sessions. None means no timeout.",
328
+ )
329
+
330
+
331
+ class ServerCapacityStatus(BaseMessage):
332
+ """Status of server capacity for concurrent sessions."""
333
+
334
+ active_sessions: int = Field(
335
+ ge=0,
336
+ description="Number of currently active sessions",
337
+ )
338
+ max_sessions: int = Field(
339
+ ge=1,
340
+ description="Maximum number of allowed sessions",
341
+ )
342
+
343
+ @model_validator(mode="after")
344
+ def check_capacity_bounds(self) -> "ServerCapacityStatus":
345
+ if self.active_sessions > self.max_sessions:
346
+ raise ValueError(
347
+ f"active_sessions ({self.active_sessions}) cannot exceed "
348
+ f"max_sessions ({self.max_sessions})"
349
+ )
350
+ return self
351
+
352
+ @property
353
+ def available_slots(self) -> int:
354
+ """Number of available session slots."""
355
+ return self.max_sessions - self.active_sessions
356
+
357
+ @property
358
+ def is_at_capacity(self) -> bool:
359
+ """Whether the server has reached maximum capacity."""
360
+ return self.available_slots == 0
361
+
362
+ @classmethod
363
+ def from_counts(cls, active: int, max_sessions: int) -> "ServerCapacityStatus":
364
+ """Create status from active and max session counts."""
365
+ return cls(
366
+ active_sessions=active,
367
+ max_sessions=max_sessions,
368
+ )
369
+
370
+
371
+ class SessionInfo(BaseMessage):
372
+ """Information about an active session."""
373
+
374
+ session_id: str = Field(description="Unique identifier for the session")
375
+ created_at: float = Field(description="Unix timestamp when the session was created")
376
+ last_activity_at: float = Field(
377
+ description="Unix timestamp of the last activity in the session"
378
+ )
379
+ step_count: int = Field(
380
+ default=0,
381
+ ge=0,
382
+ description="Number of steps executed in this session",
383
+ )
384
+ environment_type: str = Field(
385
+ description="Environment type for this session (e.g. `CodingEnv`)"
386
+ )
src/core/env_server/web_interface.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Web interface for OpenEnv environments.
9
+
10
+ When ENABLE_WEB_INTERFACE is set, the server exposes a Gradio UI at /web for
11
+ reset, step, and state observation. Controlled by the CLI enable_interface
12
+ option (e.g. openenv push --enable-interface) or ENABLE_WEB_INTERFACE env var.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import json
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from datetime import datetime
21
+ from typing import Any, Callable, Dict, List, Optional, Type
22
+
23
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
24
+ import gradio as gr
25
+ from pydantic import BaseModel, ConfigDict, Field
26
+
27
+ from .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME
28
+ from .gradio_ui import build_gradio_app, get_gradio_display_title
29
+ from .interfaces import Environment
30
+ from .serialization import deserialize_action_with_preprocessing, serialize_observation
31
+ from .types import Action, EnvironmentMetadata, Observation, State
32
+
33
+ # Quick Start markdown template; placeholders match init suffixes (__ENV_NAME__, __ENV_CLASS_NAME__*).
34
+ DEFAULT_QUICK_START_MARKDOWN = """
35
+ ### Connect to this environment
36
+
37
+ Connect from Python using `__ENV_CLASS_NAME__Env`:
38
+
39
+ ```python
40
+ from __ENV_NAME__ import __ENV_CLASS_NAME__Action, __ENV_CLASS_NAME__Env
41
+
42
+ with __ENV_CLASS_NAME__Env.from_env("<SPACE_ID>") as env:
43
+ result = await env.step(__ENV_CLASS_NAME__Action(message="..."))
44
+ ```
45
+
46
+ Or connect directly to a running server:
47
+
48
+ ```python
49
+ env = __ENV_CLASS_NAME__Env(base_url="http://localhost:8000")
50
+ ```
51
+
52
+ ### Contribute to this environment
53
+
54
+ Submit improvements via pull request on the Hugging Face Hub.
55
+
56
+ ```bash
57
+ openenv fork <SPACE_ID> --repo-id <your-username>/<your-repo-name>
58
+ ```
59
+
60
+ Then make your changes and submit a pull request:
61
+
62
+ ```bash
63
+ cd <forked-repo>
64
+ openenv push <SPACE_ID> --create-pr
65
+ ```
66
+
67
+ For more information, see the [OpenEnv documentation](https://meta-pytorch.org/OpenEnv/).
68
+ """
69
+
70
+
71
+ def get_quick_start_markdown(
72
+ metadata: Optional[EnvironmentMetadata],
73
+ action_cls: Type[Action],
74
+ observation_cls: Type[Observation],
75
+ ) -> str:
76
+ """
77
+ Build Quick Start markdown with class names replaced from current env (init-style suffixes).
78
+
79
+ Uses the same placeholder names as the init template so that __ENV_CLASS_NAME__Env,
80
+ __ENV_CLASS_NAME__Action, __ENV_CLASS_NAME__Observation and __ENV_NAME__ are
81
+ replaced with the actual class/package names.
82
+ """
83
+ import os
84
+
85
+ # Prefix from action class (e.g. EchoAction -> Echo)
86
+ action_name = getattr(action_cls, "__name__", "Action")
87
+ if action_name.endswith("Action"):
88
+ prefix = action_name[: -len("Action")]
89
+ else:
90
+ prefix = action_name.replace("Action", "").strip() or "Env"
91
+
92
+ env_client_name = f"{prefix}Env"
93
+ obs_name = getattr(observation_cls, "__name__", "Observation")
94
+ pkg_name = (metadata.name if metadata else "env").replace(" ", "_").lower()
95
+
96
+ space_id = os.environ.get("SPACE_ID", "<hf-username>/<hf-repo-name>")
97
+
98
+ content = DEFAULT_QUICK_START_MARKDOWN
99
+ content = content.replace("__ENV_CLASS_NAME__Env", env_client_name)
100
+ content = content.replace("__ENV_CLASS_NAME__Action", action_name)
101
+ content = content.replace("__ENV_CLASS_NAME__Observation", obs_name)
102
+ content = content.replace("__ENV_CLASS_NAME__", prefix)
103
+ content = content.replace("__ENV_NAME__", pkg_name)
104
+ content = content.replace("<SPACE_ID>", space_id)
105
+ return content.strip()
106
+
107
+
108
+ def load_environment_metadata(
109
+ env: Environment, env_name: Optional[str] = None
110
+ ) -> EnvironmentMetadata:
111
+ """
112
+ Load environment metadata including README content.
113
+
114
+ Args:
115
+ env: The environment instance, class, or factory function.
116
+ - If a class: used as a factory, won't call instance methods
117
+ - If a function: used as a factory, won't call instance methods
118
+ - If an instance: may call get_metadata() if available
119
+ env_name: Optional environment name for README file lookup
120
+
121
+ Returns:
122
+ EnvironmentMetadata with loaded information
123
+ """
124
+ import inspect
125
+
126
+ # Determine what type of env we received:
127
+ # 1. A class (used as factory) - e.g., PythonCodeActEnv
128
+ # 2. A function (factory function) - e.g., create_chat_environment
129
+ # 3. An actual instance - e.g., SnakeEnvironment()
130
+ is_class = inspect.isclass(env)
131
+ is_function = inspect.isfunction(env) or inspect.ismethod(env)
132
+ is_factory = is_class or is_function
133
+
134
+ # Try to get metadata from environment if it's an instance with get_metadata
135
+ if not is_factory and hasattr(env, "get_metadata"):
136
+ return env.get_metadata()
137
+
138
+ # Determine the class name for default metadata
139
+ if is_class:
140
+ # env is the class itself
141
+ class_name = env.__name__
142
+ elif is_function:
143
+ # env is a factory function - use its name or derive from env_name
144
+ class_name = env_name or env.__name__
145
+ else:
146
+ # env is an instance
147
+ class_name = env.__class__.__name__
148
+
149
+ # Default metadata
150
+ metadata = EnvironmentMetadata(
151
+ name=env_name or class_name,
152
+ description=f"{class_name} environment",
153
+ version="1.0.0",
154
+ )
155
+
156
+ # Try to load README from file system
157
+ readme_content = _load_readme_from_filesystem(env_name)
158
+ if readme_content:
159
+ metadata.readme_content = readme_content
160
+
161
+ return metadata
162
+
163
+
164
+ def _load_readme_from_filesystem(env_name: Optional[str]) -> Optional[str]:
165
+ """
166
+ Load README content from the filesystem.
167
+
168
+ Tries multiple locations:
169
+ 1. Container filesystem: /app/README.md
170
+ 2. Local development: src/envs/{env_name}/README.md
171
+ 3. Environment variable: ENV_README_PATH
172
+ """
173
+ import os
174
+ from pathlib import Path
175
+
176
+ # Try container filesystem first
177
+ container_readme = Path("/app/README.md")
178
+ if container_readme.exists():
179
+ try:
180
+ return container_readme.read_text(encoding="utf-8")
181
+ except Exception:
182
+ pass
183
+
184
+ # Try environment variable path
185
+ custom_path = os.environ.get("ENV_README_PATH")
186
+ if custom_path and Path(custom_path).exists():
187
+ try:
188
+ return Path(custom_path).read_text(encoding="utf-8")
189
+ except Exception:
190
+ pass
191
+
192
+ # Try local development path
193
+ if env_name:
194
+ local_readme = Path(f"src/envs/{env_name}/README.md")
195
+ if local_readme.exists():
196
+ try:
197
+ return local_readme.read_text(encoding="utf-8")
198
+ except Exception:
199
+ pass
200
+
201
+ return None
202
+
203
+
204
+ class ActionLog(BaseModel):
205
+ """Log entry for an action taken."""
206
+
207
+ model_config = ConfigDict(extra="forbid", validate_assignment=True)
208
+
209
+ timestamp: str = Field(description="Timestamp when action was taken")
210
+ action: Dict[str, Any] = Field(description="Action that was taken")
211
+ observation: Dict[str, Any] = Field(description="Observation returned from action")
212
+ reward: Optional[float] = Field(
213
+ default=None, description="Reward received from action"
214
+ )
215
+ done: bool = Field(description="Whether the episode is done after this action")
216
+ step_count: int = Field(description="Step count when this action was taken")
217
+
218
+
219
+ class EpisodeState(BaseModel):
220
+ """Current episode state for the web interface."""
221
+
222
+ model_config = ConfigDict(extra="forbid", validate_assignment=True)
223
+
224
+ episode_id: Optional[str] = Field(default=None, description="Current episode ID")
225
+ step_count: int = Field(description="Current step count in episode")
226
+ current_observation: Optional[Dict[str, Any]] = Field(
227
+ default=None, description="Current observation"
228
+ )
229
+ action_logs: List[ActionLog] = Field(
230
+ default_factory=list, description="List of action logs"
231
+ )
232
+ is_reset: bool = Field(
233
+ default=True, description="Whether the episode has been reset"
234
+ )
235
+
236
+
237
+ class WebInterfaceManager:
238
+ """Manages the web interface for an environment."""
239
+
240
+ MAX_ACTION_LOGS = 1000
241
+
242
+ def __init__(
243
+ self,
244
+ env: Environment,
245
+ action_cls: Type[Action],
246
+ observation_cls: Type[Observation],
247
+ metadata: Optional[EnvironmentMetadata] = None,
248
+ ):
249
+ import inspect
250
+
251
+ # If env is a class or factory function, instantiate it
252
+ if inspect.isclass(env) or inspect.isfunction(env):
253
+ self.env = env()
254
+ else:
255
+ self.env = env
256
+ self.action_cls = action_cls
257
+ self.observation_cls = observation_cls
258
+ self.metadata = metadata or EnvironmentMetadata(
259
+ name=env.__class__.__name__,
260
+ description=f"{env.__class__.__name__} environment",
261
+ )
262
+ self.episode_state = EpisodeState(
263
+ episode_id=None,
264
+ step_count=0,
265
+ current_observation=None,
266
+ action_logs=[],
267
+ )
268
+ self.connected_clients: List[WebSocket] = []
269
+ # Thread pool for running sync code (e.g., Playwright sync API) in async context
270
+ self._executor = ThreadPoolExecutor(max_workers=1)
271
+
272
+ async def _run_sync_in_thread_pool(self, func, *args, **kwargs):
273
+ """Run a synchronous function in the thread pool executor.
274
+
275
+ This is needed for environments using sync libraries (e.g., Playwright sync API)
276
+ that cannot be called directly from an async context.
277
+ """
278
+ loop = asyncio.get_event_loop()
279
+ # Use default arguments to capture values at lambda definition time
280
+ # to avoid closure issues with late binding
281
+ return await loop.run_in_executor(
282
+ self._executor, lambda f=func, a=args, kw=kwargs: f(*a, **kw)
283
+ )
284
+
285
+ async def connect_websocket(self, websocket: WebSocket):
286
+ """Connect a new WebSocket client."""
287
+ await websocket.accept()
288
+ self.connected_clients.append(websocket)
289
+
290
+ # Send current state to the new client
291
+ await self._send_state_update()
292
+
293
+ async def disconnect_websocket(self, websocket: WebSocket):
294
+ """Disconnect a WebSocket client."""
295
+ if websocket in self.connected_clients:
296
+ self.connected_clients.remove(websocket)
297
+
298
+ async def _send_state_update(self):
299
+ """Send current state to all connected clients."""
300
+ if not self.connected_clients:
301
+ return
302
+
303
+ state_data = {
304
+ "type": "state_update",
305
+ "episode_state": self.episode_state.model_dump(),
306
+ }
307
+
308
+ # Send to all connected clients
309
+ disconnected_clients = []
310
+ for client in self.connected_clients:
311
+ try:
312
+ await client.send_text(json.dumps(state_data))
313
+ except Exception:
314
+ disconnected_clients.append(client)
315
+
316
+ # Remove disconnected clients
317
+ for client in disconnected_clients:
318
+ self.connected_clients.remove(client)
319
+
320
+ async def reset_environment(self) -> Dict[str, Any]:
321
+ """Reset the environment and update state."""
322
+ # Run sync reset in thread pool to avoid blocking event loop
323
+ # and to support environments using sync libraries (e.g., Playwright)
324
+ observation: Observation = await self._run_sync_in_thread_pool(self.env.reset)
325
+ state: State = self.env.state
326
+
327
+ # Serialize observation once using shared utility
328
+ serialized = serialize_observation(observation)
329
+
330
+ # Update episode state
331
+ self.episode_state.episode_id = state.episode_id
332
+ self.episode_state.step_count = 0
333
+ self.episode_state.current_observation = serialized["observation"]
334
+ self.episode_state.action_logs = []
335
+ self.episode_state.is_reset = True
336
+
337
+ # Send state update
338
+ await self._send_state_update()
339
+
340
+ return serialized
341
+
342
+ async def step_environment(self, action_data: Dict[str, Any]) -> Dict[str, Any]:
343
+ """Execute a step in the environment and update state."""
344
+ # Deserialize action with preprocessing for web interface special cases
345
+ action: Action = deserialize_action_with_preprocessing(
346
+ action_data, self.action_cls
347
+ )
348
+
349
+ # Run sync step in thread pool to avoid blocking event loop
350
+ # and to support environments using sync libraries (e.g., Playwright)
351
+ observation: Observation = await self._run_sync_in_thread_pool(
352
+ self.env.step, action
353
+ )
354
+ state: State = self.env.state
355
+
356
+ # Serialize observation once using shared utility
357
+ serialized = serialize_observation(observation)
358
+
359
+ # Create action log
360
+ action_log = ActionLog(
361
+ timestamp=datetime.now().isoformat(),
362
+ action=action.model_dump(exclude={"metadata"}),
363
+ observation=serialized["observation"],
364
+ reward=observation.reward,
365
+ done=observation.done,
366
+ step_count=state.step_count,
367
+ )
368
+
369
+ # Update episode state
370
+ self.episode_state.episode_id = state.episode_id
371
+ self.episode_state.step_count = state.step_count
372
+ self.episode_state.current_observation = serialized["observation"]
373
+ self.episode_state.action_logs.append(action_log)
374
+ if len(self.episode_state.action_logs) > self.MAX_ACTION_LOGS:
375
+ self.episode_state.action_logs = self.episode_state.action_logs[
376
+ -self.MAX_ACTION_LOGS :
377
+ ]
378
+ self.episode_state.is_reset = False
379
+
380
+ # Send state update
381
+ await self._send_state_update()
382
+
383
+ return serialized
384
+
385
+ def get_state(self) -> Dict[str, Any]:
386
+ """Get current environment state."""
387
+ state: State = self.env.state
388
+ return state.model_dump()
389
+
390
+
391
+ def create_web_interface_app(
392
+ env: Environment,
393
+ action_cls: Type[Action],
394
+ observation_cls: Type[Observation],
395
+ env_name: Optional[str] = None,
396
+ max_concurrent_envs: Optional[int] = None,
397
+ concurrency_config: Optional[Any] = None,
398
+ gradio_builder: Optional[Callable[..., Any]] = None,
399
+ ) -> FastAPI:
400
+ """
401
+ Create a FastAPI application with web interface for the given environment.
402
+
403
+ Args:
404
+ env: The Environment instance to serve
405
+ action_cls: The Action subclass this environment expects
406
+ observation_cls: The Observation subclass this environment returns
407
+ env_name: Optional environment name for README loading
408
+ max_concurrent_envs: Maximum concurrent WebSocket sessions
409
+ concurrency_config: Optional ConcurrencyConfig for advanced concurrency settings
410
+ gradio_builder: Optional callable (web_manager, action_fields, metadata,
411
+ is_chat_env, title, quick_start_md) -> gr.Blocks to use instead of the
412
+ default Gradio UI. Lets envs replace or customize the /web interface.
413
+
414
+ Returns:
415
+ FastAPI application instance with web interface
416
+ """
417
+ from .http_server import create_fastapi_app
418
+
419
+ # Create the base environment app
420
+ app = create_fastapi_app(
421
+ env, action_cls, observation_cls, max_concurrent_envs, concurrency_config
422
+ )
423
+
424
+ # Load environment metadata
425
+ metadata = load_environment_metadata(env, env_name)
426
+
427
+ # Create web interface manager
428
+ web_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)
429
+
430
+ # Web API routes first (so they take precedence over Gradio mount at /web)
431
+ @app.get("/web/metadata")
432
+ async def web_metadata():
433
+ """Get environment metadata."""
434
+ return web_manager.metadata.model_dump()
435
+
436
+ @app.websocket("/ws/ui")
437
+ async def websocket_ui_endpoint(websocket: WebSocket):
438
+ """WebSocket endpoint for web UI real-time updates.
439
+
440
+ Note: Uses /ws/ui to avoid conflict with /ws in http_server.py
441
+ which is used for concurrent environment sessions.
442
+ """
443
+ await web_manager.connect_websocket(websocket)
444
+ try:
445
+ while True:
446
+ # Keep connection alive
447
+ await websocket.receive_text()
448
+ except WebSocketDisconnect:
449
+ await web_manager.disconnect_websocket(websocket)
450
+
451
+ @app.post("/web/reset")
452
+ async def web_reset():
453
+ """Reset endpoint for web interface."""
454
+ return await web_manager.reset_environment()
455
+
456
+ @app.post("/web/step")
457
+ async def web_step(request: Dict[str, Any]):
458
+ """Step endpoint for web interface."""
459
+ # Check if this is a message-based request (chat environment)
460
+ if "message" in request:
461
+ message = request["message"]
462
+ if hasattr(web_manager.env, "message_to_action"):
463
+ action = web_manager.env.message_to_action(message)
464
+ if hasattr(action, "tokens"):
465
+ action_data = {"tokens": action.tokens.tolist()}
466
+ else:
467
+ action_data = action.model_dump(exclude={"metadata"})
468
+ else:
469
+ action_data = {"message": message}
470
+ else:
471
+ action_data = request.get("action", {})
472
+
473
+ return await web_manager.step_environment(action_data)
474
+
475
+ @app.get("/web/state")
476
+ async def web_state():
477
+ """State endpoint for web interface."""
478
+ return web_manager.get_state()
479
+
480
+ action_fields = _extract_action_fields(action_cls)
481
+ is_chat_env = _is_chat_env(action_cls)
482
+ quick_start_md = get_quick_start_markdown(metadata, action_cls, observation_cls)
483
+
484
+ default_blocks = build_gradio_app(
485
+ web_manager,
486
+ action_fields,
487
+ metadata,
488
+ is_chat_env,
489
+ title=metadata.name,
490
+ quick_start_md=quick_start_md,
491
+ )
492
+ if gradio_builder is not None:
493
+ custom_blocks = gradio_builder(
494
+ web_manager,
495
+ action_fields,
496
+ metadata,
497
+ is_chat_env,
498
+ metadata.name,
499
+ quick_start_md,
500
+ )
501
+ if not isinstance(custom_blocks, gr.Blocks):
502
+ raise TypeError(
503
+ f"gradio_builder must return a gr.Blocks instance, "
504
+ f"got {type(custom_blocks).__name__}"
505
+ )
506
+ gradio_blocks = gr.TabbedInterface(
507
+ [default_blocks, custom_blocks],
508
+ tab_names=["Playground", "Visualization"],
509
+ title=get_gradio_display_title(metadata),
510
+ )
511
+ else:
512
+ gradio_blocks = default_blocks
513
+ app = gr.mount_gradio_app(
514
+ app,
515
+ gradio_blocks,
516
+ path="/web",
517
+ theme=OPENENV_GRADIO_THEME,
518
+ css=OPENENV_GRADIO_CSS,
519
+ )
520
+
521
+ return app
522
+
523
+
524
+ def _is_chat_env(action_cls: Type[Action]) -> bool:
525
+ """Return True if the action class is a chat-style env (tokens field)."""
526
+ if hasattr(action_cls, "model_fields"):
527
+ for field_name, field_info in action_cls.model_fields.items():
528
+ if (
529
+ field_name == "tokens"
530
+ and hasattr(field_info.annotation, "__name__")
531
+ and "Tensor" in str(field_info.annotation)
532
+ ):
533
+ return True
534
+ return False
535
+
536
+
537
+ def _extract_action_fields(action_cls: Type[Action]) -> List[Dict[str, Any]]:
538
+ """Extract enhanced field metadata from Action class for form generation."""
539
+ # Use Pydantic's JSON schema generation for robust metadata extraction
540
+ try:
541
+ schema = action_cls.model_json_schema()
542
+ except AttributeError:
543
+ # Fallback for non-Pydantic v2 models or if something goes wrong
544
+ return []
545
+
546
+ properties = schema.get("properties", {})
547
+ required_fields = schema.get("required", [])
548
+
549
+ action_fields = []
550
+
551
+ for field_name, field_info in properties.items():
552
+ if field_name == "metadata":
553
+ continue
554
+
555
+ # JSON schema "type" can be a string or list/undefined
556
+ # Determine our internal input type
557
+ input_type = _determine_input_type_from_schema(field_info, field_name)
558
+
559
+ is_required = field_name in required_fields
560
+
561
+ action_fields.append(
562
+ {
563
+ "name": field_name,
564
+ "type": input_type,
565
+ "required": is_required,
566
+ "description": field_info.get("description", ""),
567
+ "default_value": field_info.get("default"),
568
+ "choices": field_info.get("enum"),
569
+ "min_value": field_info.get("minimum"),
570
+ "max_value": field_info.get("maximum"),
571
+ "min_length": field_info.get("minLength"),
572
+ "max_length": field_info.get("maxLength"),
573
+ "pattern": field_info.get("pattern"),
574
+ "placeholder": _generate_placeholder(field_name, field_info),
575
+ "help_text": _generate_help_text(field_name, field_info),
576
+ }
577
+ )
578
+
579
+ return action_fields
580
+
581
+
582
+ def _determine_input_type_from_schema(
583
+ field_info: Dict[str, Any], field_name: str
584
+ ) -> str:
585
+ """Determine input type from JSON schema for form generation (Gradio UI)."""
586
+ schema_type = field_info.get("type")
587
+
588
+ # Check for specific tensor field convention
589
+ if "tokens" in field_name.lower():
590
+ return "tensor"
591
+
592
+ if "enum" in field_info:
593
+ return "select"
594
+
595
+ if schema_type == "boolean":
596
+ return "checkbox"
597
+
598
+ if schema_type == "integer" or schema_type == "number":
599
+ return "number"
600
+
601
+ if schema_type == "string":
602
+ # Check if it should be a textarea
603
+ if (
604
+ field_info.get("maxLength", 0) > 100
605
+ or "message" in field_name.lower()
606
+ or "code" in field_name.lower()
607
+ ):
608
+ return "textarea"
609
+ return "text"
610
+
611
+ # Default fallback
612
+ return "text"
613
+
614
+
615
+ def _generate_placeholder(field_name: str, field_info: Dict[str, Any]) -> str:
616
+ """Generate placeholder text."""
617
+ if "message" in field_name.lower():
618
+ return f"Enter {field_name.replace('_', ' ')}..."
619
+ elif "code" in field_name.lower():
620
+ return "Enter Python code here..."
621
+ elif "tokens" in field_name.lower():
622
+ return "Enter comma-separated token IDs (e.g., 1,2,3,4,5)"
623
+ else:
624
+ return f"Enter {field_name.replace('_', ' ')}..."
625
+
626
+
627
+ def _generate_help_text(field_name: str, field_info: Dict[str, Any]) -> str:
628
+ """Generate help text."""
629
+ description = field_info.get("description", "")
630
+ if description:
631
+ return description
632
+
633
+ if "action_id" in field_name.lower():
634
+ return "The action ID to execute in environment"
635
+ elif "game_name" in field_name.lower():
636
+ return "Name of game or environment"
637
+ elif "tokens" in field_name.lower():
638
+ return "Token IDs as a comma-separated list of integers"
639
+ elif "code" in field_name.lower():
640
+ return "Python code to execute in environment"
641
+ elif "message" in field_name.lower():
642
+ return "Text message to send"
643
+
644
+ return ""
src/core/generic_client.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Generic environment client that works with raw dictionaries.
9
+
10
+ This module provides a GenericEnvClient that doesn't require installing
11
+ environment-specific packages. It's useful for connecting to remote servers
12
+ without running any untrusted code locally.
13
+ """
14
+
15
+ from typing import Any, Dict
16
+
17
+ from .client_types import StepResult
18
+ from .env_client import EnvClient
19
+
20
+
21
+ class GenericEnvClient(EnvClient[Dict[str, Any], Dict[str, Any], Dict[str, Any]]):
22
+ """
23
+ Environment client that works with raw dictionaries instead of typed classes.
24
+
25
+ This client doesn't require installing environment-specific packages, making it
26
+ ideal for:
27
+ - Connecting to remote servers without installing their packages
28
+ - Quick prototyping and testing
29
+ - Environments where type safety isn't needed
30
+ - Security-conscious scenarios where you don't want to run remote code
31
+
32
+ The trade-off is that you lose type safety and IDE autocomplete for actions
33
+ and observations. Instead of typed objects, you work with plain dictionaries.
34
+
35
+ Example:
36
+ >>> # Direct connection to a running server (no installation needed)
37
+ >>> with GenericEnvClient(base_url="http://localhost:8000") as env:
38
+ ... result = env.reset()
39
+ ... result = env.step({"code": "print('hello')"})
40
+ ... print(result.observation) # Dict[str, Any]
41
+ ... print(result.observation.get("output"))
42
+
43
+ >>> # From local Docker image
44
+ >>> env = GenericEnvClient.from_docker_image("coding-env:latest")
45
+ >>> result = env.reset()
46
+ >>> result = env.step({"code": "x = 1 + 2"})
47
+ >>> env.close()
48
+
49
+ >>> # From HuggingFace Hub (pulls Docker image, no pip install)
50
+ >>> env = GenericEnvClient.from_env("user/my-env", use_docker=True)
51
+ >>> result = env.reset()
52
+ >>> env.close()
53
+
54
+ Note:
55
+ GenericEnvClient inherits `from_docker_image()` and `from_env()` from
56
+ EnvClient, so you can use it with Docker containers and HuggingFace
57
+ Spaces without any package installation.
58
+ """
59
+
60
+ def _step_payload(self, action: Dict[str, Any]) -> Dict[str, Any]:
61
+ """
62
+ Convert action to payload for the server.
63
+
64
+ For GenericEnvClient, this handles both raw dictionaries and
65
+ typed Action objects (Pydantic models). If a Pydantic model is
66
+ passed, it will be converted to a dictionary using model_dump().
67
+
68
+ Args:
69
+ action: Action as a dictionary or Pydantic BaseModel
70
+
71
+ Returns:
72
+ The action as a dictionary for the server
73
+ """
74
+ # If it's already a dict, return as-is
75
+ if isinstance(action, dict):
76
+ return action
77
+
78
+ # If it's a Pydantic model (Action subclass), convert to dict
79
+ if hasattr(action, "model_dump"):
80
+ return action.model_dump()
81
+
82
+ # Fallback for other objects with __dict__
83
+ if hasattr(action, "__dict__"):
84
+ return vars(action)
85
+
86
+ # Last resort: try to convert to dict
87
+ return dict(action)
88
+
89
+ def _parse_result(self, payload: Dict[str, Any]) -> StepResult[Dict[str, Any]]:
90
+ """
91
+ Parse server response into a StepResult.
92
+
93
+ Extracts the observation, reward, and done fields from the
94
+ server response.
95
+
96
+ Args:
97
+ payload: Response payload from the server
98
+
99
+ Returns:
100
+ StepResult with observation as a dictionary
101
+ """
102
+ return StepResult(
103
+ observation=payload.get("observation", {}),
104
+ reward=payload.get("reward"),
105
+ done=payload.get("done", False),
106
+ )
107
+
108
+ def _parse_state(self, payload: Dict[str, Any]) -> Dict[str, Any]:
109
+ """
110
+ Parse state response from the server.
111
+
112
+ For GenericEnvClient, this returns the payload as-is since
113
+ we're working with dictionaries.
114
+
115
+ Args:
116
+ payload: State payload from the server
117
+
118
+ Returns:
119
+ The state as a dictionary
120
+ """
121
+ return payload
122
+
123
+
124
+ class GenericAction(Dict[str, Any]):
125
+ """
126
+ A dictionary subclass for creating actions when using GenericEnvClient.
127
+
128
+ This provides a semantic wrapper around dictionaries to make code more
129
+ readable when working with GenericEnvClient. It behaves exactly like a
130
+ dict but signals intent that this is an action for an environment.
131
+
132
+ Example:
133
+ >>> # Without GenericAction (works fine)
134
+ >>> env.step({"code": "print('hello')"})
135
+
136
+ >>> # With GenericAction (more explicit)
137
+ >>> action = GenericAction(code="print('hello')")
138
+ >>> env.step(action)
139
+
140
+ >>> # With multiple fields
141
+ >>> action = GenericAction(code="x = 1", timeout=30, metadata={"tag": "test"})
142
+ >>> env.step(action)
143
+
144
+ Note:
145
+ GenericAction is just a dict with a constructor that accepts keyword
146
+ arguments. It's provided for symmetry with typed Action classes and
147
+ to make code more readable.
148
+ """
149
+
150
+ def __init__(self, **kwargs: Any) -> None:
151
+ """
152
+ Create a GenericAction from keyword arguments.
153
+
154
+ Args:
155
+ **kwargs: Action fields as keyword arguments
156
+
157
+ Example:
158
+ >>> action = GenericAction(code="print(1)", timeout=30)
159
+ >>> action["code"]
160
+ 'print(1)'
161
+ """
162
+ super().__init__(kwargs)
163
+
164
+ def __repr__(self) -> str:
165
+ """Return a readable representation."""
166
+ items = ", ".join(f"{k}={v!r}" for k, v in self.items())
167
+ return f"GenericAction({items})"
src/core/mcp_client.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ MCP Client classes for tool-calling environments.
9
+
10
+ This module provides async client classes for interacting with MCP-enabled environments:
11
+ - MCPClientBase: Base class with shared tool discovery
12
+ - MCPToolClient: Client for tool-calling style (one tool per step)
13
+
14
+ These clients abstract away the MCP protocol details, providing a clean interface
15
+ for listing and calling tools on remote environments. All clients are async by default.
16
+
17
+ Architecture Overview::
18
+
19
+ ┌─────────────────────────────────────────────────────────┐
20
+ │ HTTPEnvServer │
21
+ ├─────────────────────────────────────────────────────────┤
22
+ │ Simulation Mode (default): │
23
+ │ /ws → OpenEnv protocol (reset/step/state) │
24
+ │ /mcp → MCP JSON-RPC (tools/list, tools/call) │
25
+ │ /reset, /step, /state → HTTP endpoints │
26
+ ├─────────────────────────────────────────────────────────┤
27
+ │ Production Mode (use_production_mode=True): │
28
+ │ /mcp → MCP JSON-RPC (tools/list, tools/call) │
29
+ │ Bypasses step() for direct tool access │
30
+ └─────────────────────────────────────────────────────────┘
31
+
32
+ Client Usage:
33
+ MCPToolClient (default) → /ws (step-based, with rewards)
34
+ MCPToolClient (production) → /mcp (direct tool access, no rewards)
35
+
36
+ Example (async):
37
+ >>> from openenv.core.mcp_client import MCPToolClient
38
+ >>>
39
+ >>> async with MCPToolClient(base_url="http://localhost:8000") as env:
40
+ ... # Discover available tools
41
+ ... tools = await env.list_tools()
42
+ ... print([t.name for t in tools])
43
+ ...
44
+ ... # Call a tool
45
+ ... result = await env.call_tool("echo_message", message="Hello!")
46
+ ... print(result)
47
+
48
+ Example (sync wrapper):
49
+ >>> env = MCPToolClient(base_url="http://localhost:8000").sync()
50
+ >>> with env:
51
+ ... tools = env.list_tools()
52
+ ... result = env.call_tool("echo_message", message="Hello!")
53
+ """
54
+
55
+ from typing import Any, Dict, List, Optional
56
+
57
+ from .client_types import StepResult
58
+ from .env_client import EnvClient
59
+ from .env_server.mcp_types import (
60
+ CallToolAction,
61
+ CallToolObservation,
62
+ ListToolsAction,
63
+ ListToolsObservation,
64
+ Tool,
65
+ ToolError,
66
+ )
67
+ from .env_server.types import Observation, State
68
+
69
+
70
+ class MCPClientBase(EnvClient[Any, Observation, State]):
71
+ """
72
+ Base class for MCP clients with tool discovery.
73
+
74
+ This class provides the common `list_tools()` method for discovering
75
+ available tools from an MCP-enabled environment. Subclasses implement
76
+ specific interaction patterns (tool-calling or CodeAct).
77
+
78
+ Attributes:
79
+ _tools_cache: Cached list of tools (populated on first `list_tools()` call)
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ base_url: str,
85
+ connect_timeout_s: float = 10.0,
86
+ message_timeout_s: float = 60.0,
87
+ provider: Optional[Any] = None,
88
+ mode: Optional[str] = None,
89
+ ):
90
+ """
91
+ Initialize MCP client.
92
+
93
+ Args:
94
+ base_url: Base URL of the environment server (http:// or ws://).
95
+ connect_timeout_s: Timeout for establishing WebSocket connection.
96
+ message_timeout_s: Timeout for receiving responses to messages.
97
+ provider: Optional container/runtime provider for lifecycle management.
98
+ mode: Communication mode. Must be 'production' for MCP clients. Defaults to 'production'.
99
+ """
100
+ # MCPClientBase defaults to production mode, but allow override for validation
101
+ if mode is None:
102
+ mode = "production"
103
+
104
+ # Validate that mode is production
105
+ mode_lower = mode.lower()
106
+ if mode_lower != "production":
107
+ raise ValueError(
108
+ f"MCPToolClient only supports 'production' mode, got '{mode}'. "
109
+ f"Use GenericEnvClient for simulation mode."
110
+ )
111
+
112
+ super().__init__(
113
+ base_url=base_url,
114
+ connect_timeout_s=connect_timeout_s,
115
+ message_timeout_s=message_timeout_s,
116
+ provider=provider,
117
+ mode=mode,
118
+ )
119
+ self._tools_cache: Optional[List[Tool]] = None
120
+ self.use_production_mode = False
121
+
122
+ async def list_tools(self, use_cache: bool = True) -> List[Tool]:
123
+ """
124
+ Discover available tools from the environment.
125
+
126
+ Args:
127
+ use_cache: If True, return cached tools if available.
128
+ Set to False to force a fresh request.
129
+
130
+ Returns:
131
+ List of Tool objects with name, description, and input_schema.
132
+
133
+ Example:
134
+ >>> tools = await env.list_tools()
135
+ >>> for tool in tools:
136
+ ... print(f"{tool.name}: {tool.description}")
137
+ """
138
+ if use_cache and self._tools_cache is not None:
139
+ return self._tools_cache
140
+
141
+ # Use production mode HTTP endpoint if enabled
142
+ if self.use_production_mode:
143
+ import requests
144
+
145
+ # Convert ws:// URL to http:// URL
146
+ url = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")
147
+ # Remove /ws suffix if present and add /mcp
148
+ url = url.rstrip("/ws").rstrip("/") + "/mcp"
149
+
150
+ try:
151
+ response = requests.post(
152
+ url,
153
+ json={
154
+ "jsonrpc": "2.0",
155
+ "method": "tools/list",
156
+ "params": {},
157
+ "id": 1,
158
+ },
159
+ )
160
+ data = response.json()
161
+ if "result" in data and "tools" in data["result"]:
162
+ tools = [
163
+ Tool(
164
+ name=t.get("name", ""),
165
+ description=t.get("description", ""),
166
+ input_schema=t.get(
167
+ "input_schema", t.get("inputSchema", {})
168
+ ),
169
+ )
170
+ for t in data["result"]["tools"]
171
+ ]
172
+ self._tools_cache = tools
173
+ return tools
174
+ except Exception:
175
+ # If HTTP request fails, return empty list
176
+ pass
177
+ return []
178
+
179
+ result = await self.step(ListToolsAction())
180
+ self._tools_cache = result.observation.tools
181
+ return self._tools_cache
182
+
183
+ def _step_payload(self, action: Any) -> Dict[str, Any]:
184
+ """Convert an Action object to the JSON data expected by the env server."""
185
+ if isinstance(action, ListToolsAction):
186
+ return {"type": "list_tools"}
187
+ elif isinstance(action, CallToolAction):
188
+ return {
189
+ "type": "call_tool",
190
+ "tool_name": action.tool_name,
191
+ "arguments": action.arguments,
192
+ }
193
+ else:
194
+ # For unknown actions, try to serialize as dict
195
+ if hasattr(action, "model_dump"):
196
+ return action.model_dump()
197
+ return {"action": str(action)}
198
+
199
+ def _parse_result(self, payload: Dict[str, Any]) -> StepResult[Observation]:
200
+ """Convert a JSON response from the env server to StepResult[Observation]."""
201
+ obs_data = payload.get("observation", {})
202
+
203
+ # Check if this is a ListToolsObservation
204
+ if "tools" in obs_data:
205
+ tools = [
206
+ Tool(
207
+ name=t.get("name", ""),
208
+ description=t.get("description", ""),
209
+ input_schema=t.get("input_schema", t.get("inputSchema", {})),
210
+ )
211
+ for t in obs_data.get("tools", [])
212
+ ]
213
+ observation = ListToolsObservation(
214
+ tools=tools,
215
+ done=payload.get("done", False),
216
+ reward=payload.get("reward"),
217
+ metadata=obs_data.get("metadata", {}),
218
+ )
219
+ # Check if this is a CallToolObservation
220
+ elif "tool_name" in obs_data:
221
+ error = None
222
+ if obs_data.get("error"):
223
+ error = ToolError(**obs_data["error"])
224
+
225
+ observation = CallToolObservation(
226
+ tool_name=obs_data.get("tool_name", ""),
227
+ result=obs_data.get("result"),
228
+ error=error,
229
+ done=payload.get("done", False),
230
+ reward=payload.get("reward"),
231
+ metadata=obs_data.get("metadata", {}),
232
+ )
233
+ else:
234
+ # Generic observation
235
+ observation = Observation(
236
+ done=payload.get("done", False),
237
+ reward=payload.get("reward"),
238
+ metadata=obs_data.get("metadata", {}),
239
+ )
240
+
241
+ return StepResult(
242
+ observation=observation,
243
+ reward=payload.get("reward"),
244
+ done=payload.get("done", False),
245
+ )
246
+
247
+ def _parse_state(self, payload: Dict[str, Any]) -> State:
248
+ """Convert a JSON response from the state endpoint to a State object."""
249
+ return State(
250
+ episode_id=payload.get("episode_id"),
251
+ step_count=payload.get("step_count", 0),
252
+ )
253
+
254
+
255
+ class MCPToolClient(MCPClientBase):
256
+ """
257
+ Async client for tool-calling style MCP interactions.
258
+
259
+ Each step invokes a single tool. Use this for traditional function-calling
260
+ agent patterns where the agent decides which tool to call next.
261
+
262
+ This client provides convenience methods for tool discovery and invocation:
263
+ - `list_tools()`: Get all available tools with their schemas
264
+ - `call_tool(name, **kwargs)`: Invoke a tool by name with arguments
265
+
266
+ Example (async):
267
+ >>> async with MCPToolClient(base_url="http://localhost:8000") as env:
268
+ ... # Reset the environment
269
+ ... await env.reset()
270
+ ...
271
+ ... # Discover available tools
272
+ ... tools = await env.list_tools()
273
+ ... print([t.name for t in tools]) # ['echo_message', 'echo_with_length']
274
+ ...
275
+ ... # Call a tool directly
276
+ ... result = await env.call_tool("echo_message", message="Hello!")
277
+ ... print(result) # "Hello!"
278
+ ...
279
+ ... # Or use the full action interface
280
+ ... from openenv.core.env_server.mcp_types import CallToolAction
281
+ ... step_result = await env.step(CallToolAction(
282
+ ... tool_name="echo_with_length",
283
+ ... arguments={"message": "Test"}
284
+ ... ))
285
+ ... print(step_result.observation.result)
286
+
287
+ Example (sync wrapper):
288
+ >>> env = MCPToolClient(base_url="http://localhost:8000").sync()
289
+ >>> with env:
290
+ ... tools = env.list_tools()
291
+ ... result = env.call_tool("echo_message", message="Hello!")
292
+ """
293
+
294
+ async def call_tool(self, name: str, **kwargs: Any) -> Any:
295
+ """
296
+ Call a tool by name.
297
+
298
+ This is a convenience method that creates a CallToolAction, executes it,
299
+ and returns the result directly. For more control, use `step()` with
300
+ a CallToolAction directly.
301
+
302
+ Args:
303
+ name: Name of the tool to invoke (must match a tool from `list_tools()`).
304
+ **kwargs: Arguments to pass to the tool. Must match the tool's input_schema.
305
+
306
+ Returns:
307
+ The tool's result. The type depends on the tool being called.
308
+
309
+ Raises:
310
+ RuntimeError: If the server returns an error response.
311
+
312
+ Example:
313
+ >>> result = await env.call_tool("add", a=5, b=3)
314
+ >>> print(result) # 8
315
+ >>>
316
+ >>> result = await env.call_tool("greet", name="Claude")
317
+ >>> print(result) # "Hello, Claude!"
318
+ """
319
+ action = CallToolAction(tool_name=name, arguments=kwargs)
320
+ result = await self.step(action)
321
+ obs = result.observation
322
+
323
+ # Check for transport/framework errors
324
+ if isinstance(obs, CallToolObservation) and obs.error is not None:
325
+ raise RuntimeError(
326
+ f"Tool '{name}' failed: {obs.error.message} "
327
+ f"(type: {obs.error.error_type.value})"
328
+ )
329
+
330
+ # Return the result
331
+ if isinstance(obs, CallToolObservation):
332
+ result = obs.result
333
+ # Handle FastMCP CallToolResult objects
334
+ # - As object: has .data attribute
335
+ # - As dict (from JSON): has "data" key
336
+ if hasattr(result, "data"):
337
+ return result.data
338
+ if isinstance(result, dict) and "data" in result:
339
+ return result["data"]
340
+ return result
341
+
342
+ # Fallback for unexpected observation types
343
+ return obs
344
+
345
+ async def get_tool(self, name: str) -> Optional[Tool]:
346
+ """
347
+ Get a specific tool by name.
348
+
349
+ Args:
350
+ name: Name of the tool to find.
351
+
352
+ Returns:
353
+ The Tool object if found, None otherwise.
354
+
355
+ Example:
356
+ >>> tool = await env.get_tool("echo_message")
357
+ >>> if tool:
358
+ ... print(tool.description)
359
+ ... print(tool.input_schema)
360
+ """
361
+ tools = await self.list_tools()
362
+ for tool in tools:
363
+ if tool.name == name:
364
+ return tool
365
+ return None
366
+
367
+ async def has_tool(self, name: str) -> bool:
368
+ """
369
+ Check if a tool exists.
370
+
371
+ Args:
372
+ name: Name of the tool to check.
373
+
374
+ Returns:
375
+ True if the tool exists, False otherwise.
376
+ """
377
+ return await self.get_tool(name) is not None
src/core/rubrics/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Rubrics for reward computation.
8
+
9
+ See RFC 004 for full design: rfcs/004-rubrics.md
10
+ """
11
+
12
+ from openenv.core.rubrics.base import Rubric
13
+ from openenv.core.rubrics.containers import (
14
+ Sequential,
15
+ Gate,
16
+ WeightedSum,
17
+ RubricList,
18
+ RubricDict,
19
+ )
20
+ from openenv.core.rubrics.trajectory import (
21
+ TrajectoryRubric,
22
+ ExponentialDiscountingTrajectoryRubric,
23
+ )
24
+
25
+ __all__ = [
26
+ # Base
27
+ "Rubric",
28
+ # Containers
29
+ "Sequential",
30
+ "Gate",
31
+ "WeightedSum",
32
+ "RubricList",
33
+ "RubricDict",
34
+ # Trajectory
35
+ "TrajectoryRubric",
36
+ "ExponentialDiscountingTrajectoryRubric",
37
+ ]
src/core/rubrics/base.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Base Rubric class for reward computation.
8
+
9
+ Rubrics compute rewards from actions and observations. The API is modeled
10
+ after PyTorch's nn.Module: users implement forward(), and the framework
11
+ handles child registration and hooks.
12
+
13
+ See RFC 004 for full design: rfcs/004-rubrics.md
14
+ """
15
+
16
+ import inspect
17
+ from abc import ABC, abstractmethod
18
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Callable
19
+
20
+
21
+ class Rubric(ABC):
22
+ """Abstract base class for reward computation.
23
+
24
+ A Rubric computes a reward signal from an action and observation.
25
+ Subclasses implement forward() to define the reward logic.
26
+
27
+ Usage:
28
+ class MyRubric(Rubric):
29
+ def forward(self, action, observation) -> float:
30
+ return 1.0 if action.valid else 0.0
31
+
32
+ rubric = MyRubric()
33
+ reward = rubric(action, observation)
34
+
35
+ Child rubrics are auto-registered when assigned as attributes,
36
+ enabling hierarchical composition and introspection.
37
+ """
38
+
39
+ _rubric_children: Dict[str, "Rubric"]
40
+ _forward_hooks: List[Callable]
41
+ _forward_pre_hooks: List[Callable]
42
+ last_score: Optional[float]
43
+
44
+ def __init__(self):
45
+ # Use object.__setattr__ to avoid triggering __setattr__ during init
46
+ object.__setattr__(self, "_rubric_children", {})
47
+ object.__setattr__(self, "_forward_hooks", [])
48
+ object.__setattr__(self, "_forward_pre_hooks", [])
49
+ object.__setattr__(self, "last_score", None)
50
+
51
+ def __setattr__(self, name: str, value: Any) -> None:
52
+ # Auto-register child rubrics when assigned as attributes
53
+ if isinstance(value, Rubric):
54
+ self._rubric_children[name] = value
55
+ object.__setattr__(self, name, value)
56
+
57
+ def __call__(self, action: Any, observation: Any):
58
+ """Evaluate the rubric with hooks.
59
+
60
+ Args:
61
+ action: The action taken by the agent.
62
+ observation: The resulting observation.
63
+
64
+ Returns:
65
+ Reward value (typically 0.0 to 1.0).
66
+ """
67
+ # Check if forward method is async BEFORE calling it
68
+ if inspect.iscoroutinefunction(self.forward):
69
+ # Async path - pre-hooks will be called in _call_async
70
+ result = self.forward(action, observation)
71
+ return self._call_async(action, observation, result)
72
+ else:
73
+ # Sync path - call pre-hooks BEFORE forward()
74
+ for hook in self._forward_pre_hooks:
75
+ hook(self, action, observation)
76
+ result = self.forward(action, observation)
77
+ return self._call_sync(action, observation, result)
78
+
79
+ def _call_sync(self, action: Any, observation: Any, result: float) -> float:
80
+ """Synchronous call path."""
81
+ self.last_score = result
82
+
83
+ # Post-forward hooks
84
+ for hook in self._forward_hooks:
85
+ hook(self, action, observation, result)
86
+
87
+ return result
88
+
89
+ async def _call_async(self, action: Any, observation: Any, result_coro) -> float:
90
+ """Asynchronous call path."""
91
+ # Pre-forward hooks
92
+ for hook in self._forward_pre_hooks:
93
+ if inspect.iscoroutinefunction(hook):
94
+ await hook(self, action, observation)
95
+ else:
96
+ hook(self, action, observation)
97
+
98
+ # Await the forward result
99
+ result = await result_coro
100
+ self.last_score = result
101
+
102
+ # Post-forward hooks
103
+ for hook in self._forward_hooks:
104
+ if inspect.iscoroutinefunction(hook):
105
+ await hook(self, action, observation, result)
106
+ else:
107
+ hook(self, action, observation, result)
108
+
109
+ return result
110
+
111
+ @abstractmethod
112
+ def forward(self, action: Any, observation: Any) -> float:
113
+ """Compute the reward. Implement this in subclasses.
114
+
115
+ Args:
116
+ action: The action taken by the agent.
117
+ observation: The resulting observation.
118
+
119
+ Returns:
120
+ Reward value (typically 0.0 to 1.0).
121
+ """
122
+ raise NotImplementedError
123
+
124
+ def register_forward_hook(
125
+ self, hook: Callable[["Rubric", Any, Any, float], None]
126
+ ) -> None:
127
+ """Register a hook called after forward().
128
+
129
+ Args:
130
+ hook: Callable with signature (rubric, action, observation, result).
131
+ """
132
+ self._forward_hooks.append(hook)
133
+
134
+ def register_forward_pre_hook(
135
+ self, hook: Callable[["Rubric", Any, Any], None]
136
+ ) -> None:
137
+ """Register a hook called before forward().
138
+
139
+ Args:
140
+ hook: Callable with signature (rubric, action, observation).
141
+ """
142
+ self._forward_pre_hooks.append(hook)
143
+
144
+ def children(self) -> Iterator["Rubric"]:
145
+ """Iterate over immediate child rubrics."""
146
+ yield from self._rubric_children.values()
147
+
148
+ def named_children(self) -> Iterator[Tuple[str, "Rubric"]]:
149
+ """Iterate over immediate child rubrics with names."""
150
+ yield from self._rubric_children.items()
151
+
152
+ def rubrics(self) -> Iterator["Rubric"]:
153
+ """Iterate over all descendant rubrics (depth-first)."""
154
+ for child in self._rubric_children.values():
155
+ yield child
156
+ yield from child.rubrics()
157
+
158
+ def named_rubrics(self, prefix: str = "") -> Iterator[Tuple[str, "Rubric"]]:
159
+ """Iterate over all descendant rubrics with dot-separated names."""
160
+ for name, child in self._rubric_children.items():
161
+ full_name = f"{prefix}.{name}" if prefix else name
162
+ yield full_name, child
163
+ yield from child.named_rubrics(full_name)
164
+
165
+ def get_rubric(self, path: str) -> "Rubric":
166
+ """Access a nested rubric by dot-separated path.
167
+
168
+ Args:
169
+ path: Dot-separated path (e.g., "code.syntax").
170
+
171
+ Returns:
172
+ The rubric at the specified path.
173
+
174
+ Raises:
175
+ KeyError: If the path does not exist.
176
+ """
177
+ parts = path.split(".")
178
+ current = self
179
+ for part in parts:
180
+ if part not in current._rubric_children:
181
+ raise KeyError(f"Rubric path not found: {path}")
182
+ current = current._rubric_children[part]
183
+ return current
184
+
185
+ def reset(self) -> None:
186
+ """Reset any internal state. Override in subclasses if needed."""
187
+ pass
188
+
189
+ def state_dict(self) -> Dict[str, Any]:
190
+ """Serialize rubric configuration for checkpointing."""
191
+ return {}
192
+
193
+ def load_state_dict(self, state: Dict[str, Any]) -> None:
194
+ """Load rubric configuration from checkpoint."""
195
+ pass
src/core/rubrics/containers.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Container rubrics for composing reward computations.
8
+
9
+ These containers provide common aggregation patterns for rubrics,
10
+ similar to how PyTorch provides nn.Sequential alongside nn.Module.
11
+
12
+ See RFC 004 for full design: rfcs/004-rubrics.md
13
+ """
14
+
15
+ import asyncio
16
+ import inspect
17
+ from typing import Any, Dict, Iterator, List, Mapping, Tuple, Union
18
+
19
+ from openenv.core.rubrics.base import Rubric
20
+
21
+
22
+ def _in_async_context() -> bool:
23
+ """Check if we're currently in an async context."""
24
+ try:
25
+ asyncio.get_running_loop()
26
+ return True
27
+ except RuntimeError:
28
+ return False
29
+
30
+
31
+ class Sequential(Rubric):
32
+ """Run rubrics in order, fail-fast on zero.
33
+
34
+ Runs child rubrics in order. If any returns 0, stops immediately
35
+ and returns 0. This implements hierarchical gating patterns where
36
+ syntax checks run before execution checks.
37
+
38
+ Usage:
39
+ rubric = Sequential(
40
+ Gate(Compiles()),
41
+ Gate(PassesTests(), threshold=0.5),
42
+ WeightedSum([PassesTests(), StyleRubric()], weights=[0.7, 0.3])
43
+ )
44
+ """
45
+
46
+ def __init__(self, *rubrics: Rubric):
47
+ """Initialize with rubrics to run in sequence.
48
+
49
+ Args:
50
+ *rubrics: Rubrics to run in order. Stops and returns 0 if any
51
+ child returns 0.
52
+ """
53
+ super().__init__()
54
+ for i, rubric in enumerate(rubrics):
55
+ setattr(self, f"rubric_{i}", rubric)
56
+ self._rubric_list = list(rubrics)
57
+
58
+ def forward(self, action: Any, observation: Any) -> float:
59
+ """Run rubrics in order, return 0 if any returns 0. Sync version."""
60
+ result = 1.0
61
+ for rubric in self._rubric_list:
62
+ score = rubric(action, observation)
63
+ if score == 0.0:
64
+ return 0.0
65
+ result = score
66
+ return result
67
+
68
+ def __call__(self, action: Any, observation: Any):
69
+ """Override to choose sync or async path based on children."""
70
+ # Empty case - check if in async context
71
+ if not self._rubric_list:
72
+ if _in_async_context():
73
+ return self._empty_async(action, observation)
74
+ else:
75
+ # Pre-hooks
76
+ for hook in self._forward_pre_hooks:
77
+ hook(self, action, observation)
78
+ result = 1.0
79
+ self.last_score = result
80
+ for hook in self._forward_hooks:
81
+ hook(self, action, observation, result)
82
+ return result
83
+
84
+ # Call first rubric to see if it's async
85
+ first_result = self._rubric_list[0](action, observation)
86
+ if inspect.iscoroutine(first_result):
87
+ # At least one child is async, use async path
88
+ return self._call_async_detected(action, observation, first_result)
89
+ else:
90
+ # Continue with sync path
91
+ if first_result == 0.0:
92
+ # Pre-hooks
93
+ for hook in self._forward_pre_hooks:
94
+ hook(self, action, observation)
95
+ self.last_score = 0.0
96
+ for hook in self._forward_hooks:
97
+ hook(self, action, observation, 0.0)
98
+ return 0.0
99
+
100
+ final_result = first_result
101
+ for i, rubric in enumerate(self._rubric_list[1:], start=1):
102
+ score = rubric(action, observation)
103
+ if inspect.iscoroutine(score):
104
+ # Found async mid-way, switch to async
105
+ # We already called rubric at index i, so pass the coroutine and remaining rubrics
106
+ return self._call_async_mid(
107
+ action,
108
+ observation,
109
+ final_result,
110
+ score,
111
+ self._rubric_list[i + 1 :],
112
+ )
113
+ if score == 0.0:
114
+ # Pre-hooks
115
+ for hook in self._forward_pre_hooks:
116
+ hook(self, action, observation)
117
+ self.last_score = 0.0
118
+ for hook in self._forward_hooks:
119
+ hook(self, action, observation, 0.0)
120
+ return 0.0
121
+ final_result = score
122
+
123
+ # All sync - check if in async context
124
+ if _in_async_context():
125
+ return self._wrap_sync_result(action, observation, final_result)
126
+ else:
127
+ # Pre-hooks
128
+ for hook in self._forward_pre_hooks:
129
+ hook(self, action, observation)
130
+ self.last_score = final_result
131
+ for hook in self._forward_hooks:
132
+ hook(self, action, observation, final_result)
133
+ return final_result
134
+
135
+ async def _empty_async(self, action, observation):
136
+ """Async path for empty sequential."""
137
+ for hook in self._forward_pre_hooks:
138
+ if inspect.iscoroutinefunction(hook):
139
+ await hook(self, action, observation)
140
+ else:
141
+ hook(self, action, observation)
142
+
143
+ result = 1.0
144
+ self.last_score = result
145
+
146
+ for hook in self._forward_hooks:
147
+ if inspect.iscoroutinefunction(hook):
148
+ await hook(self, action, observation, result)
149
+ else:
150
+ hook(self, action, observation, result)
151
+ return result
152
+
153
+ async def _wrap_sync_result(self, action, observation, result):
154
+ """Wrap sync result for async context."""
155
+ for hook in self._forward_pre_hooks:
156
+ if inspect.iscoroutinefunction(hook):
157
+ await hook(self, action, observation)
158
+ else:
159
+ hook(self, action, observation)
160
+
161
+ self.last_score = result
162
+
163
+ for hook in self._forward_hooks:
164
+ if inspect.iscoroutinefunction(hook):
165
+ await hook(self, action, observation, result)
166
+ else:
167
+ hook(self, action, observation, result)
168
+ return result
169
+
170
+ async def _call_async_detected(self, action, observation, first_coro):
171
+ """Async path when first child is async."""
172
+ for hook in self._forward_pre_hooks:
173
+ if inspect.iscoroutinefunction(hook):
174
+ await hook(self, action, observation)
175
+ else:
176
+ hook(self, action, observation)
177
+
178
+ result = await first_coro
179
+ if result == 0.0:
180
+ self.last_score = 0.0
181
+ for hook in self._forward_hooks:
182
+ if inspect.iscoroutinefunction(hook):
183
+ await hook(self, action, observation, result)
184
+ else:
185
+ hook(self, action, observation, result)
186
+ return 0.0
187
+
188
+ for rubric in self._rubric_list[1:]:
189
+ score = rubric(action, observation)
190
+ if inspect.iscoroutine(score):
191
+ score = await score
192
+ if score == 0.0:
193
+ self.last_score = 0.0
194
+ for hook in self._forward_hooks:
195
+ if inspect.iscoroutinefunction(hook):
196
+ await hook(self, action, observation, 0.0)
197
+ else:
198
+ hook(self, action, observation, 0.0)
199
+ return 0.0
200
+ result = score
201
+
202
+ self.last_score = result
203
+ for hook in self._forward_hooks:
204
+ if inspect.iscoroutinefunction(hook):
205
+ await hook(self, action, observation, result)
206
+ else:
207
+ hook(self, action, observation, result)
208
+ return result
209
+
210
+ async def _call_async_mid(
211
+ self, action, observation, current_result, first_async_coro, remaining
212
+ ):
213
+ """Async path when async detected mid-execution."""
214
+ for hook in self._forward_pre_hooks:
215
+ if inspect.iscoroutinefunction(hook):
216
+ await hook(self, action, observation)
217
+ else:
218
+ hook(self, action, observation)
219
+
220
+ # Await the first async rubric (already called)
221
+ result = await first_async_coro
222
+ if result == 0.0:
223
+ self.last_score = 0.0
224
+ for hook in self._forward_hooks:
225
+ if inspect.iscoroutinefunction(hook):
226
+ await hook(self, action, observation, 0.0)
227
+ else:
228
+ hook(self, action, observation, 0.0)
229
+ return 0.0
230
+
231
+ # Continue with remaining rubrics
232
+ for rubric in remaining:
233
+ score = rubric(action, observation)
234
+ if inspect.iscoroutine(score):
235
+ score = await score
236
+ if score == 0.0:
237
+ self.last_score = 0.0
238
+ for hook in self._forward_hooks:
239
+ if inspect.iscoroutinefunction(hook):
240
+ await hook(self, action, observation, 0.0)
241
+ else:
242
+ hook(self, action, observation, 0.0)
243
+ return 0.0
244
+ result = score
245
+
246
+ self.last_score = result
247
+ for hook in self._forward_hooks:
248
+ if inspect.iscoroutinefunction(hook):
249
+ await hook(self, action, observation, result)
250
+ else:
251
+ hook(self, action, observation, result)
252
+ return result
253
+
254
+ def __len__(self) -> int:
255
+ return len(self._rubric_list)
256
+
257
+ def __getitem__(self, index: int) -> Rubric:
258
+ return self._rubric_list[index]
259
+
260
+
261
+ class Gate(Rubric):
262
+ """Threshold wrapper - returns 0 if child score is below threshold.
263
+
264
+ Useful for hard constraints like "must pass 50% of tests".
265
+
266
+ Usage:
267
+ rubric = Gate(PassesTests(), threshold=0.5)
268
+ # Returns PassesTests() score if >= 0.5, else 0.0
269
+ """
270
+
271
+ def __init__(self, rubric: Rubric, threshold: float = 1.0):
272
+ """Initialize with a rubric and threshold.
273
+
274
+ Args:
275
+ rubric: The rubric to gate.
276
+ threshold: Minimum score required. If child returns less than
277
+ this, Gate returns 0. Default is 1.0 (must pass completely).
278
+ """
279
+ super().__init__()
280
+ self.rubric = rubric
281
+ self.threshold = threshold
282
+
283
+ def forward(self, action: Any, observation: Any) -> float:
284
+ """Return child score if >= threshold, else 0. Sync version."""
285
+ score = self.rubric(action, observation)
286
+ if score < self.threshold:
287
+ return 0.0
288
+ return score
289
+
290
+ def __call__(self, action: Any, observation: Any):
291
+ """Override to handle async child."""
292
+ # Call child
293
+ score = self.rubric(action, observation)
294
+
295
+ if inspect.iscoroutine(score):
296
+ # Child is async
297
+ return self._call_async(action, observation, score)
298
+ else:
299
+ # Child is sync
300
+ # Pre-hooks
301
+ for hook in self._forward_pre_hooks:
302
+ hook(self, action, observation)
303
+ result = 0.0 if score < self.threshold else score
304
+ self.last_score = result
305
+ for hook in self._forward_hooks:
306
+ hook(self, action, observation, result)
307
+ return result
308
+
309
+ async def _call_async(self, action, observation, score_coro):
310
+ """Async path."""
311
+ for hook in self._forward_pre_hooks:
312
+ if inspect.iscoroutinefunction(hook):
313
+ await hook(self, action, observation)
314
+ else:
315
+ hook(self, action, observation)
316
+
317
+ score = await score_coro
318
+ result = 0.0 if score < self.threshold else score
319
+ self.last_score = result
320
+
321
+ for hook in self._forward_hooks:
322
+ if inspect.iscoroutinefunction(hook):
323
+ await hook(self, action, observation, result)
324
+ else:
325
+ hook(self, action, observation, result)
326
+ return result
327
+
328
+
329
+ class WeightedSum(Rubric):
330
+ """Weighted combination of child rubrics.
331
+
332
+ Standard aggregation pattern for multi-criteria evaluation.
333
+
334
+ Usage:
335
+ rubric = WeightedSum(
336
+ [PassesTests(), StyleRubric()],
337
+ weights=[0.7, 0.3]
338
+ )
339
+ """
340
+
341
+ def __init__(self, rubrics: List[Rubric], weights: List[float]):
342
+ """Initialize with rubrics and weights.
343
+
344
+ Args:
345
+ rubrics: List of rubrics to combine.
346
+ weights: Weight for each rubric. Must sum to 1.0.
347
+
348
+ Raises:
349
+ ValueError: If lengths don't match or weights don't sum to 1.0.
350
+ """
351
+ super().__init__()
352
+ if len(rubrics) != len(weights):
353
+ raise ValueError(
354
+ f"Number of rubrics ({len(rubrics)}) must match "
355
+ f"number of weights ({len(weights)})"
356
+ )
357
+ if abs(sum(weights) - 1.0) > 1e-6:
358
+ raise ValueError(f"Weights must sum to 1.0, got {sum(weights)}")
359
+
360
+ for i, rubric in enumerate(rubrics):
361
+ setattr(self, f"rubric_{i}", rubric)
362
+ self._rubric_list = list(rubrics)
363
+ self._weights = list(weights)
364
+
365
+ def forward(self, action: Any, observation: Any) -> float:
366
+ """Return weighted sum of child scores. Sync version."""
367
+ total = 0.0
368
+ for rubric, weight in zip(self._rubric_list, self._weights):
369
+ score = rubric(action, observation)
370
+ total += score * weight
371
+ return total
372
+
373
+ def __call__(self, action: Any, observation: Any):
374
+ """Override to handle async children with parallel execution."""
375
+ # Call all rubrics
376
+ results = [rubric(action, observation) for rubric in self._rubric_list]
377
+
378
+ # Check if any are async
379
+ has_async = any(inspect.iscoroutine(r) for r in results)
380
+
381
+ if has_async:
382
+ # Use async path
383
+ return self._call_async(action, observation, results)
384
+ else:
385
+ # Sync path
386
+ # Pre-hooks
387
+ for hook in self._forward_pre_hooks:
388
+ hook(self, action, observation)
389
+ total = 0.0
390
+ for score, weight in zip(results, self._weights):
391
+ total += score * weight
392
+ self.last_score = total
393
+ for hook in self._forward_hooks:
394
+ hook(self, action, observation, total)
395
+ return total
396
+
397
+ async def _call_async(self, action, observation, results):
398
+ """Async path with parallel execution."""
399
+ for hook in self._forward_pre_hooks:
400
+ if inspect.iscoroutinefunction(hook):
401
+ await hook(self, action, observation)
402
+ else:
403
+ hook(self, action, observation)
404
+
405
+ # Separate sync and async results
406
+ async_tasks = []
407
+ async_indices = []
408
+ scores = [None] * len(results)
409
+
410
+ for i, result in enumerate(results):
411
+ if inspect.iscoroutine(result):
412
+ async_tasks.append(result)
413
+ async_indices.append(i)
414
+ else:
415
+ scores[i] = result
416
+
417
+ # Await all async tasks in parallel
418
+ if async_tasks:
419
+ async_scores = await asyncio.gather(*async_tasks)
420
+ for i, score in zip(async_indices, async_scores):
421
+ scores[i] = score
422
+
423
+ # Compute weighted sum
424
+ total = 0.0
425
+ for score, weight in zip(scores, self._weights):
426
+ total += score * weight
427
+
428
+ self.last_score = total
429
+
430
+ for hook in self._forward_hooks:
431
+ if inspect.iscoroutinefunction(hook):
432
+ await hook(self, action, observation, total)
433
+ else:
434
+ hook(self, action, observation, total)
435
+ return total
436
+
437
+ @property
438
+ def weights(self) -> List[float]:
439
+ """Get the weights (read-only copy)."""
440
+ return list(self._weights)
441
+
442
+
443
+ class RubricList(Rubric):
444
+ """Container for dynamic lists of rubrics.
445
+
446
+ Analogous to nn.ModuleList. Does not define aggregation - use within
447
+ a parent rubric that implements custom logic.
448
+
449
+ Usage:
450
+ class MultiGameRubric(Rubric):
451
+ def __init__(self, games: List[str]):
452
+ super().__init__()
453
+ self.games = RubricList([GameRubric(g) for g in games])
454
+
455
+ def forward(self, action, obs) -> float:
456
+ return self.games[obs.game_index](action, obs)
457
+ """
458
+
459
+ def __init__(self, rubrics: List[Rubric] = None):
460
+ """Initialize with optional list of rubrics.
461
+
462
+ Args:
463
+ rubrics: Optional list of rubrics to start with.
464
+ """
465
+ super().__init__()
466
+ self._rubrics: List[Rubric] = []
467
+ if rubrics is not None:
468
+ for i, rubric in enumerate(rubrics):
469
+ self.append(rubric)
470
+
471
+ def forward(self, action: Any, observation: Any) -> float:
472
+ """RubricList does not define aggregation - override in parent."""
473
+ raise NotImplementedError(
474
+ "RubricList.forward() is not implemented. "
475
+ "Use RubricList within a parent rubric that defines aggregation."
476
+ )
477
+
478
+ def append(self, rubric: Rubric) -> None:
479
+ """Add a rubric to the list."""
480
+ index = len(self._rubrics)
481
+ setattr(self, f"rubric_{index}", rubric)
482
+ self._rubrics.append(rubric)
483
+
484
+ def extend(self, rubrics: List[Rubric]) -> None:
485
+ """Add multiple rubrics to the list."""
486
+ for rubric in rubrics:
487
+ self.append(rubric)
488
+
489
+ def __len__(self) -> int:
490
+ return len(self._rubrics)
491
+
492
+ def __getitem__(self, index: int) -> Rubric:
493
+ return self._rubrics[index]
494
+
495
+ def __iter__(self) -> Iterator[Rubric]:
496
+ return iter(self._rubrics)
497
+
498
+
499
+ class RubricDict(Rubric):
500
+ """Container for named rubrics with keyed access.
501
+
502
+ Analogous to nn.ModuleDict. Enables keyed access for multi-task
503
+ environments where different tasks require different rubrics.
504
+
505
+ Usage:
506
+ class AtariRubric(Rubric):
507
+ def __init__(self):
508
+ super().__init__()
509
+ self.games = RubricDict({
510
+ "pong": PongRubric(),
511
+ "breakout": BreakoutRubric(),
512
+ "space_invaders": SpaceInvadersRubric(),
513
+ })
514
+
515
+ def forward(self, action, obs) -> float:
516
+ return self.games[obs.game_id](action, obs)
517
+
518
+ # Access: env.rubric.games["pong"]
519
+ """
520
+
521
+ def __init__(self, rubrics: Dict[str, Rubric] = None):
522
+ """Initialize with optional dictionary of rubrics.
523
+
524
+ Args:
525
+ rubrics: Optional dictionary mapping names to rubrics.
526
+ """
527
+ super().__init__()
528
+ self._rubric_dict: Dict[str, Rubric] = {}
529
+ if rubrics is not None:
530
+ for name, rubric in rubrics.items():
531
+ self[name] = rubric
532
+
533
+ def forward(self, action: Any, observation: Any) -> float:
534
+ """RubricDict does not define aggregation - override in parent."""
535
+ raise NotImplementedError(
536
+ "RubricDict.forward() is not implemented. "
537
+ "Use RubricDict within a parent rubric that defines aggregation."
538
+ )
539
+
540
+ def __setitem__(self, key: str, rubric: Rubric) -> None:
541
+ """Add a rubric with the given key."""
542
+ setattr(self, key, rubric)
543
+ self._rubric_dict[key] = rubric
544
+
545
+ def __getitem__(self, key: str) -> Rubric:
546
+ """Get rubric by key."""
547
+ return self._rubric_dict[key]
548
+
549
+ def __contains__(self, key: str) -> bool:
550
+ """Check if key exists."""
551
+ return key in self._rubric_dict
552
+
553
+ def __len__(self) -> int:
554
+ return len(self._rubric_dict)
555
+
556
+ def __iter__(self) -> Iterator[str]:
557
+ return iter(self._rubric_dict)
558
+
559
+ def keys(self) -> Iterator[str]:
560
+ """Iterate over keys."""
561
+ return iter(self._rubric_dict.keys())
562
+
563
+ def values(self) -> Iterator[Rubric]:
564
+ """Iterate over rubrics."""
565
+ return iter(self._rubric_dict.values())
566
+
567
+ def items(self) -> Iterator[Tuple[str, Rubric]]:
568
+ """Iterate over (key, rubric) pairs."""
569
+ return iter(self._rubric_dict.items())
570
+
571
+ def update(self, rubrics: Union[Dict[str, Rubric], Mapping[str, Rubric]]) -> None:
572
+ """Update with rubrics from a dictionary."""
573
+ for name, rubric in rubrics.items():
574
+ self[name] = rubric
src/core/rubrics/trajectory.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Trajectory-based rubrics for delayed reward computation.
8
+
9
+ These rubrics accumulate trajectory data and compute rewards based on
10
+ episode outcomes rather than individual steps. This supports scenarios
11
+ where reward signals depend on future events:
12
+
13
+ - Terminal games (chess, Go): Win/loss known only at game end
14
+ - Plan execution: Plan quality depends on execution success
15
+ - Multi-agent games: One player's action quality depends on opponent response
16
+
17
+ See RFC 004 "Delayed Rewards" section for design rationale.
18
+ """
19
+
20
+ from abc import abstractmethod
21
+ from typing import Any, Dict, List, Tuple
22
+
23
+ from openenv.core.rubrics.base import Rubric
24
+
25
+
26
+ class TrajectoryRubric(Rubric):
27
+ """Abstract base for rubrics that score based on full trajectories.
28
+
29
+ Subclasses implement:
30
+ - score_trajectory(): Compute final score from trajectory
31
+ - compute_step_rewards(): Define credit assignment strategy
32
+
33
+ The __call__ method accumulates steps and returns rewards according
34
+ to the subclass's implementation.
35
+
36
+ IMPORTANT: Trajectories are stored in CPU memory to avoid GPU pressure.
37
+ Environments with GPU tensors in observations must move them to CPU
38
+ before returning from step().
39
+
40
+ Known limitation: Very long episodes (thousands of steps) may consume
41
+ significant CPU memory. For such cases, consider streaming rubrics.
42
+
43
+ Usage:
44
+ class WinLossRubric(TrajectoryRubric):
45
+ def score_trajectory(self, trajectory):
46
+ _, final_obs = trajectory[-1]
47
+ return 1.0 if final_obs.metadata.get('won') else 0.0
48
+
49
+ def compute_step_rewards(self):
50
+ # Equal credit to all steps
51
+ score = self.score_trajectory(self._trajectory)
52
+ return [score] * len(self._trajectory)
53
+
54
+ rubric = WinLossRubric()
55
+ for action, obs in episode:
56
+ reward = rubric(action, obs) # 0.0 until done
57
+ step_rewards = rubric.compute_step_rewards() # Credit assignment
58
+ """
59
+
60
+ _trajectory: List[Tuple[Any, Any]]
61
+ intermediate_reward: float
62
+
63
+ def __init__(self, intermediate_reward: float = 0.0):
64
+ """Initialize trajectory rubric.
65
+
66
+ Args:
67
+ intermediate_reward: Value to return for non-terminal steps.
68
+ Defaults to 0.0.
69
+ """
70
+ super().__init__()
71
+ self.intermediate_reward = intermediate_reward
72
+ self._trajectory = []
73
+
74
+ def forward(self, action: Any, observation: Any) -> float:
75
+ """Accumulate step and return reward.
76
+
77
+ Returns intermediate_reward until done, then computes trajectory score.
78
+
79
+ Args:
80
+ action: The action taken.
81
+ observation: The resulting observation. Must have a 'done' attribute.
82
+
83
+ Returns:
84
+ intermediate_reward if not done, else score_trajectory() result.
85
+ """
86
+ self._trajectory.append((action, observation))
87
+
88
+ if getattr(observation, "done", False):
89
+ return self.score_trajectory(self._trajectory)
90
+ else:
91
+ return self.intermediate_reward
92
+
93
+ @abstractmethod
94
+ def score_trajectory(self, trajectory: List[Tuple[Any, Any]]) -> float:
95
+ """Score the complete trajectory. Return 0.0-1.0.
96
+
97
+ Called when observation.done=True.
98
+
99
+ Args:
100
+ trajectory: List of (action, observation) tuples.
101
+
102
+ Returns:
103
+ Final trajectory score (typically 0.0 to 1.0).
104
+ """
105
+ raise NotImplementedError
106
+
107
+ @abstractmethod
108
+ def compute_step_rewards(self) -> List[float]:
109
+ """Compute per-step rewards from the accumulated trajectory.
110
+
111
+ Returns:
112
+ List of rewards, one per step. Length matches len(trajectory).
113
+
114
+ Define your credit assignment strategy here (e.g., discounting,
115
+ assigning all credit to specific steps, etc.).
116
+ """
117
+ raise NotImplementedError
118
+
119
+ def reset(self) -> None:
120
+ """Clear accumulated trajectory. Call on env.reset()."""
121
+ self._trajectory = []
122
+
123
+ @property
124
+ def trajectory(self) -> List[Tuple[Any, Any]]:
125
+ """Current trajectory (read-only copy)."""
126
+ return list(self._trajectory)
127
+
128
+ def state_dict(self) -> Dict[str, Any]:
129
+ """Serialize configuration (not trajectory data)."""
130
+ return {"intermediate_reward": self.intermediate_reward}
131
+
132
+ def load_state_dict(self, state: Dict[str, Any]) -> None:
133
+ """Load configuration from checkpoint."""
134
+ if "intermediate_reward" in state:
135
+ self.intermediate_reward = state["intermediate_reward"]
136
+
137
+
138
+ class ExponentialDiscountingTrajectoryRubric(TrajectoryRubric):
139
+ """TrajectoryRubric with exponential discounting for credit assignment.
140
+
141
+ Per-step reward: r_t = gamma^(T-1-t) * R_final
142
+
143
+ With gamma=0.99, later steps get higher reward (they're "closer" to the outcome).
144
+ With gamma=1.0, all steps get equal reward.
145
+ With gamma=0.0, only the final step gets reward.
146
+
147
+ This is the standard temporal discounting used in reinforcement learning,
148
+ applied retroactively once the episode outcome is known.
149
+
150
+ Usage:
151
+ class ChessRubric(ExponentialDiscountingTrajectoryRubric):
152
+ def score_trajectory(self, trajectory):
153
+ _, final_obs = trajectory[-1]
154
+ outcome = final_obs.metadata.get('winner')
155
+ if outcome == 'agent': return 1.0
156
+ elif outcome == 'opponent': return 0.0
157
+ else: return 0.5 # Draw
158
+
159
+ rubric = ChessRubric(gamma=0.99)
160
+ reward = rubric(action, obs) # 0.0 until done, then final score
161
+ step_rewards = rubric.compute_step_rewards() # Discounted per-step rewards
162
+ """
163
+
164
+ gamma: float
165
+
166
+ def __init__(self, gamma: float = 0.99, intermediate_reward: float = 0.0):
167
+ """Initialize with discount factor.
168
+
169
+ Args:
170
+ gamma: Discount factor in [0, 1]. Higher values give more credit
171
+ to early moves. 0.99 is a common choice.
172
+ intermediate_reward: Value to return for non-terminal steps.
173
+ """
174
+ super().__init__(intermediate_reward=intermediate_reward)
175
+ if not 0.0 <= gamma <= 1.0:
176
+ raise ValueError(f"gamma must be in [0, 1], got {gamma}")
177
+ self.gamma = gamma
178
+
179
+ def compute_step_rewards(self) -> List[float]:
180
+ """Apply exponential discounting from final reward.
181
+
182
+ Returns:
183
+ List of discounted rewards. step_rewards[t] = gamma^(T-1-t) * R_final
184
+ where T is the trajectory length and R_final is score_trajectory().
185
+ """
186
+ if not self._trajectory:
187
+ return []
188
+
189
+ final_score = self.score_trajectory(self._trajectory)
190
+ T = len(self._trajectory)
191
+ return [final_score * (self.gamma ** (T - 1 - t)) for t in range(T)]
192
+
193
+ def state_dict(self) -> Dict[str, Any]:
194
+ """Serialize configuration."""
195
+ state = super().state_dict()
196
+ state["gamma"] = self.gamma
197
+ return state
198
+
199
+ def load_state_dict(self, state: Dict[str, Any]) -> None:
200
+ """Load configuration from checkpoint."""
201
+ super().load_state_dict(state)
202
+ if "gamma" in state:
203
+ self.gamma = state["gamma"]
src/core/sync_client.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Synchronous wrapper for async EnvClient.
9
+
10
+ This module provides a SyncEnvClient that wraps an async EnvClient,
11
+ allowing synchronous usage while the underlying client uses async I/O.
12
+
13
+ Example:
14
+ >>> from openenv.core import GenericEnvClient
15
+ >>>
16
+ >>> # Create async client and get sync wrapper
17
+ >>> async_client = GenericEnvClient(base_url="http://localhost:8000")
18
+ >>> sync_client = async_client.sync()
19
+ >>>
20
+ >>> # Use synchronous API
21
+ >>> with sync_client:
22
+ ... result = sync_client.reset()
23
+ ... result = sync_client.step({"code": "print('hello')"})
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Any, Dict, Generic, TYPE_CHECKING, TypeVar
29
+
30
+ from .client_types import StepResult, StateT
31
+ from .utils import run_async_safely
32
+
33
+ if TYPE_CHECKING:
34
+ from .env_client import EnvClient
35
+
36
+ ActT = TypeVar("ActT")
37
+ ObsT = TypeVar("ObsT")
38
+
39
+
40
+ class SyncEnvClient(Generic[ActT, ObsT, StateT]):
41
+ """
42
+ Synchronous wrapper around an async EnvClient.
43
+
44
+ This class provides a synchronous interface to an async EnvClient,
45
+ making it easier to use in synchronous code or to stop async from
46
+ "infecting" the entire call stack.
47
+
48
+ The wrapper uses `run_async_safely()` to execute async operations,
49
+ which handles both sync and async calling contexts correctly.
50
+
51
+ Example:
52
+ >>> # From an async client
53
+ >>> async_client = GenericEnvClient(base_url="http://localhost:8000")
54
+ >>> sync_client = async_client.sync()
55
+ >>>
56
+ >>> # Use synchronous context manager
57
+ >>> with sync_client:
58
+ ... result = sync_client.reset()
59
+ ... result = sync_client.step({"action": "test"})
60
+
61
+ Attributes:
62
+ _async: The wrapped async EnvClient instance
63
+ """
64
+
65
+ def __init__(self, async_client: "EnvClient[ActT, ObsT, StateT]"):
66
+ """
67
+ Initialize sync wrapper around an async client.
68
+
69
+ Args:
70
+ async_client: The async EnvClient to wrap
71
+ """
72
+ self._async = async_client
73
+
74
+ @property
75
+ def async_client(self) -> "EnvClient[ActT, ObsT, StateT]":
76
+ """Access the underlying async client."""
77
+ return self._async
78
+
79
+ def connect(self) -> "SyncEnvClient[ActT, ObsT, StateT]":
80
+ """
81
+ Establish connection to the server.
82
+
83
+ Returns:
84
+ self for method chaining
85
+ """
86
+ run_async_safely(self._async.connect())
87
+ return self
88
+
89
+ def disconnect(self) -> None:
90
+ """Close the connection."""
91
+ run_async_safely(self._async.disconnect())
92
+
93
+ def reset(self, **kwargs: Any) -> StepResult[ObsT]:
94
+ """
95
+ Reset the environment.
96
+
97
+ Args:
98
+ **kwargs: Optional parameters passed to the environment's reset method
99
+
100
+ Returns:
101
+ StepResult containing initial observation
102
+ """
103
+ return run_async_safely(self._async.reset(**kwargs))
104
+
105
+ def step(self, action: ActT, **kwargs: Any) -> StepResult[ObsT]:
106
+ """
107
+ Execute an action in the environment.
108
+
109
+ Args:
110
+ action: The action to execute
111
+ **kwargs: Optional parameters
112
+
113
+ Returns:
114
+ StepResult containing observation, reward, and done status
115
+ """
116
+ return run_async_safely(self._async.step(action, **kwargs))
117
+
118
+ def state(self) -> StateT:
119
+ """
120
+ Get the current environment state.
121
+
122
+ Returns:
123
+ State object with environment state information
124
+ """
125
+ return run_async_safely(self._async.state())
126
+
127
+ def close(self) -> None:
128
+ """Close the connection and clean up resources."""
129
+ run_async_safely(self._async.close())
130
+
131
+ def __enter__(self) -> "SyncEnvClient[ActT, ObsT, StateT]":
132
+ """Enter context manager, establishing connection."""
133
+ self.connect()
134
+ return self
135
+
136
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
137
+ """Exit context manager, closing connection."""
138
+ self.close()
139
+
140
+ # Delegate abstract method implementations to the wrapped client
141
+ def _step_payload(self, action: ActT) -> Dict[str, Any]:
142
+ """Delegate to async client's _step_payload."""
143
+ return self._async._step_payload(action)
144
+
145
+ def _parse_result(self, payload: Dict[str, Any]) -> StepResult[ObsT]:
146
+ """Delegate to async client's _parse_result."""
147
+ return self._async._parse_result(payload)
148
+
149
+ def _parse_state(self, payload: Dict[str, Any]) -> StateT:
150
+ """Delegate to async client's _parse_state."""
151
+ return self._async._parse_state(payload)
src/core/tools/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Core tools for code execution and other utilities."""
8
+
9
+ from .git_server_client import GitServerClient, RepoInfo
10
+ from .local_python_executor import PyExecutor
11
+
12
+ __all__ = [
13
+ "PyExecutor",
14
+ "GitServerClient",
15
+ "RepoInfo",
16
+ ]
src/core/tools/git_server_client.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Git Server Client for connecting to external Gitea instance.
4
+
5
+ This module provides a lightweight client for interacting with a shared
6
+ Gitea service, optimized for task-based isolation where multiple environment
7
+ instances share the same Gitea server but have isolated workspaces.
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import time
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from urllib.parse import urlparse
18
+
19
+
20
+ @dataclass
21
+ class RepoInfo:
22
+ """Information about a repository."""
23
+
24
+ name: str
25
+ url: str
26
+ commit: str
27
+ clone_url: str
28
+
29
+
30
+ class GitServerClient:
31
+ """
32
+ Client for connecting to an external Gitea server.
33
+
34
+ This client is optimized for task-based isolation where:
35
+ - Multiple tasks share the same Gitea instance
36
+ - Each task has its own isolated workspace
37
+ - Fast reset() via git operations (no server restart)
38
+ - Repos are pre-migrated to Gitea once
39
+
40
+ Args:
41
+ gitea_url: URL of the Gitea server (e.g., "http://gitea:3000")
42
+ username: Gitea username for authentication
43
+ password: Gitea password for authentication
44
+ workspace_dir: Local workspace directory for cloning repos
45
+
46
+ Example:
47
+ >>> # Connect to shared Gitea (credentials from environment)
48
+ >>> import os
49
+ >>> client = GitServerClient(
50
+ ... gitea_url=os.getenv("GITEA_URL"),
51
+ ... username=os.getenv("GITEA_USERNAME"),
52
+ ... password=os.getenv("GITEA_PASSWORD")
53
+ ... )
54
+ >>> client.wait_for_ready()
55
+ >>> # Clone repo to workspace
56
+ >>> path = client.clone_to_workspace("my-repo", commit="abc123")
57
+ >>> # Fast reset to base state
58
+ >>> client.reset_workspace("my-repo", commit="abc123")
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ gitea_url: str,
64
+ username: str,
65
+ password: str,
66
+ workspace_dir: str = "/workspace",
67
+ ):
68
+ """Initialize Git Server Client."""
69
+ self.gitea_url = gitea_url.rstrip("/")
70
+ self.username = username
71
+ self.password = password
72
+ self.workspace_dir = Path(workspace_dir)
73
+ self.is_ready = False
74
+
75
+ # Parse Gitea URL
76
+ parsed = urlparse(self.gitea_url)
77
+ self.domain = parsed.hostname or "localhost"
78
+ self.port = parsed.port or 3000
79
+
80
+ # Ensure workspace exists
81
+ os.makedirs(self.workspace_dir, exist_ok=True)
82
+
83
+ # Configure git credentials
84
+ self._configure_git()
85
+
86
+ def _configure_git(self):
87
+ """Configure git credentials for automatic authentication."""
88
+ home_dir = Path.home()
89
+
90
+ # Git config
91
+ git_config = f"""[user]
92
+ name = {self.username}
93
+ email = {self.username}@local.env
94
+ [init]
95
+ defaultBranch = main
96
+ [credential]
97
+ helper = store
98
+ """
99
+ gitconfig_path = home_dir / ".gitconfig"
100
+ gitconfig_path.write_text(git_config)
101
+
102
+ # Git credentials
103
+ git_credentials = (
104
+ f"http://{self.username}:{self.password}@{self.domain}:{self.port}\n"
105
+ )
106
+ gitcreds_path = home_dir / ".git-credentials"
107
+ gitcreds_path.write_text(git_credentials)
108
+ gitcreds_path.chmod(0o600)
109
+
110
+ def wait_for_ready(self, timeout: int = 30) -> bool:
111
+ """
112
+ Wait for Gitea server to be ready.
113
+
114
+ Args:
115
+ timeout: Maximum seconds to wait
116
+
117
+ Returns:
118
+ True if server is ready, False otherwise
119
+ """
120
+ start_time = time.time()
121
+ while time.time() - start_time < timeout:
122
+ try:
123
+ result = subprocess.run(
124
+ ["curl", "-sf", f"{self.gitea_url}/"],
125
+ capture_output=True,
126
+ timeout=5,
127
+ )
128
+ if result.returncode == 0:
129
+ self.is_ready = True
130
+ return True
131
+ except subprocess.TimeoutExpired:
132
+ pass
133
+ except Exception:
134
+ pass
135
+
136
+ time.sleep(1)
137
+
138
+ return False
139
+
140
+ def list_repositories(self) -> list[dict[str, str]]:
141
+ """
142
+ List all repositories in Gitea.
143
+
144
+ Returns:
145
+ List of repository information dictionaries
146
+ """
147
+ if not self.is_ready:
148
+ raise RuntimeError("Gitea server is not ready")
149
+
150
+ result = subprocess.run(
151
+ [
152
+ "curl",
153
+ "-s",
154
+ f"{self.gitea_url}/api/v1/user/repos",
155
+ "-u",
156
+ f"{self.username}:{self.password}",
157
+ ],
158
+ capture_output=True,
159
+ text=True,
160
+ )
161
+
162
+ if result.returncode != 0:
163
+ return []
164
+
165
+ try:
166
+ repos = json.loads(result.stdout)
167
+ return [
168
+ {
169
+ "name": repo["name"],
170
+ "full_name": repo["full_name"],
171
+ "clone_url": repo["clone_url"],
172
+ "description": repo.get("description", ""),
173
+ }
174
+ for repo in repos
175
+ ]
176
+ except (json.JSONDecodeError, KeyError):
177
+ return []
178
+
179
+ def clone_to_workspace(
180
+ self, repo_name: str, target_dir: str | None = None, commit: str = "main"
181
+ ) -> str:
182
+ """
183
+ Clone a repository to the workspace at a specific commit.
184
+
185
+ This creates a fresh clone optimized for task isolation.
186
+
187
+ Args:
188
+ repo_name: Name of repository to clone
189
+ target_dir: Target directory name (defaults to repo_name)
190
+ commit: Commit hash or branch to check out
191
+
192
+ Returns:
193
+ Path to cloned repository
194
+
195
+ Raises:
196
+ RuntimeError: If clone fails
197
+ """
198
+ if not self.is_ready:
199
+ raise RuntimeError("Gitea server is not ready")
200
+
201
+ target_dir = target_dir or repo_name
202
+ target_path = self.workspace_dir / target_dir
203
+
204
+ # Remove existing directory if present
205
+ if target_path.exists():
206
+ shutil.rmtree(target_path)
207
+
208
+ clone_url = f"{self.gitea_url}/{self.username}/{repo_name}.git"
209
+
210
+ # Clone repository
211
+ result = subprocess.run(
212
+ ["git", "clone", clone_url, str(target_path)],
213
+ capture_output=True,
214
+ text=True,
215
+ )
216
+
217
+ if result.returncode != 0:
218
+ raise RuntimeError(f"Clone failed: {result.stderr}")
219
+
220
+ # Checkout specific commit
221
+ if commit != "main":
222
+ result = subprocess.run(
223
+ ["git", "checkout", commit],
224
+ cwd=str(target_path),
225
+ capture_output=True,
226
+ text=True,
227
+ )
228
+
229
+ if result.returncode != 0:
230
+ raise RuntimeError(f"Checkout failed: {result.stderr}")
231
+
232
+ return str(target_path)
233
+
234
+ def reset_workspace(self, repo_name: str, commit: str = "main") -> bool:
235
+ """
236
+ Fast reset of workspace to base state (optimized for task resets).
237
+
238
+ This is much faster than re-cloning. It:
239
+ 1. Checks out the target commit
240
+ 2. Resets to that commit (hard)
241
+ 3. Cleans untracked files
242
+
243
+ Args:
244
+ repo_name: Name of repository (directory in workspace)
245
+ commit: Commit hash or branch to reset to
246
+
247
+ Returns:
248
+ True if reset successful
249
+
250
+ Raises:
251
+ RuntimeError: If reset fails
252
+ """
253
+ repo_path = self.workspace_dir / repo_name
254
+
255
+ if not repo_path.exists():
256
+ raise RuntimeError(f"Repository not found in workspace: {repo_name}")
257
+
258
+ # Fetch latest (in case commit is new)
259
+ subprocess.run(
260
+ ["git", "fetch", "--all"],
261
+ cwd=str(repo_path),
262
+ capture_output=True,
263
+ )
264
+
265
+ # Checkout and hard reset to commit
266
+ result = subprocess.run(
267
+ ["git", "checkout", commit],
268
+ cwd=str(repo_path),
269
+ capture_output=True,
270
+ text=True,
271
+ )
272
+
273
+ if result.returncode != 0:
274
+ raise RuntimeError(f"Checkout failed: {result.stderr}")
275
+
276
+ result = subprocess.run(
277
+ [
278
+ "git",
279
+ "reset",
280
+ "--hard",
281
+ f"origin/{commit}" if commit != "main" else commit,
282
+ ],
283
+ cwd=str(repo_path),
284
+ capture_output=True,
285
+ text=True,
286
+ )
287
+
288
+ if result.returncode != 0:
289
+ # Try without origin/ prefix
290
+ result = subprocess.run(
291
+ ["git", "reset", "--hard", commit],
292
+ cwd=str(repo_path),
293
+ capture_output=True,
294
+ text=True,
295
+ )
296
+ if result.returncode != 0:
297
+ raise RuntimeError(f"Reset failed: {result.stderr}")
298
+
299
+ # Clean untracked files and directories
300
+ subprocess.run(
301
+ ["git", "clean", "-fdx"],
302
+ cwd=str(repo_path),
303
+ capture_output=True,
304
+ )
305
+
306
+ return True
307
+
308
+ def execute_git_command(
309
+ self, command: str, working_dir: str = ""
310
+ ) -> tuple[int, str, str]:
311
+ """
312
+ Execute a git command in the workspace.
313
+
314
+ Args:
315
+ command: Git command to execute (without 'git' prefix)
316
+ working_dir: Working directory relative to workspace
317
+
318
+ Returns:
319
+ Tuple of (exit_code, stdout, stderr)
320
+ """
321
+ work_path = (
322
+ self.workspace_dir / working_dir if working_dir else self.workspace_dir
323
+ )
324
+
325
+ if not work_path.exists():
326
+ return (1, "", f"Working directory does not exist: {work_path}")
327
+
328
+ # Split command safely
329
+ cmd_parts = ["git"] + command.split()
330
+
331
+ result = subprocess.run(
332
+ cmd_parts,
333
+ cwd=str(work_path),
334
+ capture_output=True,
335
+ text=True,
336
+ )
337
+
338
+ return (result.returncode, result.stdout, result.stderr)
339
+
340
+ def get_current_commit(self, repo_name: str) -> str:
341
+ """
342
+ Get current commit hash of a workspace repository.
343
+
344
+ Args:
345
+ repo_name: Name of repository in workspace
346
+
347
+ Returns:
348
+ Commit hash
349
+ """
350
+ repo_path = self.workspace_dir / repo_name
351
+
352
+ if not repo_path.exists():
353
+ raise RuntimeError(f"Repository not found: {repo_name}")
354
+
355
+ result = subprocess.run(
356
+ ["git", "rev-parse", "HEAD"],
357
+ cwd=str(repo_path),
358
+ capture_output=True,
359
+ text=True,
360
+ )
361
+
362
+ if result.returncode != 0:
363
+ raise RuntimeError(f"Failed to get commit: {result.stderr}")
364
+
365
+ return result.stdout.strip()
366
+
367
+ def workspace_exists(self, repo_name: str) -> bool:
368
+ """Check if a repository exists in workspace."""
369
+ return (self.workspace_dir / repo_name).exists()
src/core/tools/local_python_executor.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Local Python Executor (enhanced).
8
+
9
+ This module provides a safer wrapper around smolagents.LocalPythonExecutor
10
+ with improved exception handling and a few helpful tools registered with
11
+ the executor to make debugging executed code easier.
12
+
13
+ Key improvements:
14
+ - Register a few helper utilities via send_tools so user code can use
15
+ them for reporting (e.g. `format_exc`).
16
+ - More robust extraction of stdout/stderr/exit codes from the executor
17
+ result object, tolerant to different versions of smolagents.
18
+ - Detailed stderr on unexpected exceptions including full traceback.
19
+ - Structured logging for operational visibility.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import logging
26
+ import traceback
27
+
28
+ from smolagents import LocalPythonExecutor
29
+
30
+ from openenv.core.env_server.types import CodeExecResult
31
+
32
+ logger = logging.getLogger(__name__)
33
+ logger.addHandler(logging.NullHandler())
34
+
35
+
36
+ class PyExecutor:
37
+ """Wrapper around smolagents LocalPythonExecutor.
38
+
39
+ The wrapper registers a few non-privileged helper tools to the
40
+ LocalPythonExecutor that can be used by the executed code to
41
+ format exceptions and to safely stringify results for improved
42
+ error reporting.
43
+ """
44
+
45
+ def __init__(self, additional_imports: list[str] | None = None):
46
+ if additional_imports is None:
47
+ additional_imports = []
48
+
49
+ self._executor = LocalPythonExecutor(
50
+ additional_authorized_imports=additional_imports
51
+ )
52
+
53
+ # Register helpful utilities exposed to the execution environment.
54
+ # These are intentionally small, read-only helpers.
55
+ tools = {
56
+ # Provide a small helper to format the current exception in the
57
+ # executed context. This is a *string formatting* helper only.
58
+ "format_exc": traceback.format_exc,
59
+ # Safe JSON dumps with a fallback for non-serializable objects.
60
+ "safe_json_dumps": lambda obj: json.dumps(obj, default=lambda o: repr(o)),
61
+ }
62
+
63
+ # `send_tools` is the public API on LocalPythonExecutor to make
64
+ # helper callables available to the sandboxed runtime. We don't
65
+ # provide any builtins that could change the environment.
66
+ try:
67
+ self._executor.send_tools(tools)
68
+ except Exception:
69
+ # If the LocalPythonExecutor implementation doesn't support
70
+ # send_tools or fails, log and continue — the executor is still usable.
71
+ logger.debug(
72
+ "LocalPythonExecutor.send_tools failed; continuing without extra tools",
73
+ exc_info=True,
74
+ )
75
+
76
+ def run(self, code: str) -> CodeExecResult:
77
+ """Execute Python code and return a CodeExecResult.
78
+
79
+ This method is intentionally defensive: it attempts to extract
80
+ meaningful stdout/stderr/exit_code information from a variety of
81
+ possible return shapes that different versions of smolagents
82
+ may provide.
83
+ """
84
+ try:
85
+ exec_result = self._executor(code)
86
+
87
+ # Default values
88
+ stdout_parts: list[str] = []
89
+ stderr_parts: list[str] = []
90
+ exit_code = 0
91
+
92
+ # Extract logs/prints
93
+ try:
94
+ logs = getattr(exec_result, "logs", None)
95
+ if logs:
96
+ stdout_parts.append(str(logs))
97
+ except Exception:
98
+ logger.debug("Failed to read exec_result.logs", exc_info=True)
99
+
100
+ # Extract the result / output value
101
+ try:
102
+ if hasattr(exec_result, "output"):
103
+ out_val = exec_result.output
104
+ # If the output is not None, stringify it in a safe way
105
+ if out_val is not None:
106
+ # Prefer JSON if possible, otherwise repr
107
+ try:
108
+ stdout_parts.append(json.dumps(out_val))
109
+ except Exception:
110
+ stdout_parts.append(repr(out_val))
111
+ except Exception:
112
+ logger.debug("Failed to read exec_result.output", exc_info=True)
113
+
114
+ # Some runtime implementations may put errors on `error` or `exception`
115
+ try:
116
+ err = getattr(exec_result, "error", None)
117
+ if err:
118
+ stderr_parts.append(str(err))
119
+ except Exception:
120
+ logger.debug("Failed to read exec_result.error", exc_info=True)
121
+
122
+ try:
123
+ ex = getattr(exec_result, "exception", None)
124
+ if ex:
125
+ stderr_parts.append(str(ex))
126
+ except Exception:
127
+ logger.debug("Failed to read exec_result.exception", exc_info=True)
128
+
129
+ # Determine exit code if provided
130
+ try:
131
+ if hasattr(exec_result, "exit_code"):
132
+ exit_code = (
133
+ int(exec_result.exit_code)
134
+ if exec_result.exit_code is not None
135
+ else 0
136
+ )
137
+ elif hasattr(exec_result, "success"):
138
+ # Some versions use `success` boolean
139
+ exit_code = 0 if exec_result.success else 1
140
+ else:
141
+ # Fallback: if there were any stderr parts, treat as non-zero
142
+ exit_code = 1 if stderr_parts else 0
143
+ except Exception:
144
+ logger.debug("Failed to determine exec_result exit code", exc_info=True)
145
+ exit_code = 1 if stderr_parts else 0
146
+
147
+ # Compose the final stdout/stderr strings
148
+ stdout = "\n".join(part for part in stdout_parts if part is not None)
149
+ stderr = "\n".join(part for part in stderr_parts if part is not None)
150
+
151
+ return CodeExecResult(stdout=stdout, stderr=stderr, exit_code=exit_code)
152
+
153
+ except Exception:
154
+ # Any unexpected exception from the LocalPythonExecutor is
155
+ # returned with a full traceback to make debugging easier.
156
+ tb = traceback.format_exc()
157
+ logger.exception("LocalPythonExecutor raised an exception during run")
158
+ return CodeExecResult(stdout="", stderr=tb, exit_code=1)
src/core/utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Utility functions for OpenEnv core."""
8
+
9
+ import asyncio
10
+ import concurrent.futures
11
+
12
+
13
+ def run_async_safely(coro):
14
+ """
15
+ Run an async coroutine safely from any context.
16
+
17
+ This handles the case where we may already be inside an async event loop
18
+ (e.g., when called from an async framework). In that case, asyncio.run()
19
+ would fail, so we use a ThreadPoolExecutor to run in a separate thread.
20
+
21
+ Args:
22
+ coro: The coroutine to run
23
+
24
+ Returns:
25
+ The result of the coroutine
26
+ """
27
+ try:
28
+ loop = asyncio.get_running_loop()
29
+ except RuntimeError:
30
+ loop = None
31
+
32
+ if loop is not None:
33
+ # Already in async context - run in a thread pool
34
+ with concurrent.futures.ThreadPoolExecutor() as pool:
35
+ future = pool.submit(asyncio.run, coro)
36
+ return future.result()
37
+ else:
38
+ # No async context - use asyncio.run() directly
39
+ return asyncio.run(coro)
40
+
41
+
42
+ def convert_to_ws_url(url: str) -> str:
43
+ """
44
+ Convert an HTTP/HTTPS URL to a WS/WSS URL.
45
+
46
+ Args:
47
+ url: The URL to convert.
48
+
49
+ Returns:
50
+ The converted WebSocket URL.
51
+ """
52
+ ws_url = url.rstrip("/")
53
+ if ws_url.startswith("http://"):
54
+ ws_url = "ws://" + ws_url[7:]
55
+ elif ws_url.startswith("https://"):
56
+ ws_url = "wss://" + ws_url[8:]
57
+ elif not ws_url.startswith("ws://") and not ws_url.startswith("wss://"):
58
+ ws_url = "ws://" + ws_url
59
+ return ws_url