Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Dockerfile+1-1
- README.md+5-3
- envs/tbench2_env/README.md+3-1
- envs/tbench2_env/pyproject.toml+1-1
- envs/tbench2_env/server/Dockerfile+1-1
- envs/tbench2_env/server/app.py+14-3
- envs/tbench2_env/server/tbench2_env_environment.py+46-6
- pyproject.toml+1-1
- server/Dockerfile+1-1
- server/app.py+14-3
- server/tbench2_env_environment.py+46-6
- src/core/README.md+6-6
- src/core/__init__.py+3-1
- src/core/containers/runtime/__init__.py-2
- src/core/containers/runtime/_server_config.py+39-2
- src/core/containers/runtime/daytona_provider.py+1-1
- src/core/containers/runtime/hf_sandbox_provider.py+64-12
- src/core/containers/runtime/kubernetes_provider.pyAdded+985
- src/core/containers/runtime/modal_provider.py+22-53
- src/core/containers/runtime/providers.py+94-32
- src/core/containers/runtime/uv_provider.py+22-3
- src/core/env_client.py+62-9
- src/core/env_server/exceptions.py+11-2
- src/core/env_server/http_server.py+502-68
- src/core/env_server/interfaces.py+2-2
- src/core/env_server/mcp_environment.py+17-18
- src/core/env_server/security.pyAdded+192
- src/core/env_server/session_telemetry.pyAdded+241
- src/core/env_server/types.py+6
- src/core/env_server/web_interface.py+9-2
- src/core/harness/bridge.py+14-4
- src/core/harness/capture/forwarding.py+27
- src/core/harness/capture/graph.py+16
- src/core/harness/capture/server.py+52
- src/core/harness/capture/validate_llm.py+58-6
- src/core/harness/collect.py+34-15
- src/core/mcp_client.py+6
- src/core/openenv/auto/auto_action.py+3-3
- src/core/openenv/auto/auto_env.py+3-3
- src/core/openenv/cli/__main__.py+4-3
- src/core/openenv/cli/commands/build.py+33-59
- src/core/openenv/cli/commands/harbor.py+194-6
- src/core/openenv/cli/commands/push.py+2-4
- src/core/openenv/cli/commands/serve.py+122-57
- src/core/openenv/cli/commands/skills.py+1-1
- src/core/openenv/cli/commands/validate.py+154-4
- src/core/openenv/cli/importers/__init__.py+3-1
- src/core/openenv/cli/importers/agentenv.pyAdded+163
- src/core/openenv/cli/importers/base.py+13-2
- src/core/openenv/cli/importers/templates/agentenv_README.md.tplAdded+82
81 unmodified lines8283848581 unmodified lines# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]81 unmodified lines8283848581 unmodified lines# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && exec uvicorn server.app:app --host 0.0.0.0 --port 8000"]
7 unmodified lines8910111213148 unmodified lines23242526272875 unmodified lines104105106107108109110109 unmodified lines2202212222232242252267 unmodified linesapp_port: 8000base_path: /webtags:- openenv-0.10.0- openenv- terminal-bench-2- spaces8 unmodified lines| **Local** | Runs commands in the server process (no Docker) | Hugging Face Spaces, environments without Docker access || **Docker** | Runs each task in its own container | Full TB2.0 fidelity with custom task images |## Quick Start```python75 unmodified lines### Local Mode (Default)Commands execute directly in the server process. Ideal for HF Spaces where Docker-in-Docker is unavailable.```bash# Default - local mode109 unmodified linesThis Space is built from OpenEnv environment `tbench2_env`.- Space URL: `https://huggingface.co/spaces/openenv/tbench2`- OpenEnv pinned ref: `0.10.0`- Hub tag: `openenv`### Connecting from Code7 unmodified lines8910111213148 unmodified lines232425262728293075 unmodified lines106107108109110111112109 unmodified lines2222232242252262272287 unmodified linesapp_port: 8000base_path: /webtags:- openenv-0.15.0- openenv- terminal-bench-2- spaces8 unmodified lines| **Local** | Runs commands in the server process (no Docker) | Hugging Face Spaces, environments without Docker access || **Docker** | Runs each task in its own container | Full TB2.0 fidelity with custom task images |Try it on the [`openenv/tbench2`](https://huggingface.co/spaces/openenv/tbench2) Space, or connect a client to `https://openenv-tbench2.hf.space`.## Quick Start```python75 unmodified lines### Local Mode (Default)Commands execute on the server's host, as the server's user, with network access. Sessions share the host, the task folders and the verifier's fixed paths, so local mode serves one session at a time (use Docker mode for concurrent sessions). Ideal for HF Spaces where Docker-in-Docker is unavailable. The agent's shell gets only an allowlist of the server's environment variables (no tokens or keys), and on Linux the server is non-dumpable, so that shell can't read the server's environment through `/proc`. Keep secrets out of files that user can read.```bash# Default - local mode109 unmodified linesThis Space is built from OpenEnv environment `tbench2_env`.- Space URL: `https://huggingface.co/spaces/openenv/tbench2`- OpenEnv pinned ref: `0.15.0`- Hub tag: `openenv`### Connecting from Code
21 unmodified lines22232425262775 unmodified lines10310410510610710810921 unmodified lines| **Local** | Runs commands in the server process (no Docker) | Hugging Face Spaces, environments without Docker access || **Docker** | Runs each task in its own container | Full TB2.0 fidelity with custom task images |## Quick Start```python75 unmodified lines### Local Mode (Default)Commands execute directly in the server process. Ideal for HF Spaces where Docker-in-Docker is unavailable.```bash# Default - local mode21 unmodified lines222324252627282975 unmodified lines10510610710810911011121 unmodified lines| **Local** | Runs commands in the server process (no Docker) | Hugging Face Spaces, environments without Docker access || **Docker** | Runs each task in its own container | Full TB2.0 fidelity with custom task images |Try it on the [`openenv/tbench2`](https://huggingface.co/spaces/openenv/tbench2) Space, or connect a client to `https://openenv-tbench2.hf.space`.## Quick Start```python75 unmodified lines### Local Mode (Default)Commands execute on the server's host, as the server's user, with network access. Sessions share the host, the task folders and the verifier's fixed paths, so local mode serves one session at a time (use Docker mode for concurrent sessions). Ideal for HF Spaces where Docker-in-Docker is unavailable. The agent's shell gets only an allowlist of the server's environment variables (no tokens or keys), and on Linux the server is non-dumpable, so that shell can't read the server's environment through `/proc`. Keep secrets out of files that user can read.```bash# Default - local mode
14 unmodified lines1516171819202114 unmodified linesrequires-python = ">=3.10"dependencies = [# Core OpenEnv runtime (provides FastAPI server + HTTP client types)"openenv @ git+https://github.com/huggingface/OpenEnv.git@v0.10.0",# Environment-specific dependencies"camel-ai>=0.2.90",# Docker-backed mode (optional, for full TB2.0 compatibility)14 unmodified lines1516171819202114 unmodified linesrequires-python = ">=3.10"dependencies = [# Core OpenEnv runtime (provides FastAPI server + HTTP client types)"openenv @ git+https://github.com/openenv/OpenEnv.git@v0.15.0",# Environment-specific dependencies"camel-ai>=0.2.90",# Docker-backed mode (optional, for full TB2.0 compatibility)
77 unmodified lines7879808177 unmodified lines# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]77 unmodified lines7879808177 unmodified lines# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && exec uvicorn server.app:app --host 0.0.0.0 --port 8000"]
28 unmodified lines293031323334355 unmodified lines4142434445464748495051525310 unmodified lines6465666768693 unmodified lines7374757677787928 unmodified linesEnvironment Variables:TB2_MODE: Execution mode - "local" (default) or "docker"MAX_CONCURRENT_ENVS: Maximum concurrent WebSocket sessions (default: 8)"""import os5 unmodified lines# In-repo importsfrom tbench2_env.models import Tbench2Action, Tbench2Observation, Tbench2Statefrom .tbench2_env_environment import Tbench2DockerEnvironment, Tbench2Environmentexcept Exception as e: # pragma: no coverfrom models import Tbench2Action, Tbench2Observation, Tbench2State# Standalone imports (when environment is standalone with openenv from pip)from openenv.core.env_server.http_server import create_appfrom server.tbench2_env_environment import (Tbench2DockerEnvironment,Tbench2Environment,)10 unmodified lineselif _TB2_MODE == "local":_DEFAULT_ENVIRONMENT = Tbench2Environment_ENV_SUFFIX = " (local mode)"else:# No silent aliases: the old "auto" value claimed to auto-detect Docker# but always ran local mode, and a typo'd mode would quietly do the same.3 unmodified lines# Create the app with web interface and README integrationmax_concurrent = int(os.getenv("MAX_CONCURRENT_ENVS", "8"))app = create_app(_DEFAULT_ENVIRONMENT,28 unmodified lines293031323334355 unmodified lines41424344454647484950515253545556575810 unmodified lines6970717273747576773 unmodified lines8182838485868788899028 unmodified linesEnvironment Variables:TB2_MODE: Execution mode - "local" (default) or "docker"MAX_CONCURRENT_ENVS: Maximum concurrent WebSocket sessions (default: 8 in docker mode, 1 in local mode)"""import os5 unmodified lines# In-repo importsfrom tbench2_env.models import Tbench2Action, Tbench2Observation, Tbench2Statefrom .tbench2_env_environment import (set_non_dumpable,Tbench2DockerEnvironment,Tbench2Environment,)except Exception as e: # pragma: no coverfrom models import Tbench2Action, Tbench2Observation, Tbench2State# Standalone imports (when environment is standalone with openenv from pip)from openenv.core.env_server.http_server import create_appfrom server.tbench2_env_environment import (set_non_dumpable,Tbench2DockerEnvironment,Tbench2Environment,)10 unmodified lineselif _TB2_MODE == "local":_DEFAULT_ENVIRONMENT = Tbench2Environment_ENV_SUFFIX = " (local mode)"# The agent's shell runs as this server's user: keep it from reading this# process's environment and memory through /proc.set_non_dumpable()else:# No silent aliases: the old "auto" value claimed to auto-detect Docker# but always ran local mode, and a typo'd mode would quietly do the same.3 unmodified lines# Create the app with web interface and README integration# Local mode serves one session at a time (see Tbench2Environment).max_concurrent = int(os.getenv("MAX_CONCURRENT_ENVS", "8" if _TB2_MODE == "docker" else "1"))app = create_app(_DEFAULT_ENVIRONMENT,
76 unmodified lines7778798081829 unmodified lines92939495969798118 unmodified lines2172182192202212222235 unmodified lines2292302312322332342352362371 unmodified line23924024124224324424524628 unmodified lines27527627727827928028176 unmodified linestar.extractall(dest)def _require_terminal_toolkit() -> Any:global _CAMEL_IMPORT_ERRORif _CAMEL_IMPORT_ERROR is not None:9 unmodified lines"camel-ai (TerminalToolkit) is required for TB2. Install from PyPI or from the CAMEL repo.") from excreturn TerminalToolkitdef _download_tb2_repo(cache_dir: Path) -> Path:118 unmodified lines"""The verdict test.sh's verifier wrote to reward.txt, echoed on themarker line. None when no verdict can be recovered — no marker line, anempty value (reward.txt absent: test.sh crashed or was killed before itsverifier wrote one), or a non-numeric value. A missing verdict is ascoring failure, not a task failure: callers raise so ``evaluate``reports an error (observation.error set, reward None) instead of a 0.0indistinguishable from tests genuinely failing — RL consumers must be5 unmodified linesif not raw:return Nonetry:return float(raw)except ValueError:return Nonereturn None1 unmodified line"""Raise when the canonical harness produced no verdict (see above)."""if reward is None:raise RuntimeError("canonical harness produced no verdict (reward.txt missing after "f"tests/test.sh ran); test.sh log tail: {output[-800:]!r}")return reward28 unmodified linesclass Tbench2Environment(Environment[Tbench2Action, Tbench2Observation, Tbench2State]):"""OpenEnv wrapper around Terminal-Bench 2 tasks (local execution)."""SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self,76 unmodified lines77787980818283848586878889909192939495969798991001011021031041051069 unmodified lines116117118119120121122123124125126127128129130131132133134118 unmodified lines2532542552562572582592605 unmodified lines2662672682692702712722732742751 unmodified line27727827928028128228328428 unmodified lines31331431531631731831932032176 unmodified linestar.extractall(dest)# The only server environment variables the agent's shell gets (plus LC_*, UV_*# and the toolkit's own runtime paths). Tokens and keys stay in the server._SHELL_ENV_ALLOWLIST = ("PATH","HOME","LANG","TERM","TZ","USER","LOGNAME","SHELL","TMPDIR","PYTHONUNBUFFERED",)def set_non_dumpable() -> None:"""Linux: other processes of the same user can't read this one's /proc/<pid>/{environ,mem}."""if sys.platform.startswith("linux"):import ctypesctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLEdef _require_terminal_toolkit() -> Any:global _CAMEL_IMPORT_ERRORif _CAMEL_IMPORT_ERROR is not None:9 unmodified lines"camel-ai (TerminalToolkit) is required for TB2. Install from PyPI or from the CAMEL repo.") from excclass _TerminalToolkit(TerminalToolkit):"""Runs the agent's and the verifier's commands without the server's secrets."""def _get_env_vars(self) -> dict[str, str]:return {k: vfor k, v in super()._get_env_vars().items()if k in _SHELL_ENV_ALLOWLISTor k.startswith(("LC_", "UV_"))or k in self._runtime_env_vars}return _TerminalToolkitdef _download_tb2_repo(cache_dir: Path) -> Path:118 unmodified lines"""The verdict test.sh's verifier wrote to reward.txt, echoed on themarker line. None when no verdict can be recovered — no marker line, anempty value (reward.txt absent: test.sh crashed or was killed before itsverifier wrote one), or a value that is not a finite number (``float``also reads "nan" and "inf"). A missing verdict is ascoring failure, not a task failure: callers raise so ``evaluate``reports an error (observation.error set, reward None) instead of a 0.0indistinguishable from tests genuinely failing — RL consumers must be5 unmodified linesif not raw:return Nonetry:value = float(raw)except ValueError:return Nonereturn value if math.isfinite(value) else Nonereturn None1 unmodified line"""Raise when the canonical harness produced no verdict (see above)."""if reward is None:raise RuntimeError("canonical harness produced no verdict (reward.txt missing or not a "f"finite number after tests/test.sh ran); test.sh log tail: {output[-800:]!r}")return reward28 unmodified linesclass Tbench2Environment(Environment[Tbench2Action, Tbench2Observation, Tbench2State]):"""OpenEnv wrapper around Terminal-Bench 2 tasks (local execution)."""# Sessions share the host, the task folders and the verifier's fixed paths# (/tests, /logs/verifier), so they can't run side by side.SUPPORTS_CONCURRENT_SESSIONS: bool = Falsedef __init__(self,
14 unmodified lines1516171819202114 unmodified linesrequires-python = ">=3.10"dependencies = [# Core OpenEnv runtime (provides FastAPI server + HTTP client types)"openenv @ git+https://github.com/huggingface/OpenEnv.git@v0.10.0",# Environment-specific dependencies"camel-ai>=0.2.90",# Docker-backed mode (optional, for full TB2.0 compatibility)14 unmodified lines1516171819202114 unmodified linesrequires-python = ">=3.10"dependencies = [# Core OpenEnv runtime (provides FastAPI server + HTTP client types)"openenv @ git+https://github.com/openenv/OpenEnv.git@v0.15.0",# Environment-specific dependencies"camel-ai>=0.2.90",# Docker-backed mode (optional, for full TB2.0 compatibility)
77 unmodified lines7879808177 unmodified lines# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]77 unmodified lines7879808177 unmodified lines# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && exec uvicorn server.app:app --host 0.0.0.0 --port 8000"]
28 unmodified lines293031323334355 unmodified lines4142434445464748495051525310 unmodified lines6465666768693 unmodified lines7374757677787928 unmodified linesEnvironment Variables:TB2_MODE: Execution mode - "local" (default) or "docker"MAX_CONCURRENT_ENVS: Maximum concurrent WebSocket sessions (default: 8)"""import os5 unmodified lines# In-repo importsfrom tbench2_env.models import Tbench2Action, Tbench2Observation, Tbench2Statefrom .tbench2_env_environment import Tbench2DockerEnvironment, Tbench2Environmentexcept Exception as e: # pragma: no coverfrom models import Tbench2Action, Tbench2Observation, Tbench2State# Standalone imports (when environment is standalone with openenv from pip)from openenv.core.env_server.http_server import create_appfrom server.tbench2_env_environment import (Tbench2DockerEnvironment,Tbench2Environment,)10 unmodified lineselif _TB2_MODE == "local":_DEFAULT_ENVIRONMENT = Tbench2Environment_ENV_SUFFIX = " (local mode)"else:# No silent aliases: the old "auto" value claimed to auto-detect Docker# but always ran local mode, and a typo'd mode would quietly do the same.3 unmodified lines# Create the app with web interface and README integrationmax_concurrent = int(os.getenv("MAX_CONCURRENT_ENVS", "8"))app = create_app(_DEFAULT_ENVIRONMENT,28 unmodified lines293031323334355 unmodified lines41424344454647484950515253545556575810 unmodified lines6970717273747576773 unmodified lines8182838485868788899028 unmodified linesEnvironment Variables:TB2_MODE: Execution mode - "local" (default) or "docker"MAX_CONCURRENT_ENVS: Maximum concurrent WebSocket sessions (default: 8 in docker mode, 1 in local mode)"""import os5 unmodified lines# In-repo importsfrom tbench2_env.models import Tbench2Action, Tbench2Observation, Tbench2Statefrom .tbench2_env_environment import (set_non_dumpable,Tbench2DockerEnvironment,Tbench2Environment,)except Exception as e: # pragma: no coverfrom models import Tbench2Action, Tbench2Observation, Tbench2State# Standalone imports (when environment is standalone with openenv from pip)from openenv.core.env_server.http_server import create_appfrom server.tbench2_env_environment import (set_non_dumpable,Tbench2DockerEnvironment,Tbench2Environment,)10 unmodified lineselif _TB2_MODE == "local":_DEFAULT_ENVIRONMENT = Tbench2Environment_ENV_SUFFIX = " (local mode)"# The agent's shell runs as this server's user: keep it from reading this# process's environment and memory through /proc.set_non_dumpable()else:# No silent aliases: the old "auto" value claimed to auto-detect Docker# but always ran local mode, and a typo'd mode would quietly do the same.3 unmodified lines# Create the app with web interface and README integration# Local mode serves one session at a time (see Tbench2Environment).max_concurrent = int(os.getenv("MAX_CONCURRENT_ENVS", "8" if _TB2_MODE == "docker" else "1"))app = create_app(_DEFAULT_ENVIRONMENT,
76 unmodified lines7778798081829 unmodified lines92939495969798118 unmodified lines2172182192202212222235 unmodified lines2292302312322332342352362371 unmodified line23924024124224324424524628 unmodified lines27527627727827928028176 unmodified linestar.extractall(dest)def _require_terminal_toolkit() -> Any:global _CAMEL_IMPORT_ERRORif _CAMEL_IMPORT_ERROR is not None:9 unmodified lines"camel-ai (TerminalToolkit) is required for TB2. Install from PyPI or from the CAMEL repo.") from excreturn TerminalToolkitdef _download_tb2_repo(cache_dir: Path) -> Path:118 unmodified lines"""The verdict test.sh's verifier wrote to reward.txt, echoed on themarker line. None when no verdict can be recovered — no marker line, anempty value (reward.txt absent: test.sh crashed or was killed before itsverifier wrote one), or a non-numeric value. A missing verdict is ascoring failure, not a task failure: callers raise so ``evaluate``reports an error (observation.error set, reward None) instead of a 0.0indistinguishable from tests genuinely failing — RL consumers must be5 unmodified linesif not raw:return Nonetry:return float(raw)except ValueError:return Nonereturn None1 unmodified line"""Raise when the canonical harness produced no verdict (see above)."""if reward is None:raise RuntimeError("canonical harness produced no verdict (reward.txt missing after "f"tests/test.sh ran); test.sh log tail: {output[-800:]!r}")return reward28 unmodified linesclass Tbench2Environment(Environment[Tbench2Action, Tbench2Observation, Tbench2State]):"""OpenEnv wrapper around Terminal-Bench 2 tasks (local execution)."""SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self,76 unmodified lines77787980818283848586878889909192939495969798991001011021031041051069 unmodified lines116117118119120121122123124125126127128129130131132133134118 unmodified lines2532542552562572582592605 unmodified lines2662672682692702712722732742751 unmodified line27727827928028128228328428 unmodified lines31331431531631731831932032176 unmodified linestar.extractall(dest)# The only server environment variables the agent's shell gets (plus LC_*, UV_*# and the toolkit's own runtime paths). Tokens and keys stay in the server._SHELL_ENV_ALLOWLIST = ("PATH","HOME","LANG","TERM","TZ","USER","LOGNAME","SHELL","TMPDIR","PYTHONUNBUFFERED",)def set_non_dumpable() -> None:"""Linux: other processes of the same user can't read this one's /proc/<pid>/{environ,mem}."""if sys.platform.startswith("linux"):import ctypesctypes.CDLL(None, use_errno=True).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLEdef _require_terminal_toolkit() -> Any:global _CAMEL_IMPORT_ERRORif _CAMEL_IMPORT_ERROR is not None:9 unmodified lines"camel-ai (TerminalToolkit) is required for TB2. Install from PyPI or from the CAMEL repo.") from excclass _TerminalToolkit(TerminalToolkit):"""Runs the agent's and the verifier's commands without the server's secrets."""def _get_env_vars(self) -> dict[str, str]:return {k: vfor k, v in super()._get_env_vars().items()if k in _SHELL_ENV_ALLOWLISTor k.startswith(("LC_", "UV_"))or k in self._runtime_env_vars}return _TerminalToolkitdef _download_tb2_repo(cache_dir: Path) -> Path:118 unmodified lines"""The verdict test.sh's verifier wrote to reward.txt, echoed on themarker line. None when no verdict can be recovered — no marker line, anempty value (reward.txt absent: test.sh crashed or was killed before itsverifier wrote one), or a value that is not a finite number (``float``also reads "nan" and "inf"). A missing verdict is ascoring failure, not a task failure: callers raise so ``evaluate``reports an error (observation.error set, reward None) instead of a 0.0indistinguishable from tests genuinely failing — RL consumers must be5 unmodified linesif not raw:return Nonetry:value = float(raw)except ValueError:return Nonereturn value if math.isfinite(value) else Nonereturn None1 unmodified line"""Raise when the canonical harness produced no verdict (see above)."""if reward is None:raise RuntimeError("canonical harness produced no verdict (reward.txt missing or not a "f"finite number after tests/test.sh ran); test.sh log tail: {output[-800:]!r}")return reward28 unmodified linesclass Tbench2Environment(Environment[Tbench2Action, Tbench2Observation, Tbench2State]):"""OpenEnv wrapper around Terminal-Bench 2 tasks (local execution)."""# Sessions share the host, the task folders and the verifier's fixed paths# (/tests, /logs/verifier), so they can't run side by side.SUPPORTS_CONCURRENT_SESSIONS: bool = Falsedef __init__(self,
164 unmodified lines16516616716816917017117217317417517617717853 unmodified lines232233234235236237164 unmodified linesprovider.stop_container()```### Kubernetes Provider (Coming Soon)```pythonfrom openenv.core.containers.runtime import KubernetesProviderprovider = KubernetesProvider(namespace="envs")base_url = provider.start_container("my-env:latest")# Use environment...provider.stop_container()```53 unmodified lines## Links- **Homepage**: https://github.com/huggingface/OpenEnv- **Documentation**: https://github.com/huggingface/OpenEnv/blob/main/README.md- **Bug Tracker**: https://github.com/huggingface/OpenEnv/issues164 unmodified lines16516616716816917017117217317417517617717853 unmodified lines232233234235236237164 unmodified linesprovider.stop_container()```### Kubernetes Provider```pythonfrom openenv.core.containers.runtime.kubernetes_provider import KubernetesProviderprovider = KubernetesProvider(namespace="envs")base_url = provider.start_container("my-env:latest")provider.wait_for_ready(base_url)provider.stop_container()```53 unmodified lines## Links- **Homepage**: https://github.com/openenv/OpenEnv- **Documentation**: https://github.com/openenv/OpenEnv/blob/main/README.md- **Bug Tracker**: https://github.com/openenv/OpenEnv/issues
10 unmodified lines111213141516178 unmodified lines26272829303110 unmodified lines42434445464710 unmodified linesfrom .env_server import * # noqa: F403if TYPE_CHECKING:from .env_client import EnvClientfrom .generic_client import GenericAction, GenericEnvClientfrom .llm_client import (AnthropicClient,8 unmodified lines__all__ = ["EnvClient","SyncEnvClient","GenericEnvClient","GenericAction",10 unmodified lines_LAZY_ATTRS = {"EnvClient": (".env_client", "EnvClient"),"SyncEnvClient": (".sync_client", "SyncEnvClient"),"GenericEnvClient": (".generic_client", "GenericEnvClient"),"GenericAction": (".generic_client", "GenericAction"),10 unmodified lines111213141516178 unmodified lines2627282930313210 unmodified lines4344454647484910 unmodified linesfrom .env_server import * # noqa: F403if TYPE_CHECKING:from .env_client import EnvClient, SessionLostErrorfrom .generic_client import GenericAction, GenericEnvClientfrom .llm_client import (AnthropicClient,8 unmodified lines__all__ = ["EnvClient","SessionLostError","SyncEnvClient","GenericEnvClient","GenericAction",10 unmodified lines_LAZY_ATTRS = {"EnvClient": (".env_client", "EnvClient"),"SessionLostError": (".env_client", "SessionLostError"),"SyncEnvClient": (".sync_client", "SyncEnvClient"),"GenericEnvClient": (".generic_client", "GenericEnvClient"),"GenericAction": (".generic_client", "GenericAction"),
4 unmodified lines5678910118 unmodified lines202122232425264 unmodified linesfrom .providers import (ContainerProvider,DockerSwarmProvider,KubernetesProvider,LocalDockerProvider,RuntimeProvider,)8 unmodified lines"ContainerProvider","DockerSwarmProvider","LocalDockerProvider","KubernetesProvider","RuntimeProvider","UVProvider",]4 unmodified lines56789108 unmodified lines1920212223244 unmodified linesfrom .providers import (ContainerProvider,DockerSwarmProvider,LocalDockerProvider,RuntimeProvider,)8 unmodified lines"ContainerProvider","DockerSwarmProvider","LocalDockerProvider","RuntimeProvider","UVProvider",]
29 unmodified lines303132333435363738394029 unmodified linesdef parse_dockerfile_cmd(dockerfile_content: str) -> str | None:"""Extract the server command from the last Dockerfile ``CMD``."""last_cmd: str | None = Nonefor line in dockerfile_content.splitlines():stripped = line.strip()if stripped.startswith("#"):continuematch = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE)if match:last_cmd = match.group(1).strip()29 unmodified lines30313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767729 unmodified linesdef parse_dockerfile_cmd(dockerfile_content: str) -> str | None:"""Extract the server command from the last Dockerfile ``CMD``."""last_cmd: str | None = Noneinstruction = ""escape = "\\"directives = Truefor line in dockerfile_content.splitlines():stripped = line.lstrip()if stripped.startswith("#"):if directives:directive = re.fullmatch(r"#\s*(syntax|check|escape)\s*=\s*(.+)",stripped,flags=re.IGNORECASE,)if directive is None:directives = Falseelif directive[1].lower() == "escape" and directive[2].strip() in ("\\","`",):escape = directive[2].strip()continueif not stripped.strip():directives = Falsecontinuedirectives = Falseif not instruction:match = re.match(r"\s*CMD\s+(.+)", line, flags=re.IGNORECASE)if match:last_cmd = match.group(1).strip()continuation = re.search(rf"(?<!{re.escape(escape)}){re.escape(escape)}[ \t]*$", line)if continuation:instruction += line[: continuation.start()]continueinstruction += linematch = re.match(r"\s*CMD\s+(.+)", instruction, flags=re.IGNORECASE)if match:last_cmd = match.group(1).strip()instruction = ""if instruction:match = re.match(r"\s*CMD\s+(.+)", instruction, flags=re.IGNORECASE)if match:last_cmd = match.group(1).strip()
2 unmodified lines34567892 unmodified lines"""Daytona container provider for running OpenEnv environments in Daytona cloud sandboxes.Requires the ``daytona`` SDK: ``pip install daytona>=0.10``"""from __future__ import annotations2 unmodified lines34567892 unmodified lines"""Daytona container provider for running OpenEnv environments in Daytona cloud sandboxes.Requires the ``daytona`` SDK: ``pip install 'daytona>=0.10,<1'``"""from __future__ import annotations
9 unmodified lines1011121314158 unmodified lines24252627282965 unmodified lines959697989910030 unmodified lines13113213313413513613713813914014114214312 unmodified lines15615715815916016116238 unmodified lines20120220320420520620720820921021121221313 unmodified lines22722822923023123223323423523635 unmodified lines27227327427527627727827931 unmodified lines3113123133143153163173183193203213223233249 unmodified linesimport asyncioimport hashlibimport socketimport threadingimport time8 unmodified linesfrom .providers import ContainerProvider_DEFAULT_PORT = 8000_SERVER_COMMAND = ('export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; '65 unmodified linesclass _LocalAuthProxy:def __init__(self, *, target_url: str, headers: dict[str, str]):self.target_url = target_url.rstrip("/")self.headers = headers30 unmodified linesdata=body,headers=headers,timeout=60.0,allow_redirects=True,)except requests.RequestException:return Response(content=b"upstream HF job unreachable",status_code=502,)response_headers = {key: valuefor key, value in upstream.headers.items()12 unmodified linesif query:target = f"{target}?{query}"headers = {**self.headers, "accept": "*/*"}upstream = await self._connect_upstream_websocket(target, headers)await websocket.accept()try:to_upstream = asyncio.create_task(38 unmodified lines) -> Any:last_error: Exception | None = Nonefor _ in range(5):try:return await ws_connect(target,additional_headers=headers,max_size=_MAX_WS_MESSAGE_SIZE,compression=None,)except Exception as exc:last_error = excawait asyncio.sleep(0.5)13 unmodified linesawait websocket.send_text(message)def stop(self) -> None:if self._server is None or self._thread is None:returnself._server.should_exit = Trueself._thread.join(timeout=5.0)self._server = Noneself._thread = None35 unmodified linesenv_vars: dict[str, str] | None = None,**kwargs: Any,) -> str:if self._sandbox is not None:raise RuntimeError("HFSandboxProvider already has an active service")if kwargs:unsupported = ", ".join(sorted(kwargs))raise ValueError(31 unmodified linesraisedef stop_container(self) -> None:if self._proxy is not None:self._proxy.stop()self._proxy = Noneif self._sandbox is not None:sandbox = self._sandboxself._sandbox = Nonewith suppress(Exception):sandbox.kill()def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None:deadline = time.time() + timeout_s9 unmodified lines101112131415168 unmodified lines252627282930313265 unmodified lines989910010110210310410510610710810911011111211311430 unmodified lines14514614714814915015115215315415515615715815916016116216316412 unmodified lines17717817918018118218318418518618718818919019119238 unmodified lines23123223323423523623723823924024124224324424524624724813 unmodified lines26226326426526626726826927027127227327427527627727827935 unmodified lines31531631731831932032132232332432531 unmodified lines3573583593603613623633643653663673683693703713723733743753769 unmodified linesimport asyncioimport hashlibimport loggingimport socketimport threadingimport time8 unmodified linesfrom .providers import ContainerProviderlogger = logging.getLogger(__name__)_DEFAULT_PORT = 8000_SERVER_COMMAND = ('export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; '65 unmodified linesclass _LocalAuthProxy:"""Loopback proxy that adds the HF auth headers to every request.Copied into agent_sandbox_provider._LocalAuthProxy; keep the copiesaligned.Limitations: bodies are buffered (a streamed upstream response such asSSE is withheld until it ends), only JSON text frames are relayedupstream (binary client frames and close codes are not forwarded), andupstream redirects are rejected. EnvClient uses none of these."""def __init__(self, *, target_url: str, headers: dict[str, str]):self.target_url = target_url.rstrip("/")self.headers = headers30 unmodified linesdata=body,headers=headers,timeout=60.0,allow_redirects=False,)except requests.RequestException:return Response(content=b"upstream HF job unreachable",status_code=502,)if 300 <= upstream.status_code < 400:# Following a redirect would replay the body and the injected# headers to another origin and could downgrade https to http.return Response(content=b"upstream HF job redirected; rejected",status_code=502,)response_headers = {key: valuefor key, value in upstream.headers.items()12 unmodified linesif query:target = f"{target}?{query}"headers = {**self.headers, "accept": "*/*"}try:upstream = await self._connect_upstream_websocket(target, headers)except Exception:# Never propagate the upstream exception: its message can embed# the target URL, which may carry credentials. Deny generically# instead.logger.warning("HF sandbox WebSocket upstream handshake failed")with suppress(Exception):await websocket.close(code=1011)returnawait websocket.accept()try:to_upstream = asyncio.create_task(38 unmodified lines) -> Any:last_error: Exception | None = Nonefor _ in range(5):connector = ws_connect(target,additional_headers=headers,max_size=_MAX_WS_MESSAGE_SIZE,compression=None,)# Never follow handshake redirects: websockets replays# additional_headers to the redirect target, which would leak the# auth headers to another origin.connector.process_redirect = lambda exc: exctry:return await connectorexcept Exception as exc:last_error = excawait asyncio.sleep(0.5)13 unmodified linesawait websocket.send_text(message)def stop(self) -> None:"""Shut the proxy down. Raises `RuntimeError` if the thread will notexit; the handles are then retained so a later call can retry, insteadof silently leaking a thread that keeps the loopback port bound."""if self._server is None or self._thread is None:returnself._server.should_exit = True# Bound the graceful drain: do not wait out long-lived upstream# responses that would outlive the 5s join below.self._server.force_exit = Trueself._thread.join(timeout=5.0)if self._thread.is_alive():raise RuntimeError("HF sandbox auth proxy did not stop")self._server = Noneself._thread = None35 unmodified linesenv_vars: dict[str, str] | None = None,**kwargs: Any,) -> str:if self._sandbox is not None or self._proxy is not None:raise RuntimeError("HFSandboxProvider already has an active service, or a proxy ""still awaits cleanup. Call stop_container() first.")if kwargs:unsupported = ", ".join(sorted(kwargs))raise ValueError(31 unmodified linesraisedef stop_container(self) -> None:proxy_error: RuntimeError | None = Noneif self._proxy is not None:try:self._proxy.stop()self._proxy = Noneexcept RuntimeError as exc:proxy_error = excif self._sandbox is not None:sandbox = self._sandboxself._sandbox = Nonewith suppress(Exception):sandbox.kill()if proxy_error is not None:raise proxy_errordef wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None:deadline = time.time() + timeout_s
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985# SPDX-License-Identifier: BSD-3-Clause
"""Kubernetes container provider for running OpenEnv environments in-cluster.
Requires the ``kubernetes`` client: ``pip install openenv[kubernetes]``
One provider instance owns one Pod and one Service, matching``LocalDockerProvider`` owning one container. The returned ``base_url`` is theshort in-cluster Service address ``http://{name}.{namespace}:{port}``. Pod DNSsearch completes that to the cluster domain, so the provider does not hardcode``.svc.cluster.local``. That plaintext URL is the in-cluster exceptionconfirmed for this provider: ``ModalProvider`` and ``ACASandboxProvider`` stillrefuse non-HTTPS tunnel URLs. This provider never returns a URL it did notconstruct from a validated name, namespace, and port, and it does not copythat URL or raw API bodies into errors."""
from __future__ import annotations
import reimport secretsimport timefrom typing import Any, Mapping, Optional
from .providers import ContainerProvider
_CONTAINER_PORT = 8000_CONTAINER_NAME = "env"_DEFAULT_NAMESPACE = "default"_NAME_PREFIX = "openenv-"
# ``openenv-`` + slug + ``-`` + millisecond timestamp + ``-`` + 4 hex chars._SLUG_MAX = 32
_DNS_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")_LABEL_NAME = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$")_LABEL_VALUE = re.compile(r"^([A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$")_SAFE_REASON = re.compile(r"^[A-Za-z][A-Za-z0-9]{0,63}$")
# Applied last so a caller-supplied label cannot drop ownership or retarget# the Service selector._SELECTOR_KEY = "app.kubernetes.io/instance"
_START_KWARGS = { "resources", "runtime_class_name", "image_pull_secrets", "labels", "service_account_name", "automount_service_account_token",}
def _raise_install_error(exc: ImportError) -> None: raise RuntimeError( "KubernetesProvider requires the kubernetes client. " "Install it with `pip install openenv[kubernetes]`." ) from exc
def _dns_label(value: str, *, max_length: int, what: str) -> str: """Return *value* as a DNS-1123 label, or raise ``ValueError``.
Namespace and runtime class names are validated, not rewritten: rewriting them would target a different object than the one the caller named. """ if not isinstance(value, str) or not _DNS_LABEL.fullmatch(value): raise ValueError( f"{what} must be a DNS-1123 label: lowercase alphanumeric " "characters or '-', starting and ending with an alphanumeric." ) if not 1 <= len(value) <= max_length: raise ValueError(f"{what} must be 1 to {max_length} characters.") return value
def _slug(image: str) -> str: """DNS-1123 slug from an image reference. Raises if nothing usable remains.""" raw = image.split("/")[-1].split("@")[0].split(":")[0] cleaned = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-") cleaned = re.sub(r"-{2,}", "-", cleaned)[:_SLUG_MAX].strip("-") if not cleaned or not _DNS_LABEL.fullmatch(cleaned): raise ValueError( "image does not yield a valid Kubernetes name. " "Use an image reference with an alphanumeric name." ) return cleaned
def _resource_name(image: str) -> str: suffix = f"{int(time.time() * 1000)}-{secrets.token_hex(2)}" name = f"{_NAME_PREFIX}{_slug(image)}-{suffix}" if len(name) > 63 or not _DNS_LABEL.fullmatch(name): raise ValueError("generated Kubernetes name is not a valid DNS-1123 label.") return name
def _label_key(key: str) -> str: if not isinstance(key, str) or len(key) > 253: raise ValueError( "Kubernetes label keys must be strings of at most 253 characters." ) prefix, sep, name = key.rpartition("/") if not _LABEL_NAME.fullmatch(name): raise ValueError(f"Invalid Kubernetes label key {key!r}.") if sep and (len(prefix) > 253 or not _dns_subdomain(prefix)): raise ValueError(f"Invalid Kubernetes label key prefix {prefix!r}.") return key
def _dns_subdomain(value: str) -> bool: if not value or len(value) > 253: return False return all(_DNS_LABEL.fullmatch(part) for part in value.split("."))
def _label_value(value: str) -> str: if not isinstance(value, str) or not _LABEL_VALUE.fullmatch(value): raise ValueError( "Kubernetes label values must be 63 characters or fewer and contain " "only alphanumeric characters, '-', '_' or '.'." ) return value
def _ownership_labels(name: str) -> dict[str, str]: return { "app.kubernetes.io/name": "openenv", "app.kubernetes.io/instance": name, "app.kubernetes.io/managed-by": "openenv", "app.kubernetes.io/part-of": "openenv", "app.kubernetes.io/component": "environment", }
def _merged_labels(name: str, extra: Optional[Mapping[str, str]]) -> dict[str, str]: labels: dict[str, str] = {} if extra: if not isinstance(extra, Mapping): raise ValueError("labels must be a mapping of strings.") for key, value in extra.items(): labels[_label_key(key)] = _label_value(value) labels.update(_ownership_labels(name)) return labels
def _safe_reason(reason: Optional[str]) -> Optional[str]: """Keep kubelet reason codes. Drop anything else so API text cannot leak.""" if isinstance(reason, str) and _SAFE_REASON.fullmatch(reason): return reason return None
class _NamespaceMissing(RuntimeError): """Creating a namespaced object returned 404: the namespace is absent."""
class _CreateConflict(RuntimeError): """Creating a namespaced object returned 409: the name is already taken."""
class _TransientStatusError(RuntimeError): """A Pod status read can be retried within the readiness deadline."""
def _incluster_base_url(name: str, namespace: str, port: int) -> str: # *name* and *namespace* are already DNS-1123 labels and *port* is an int, # so this cannot be steered by a status field from the API server. # ``name.namespace`` is completed by the Pod DNS search list # (``svc.<cluster-domain>``), which works when the cluster domain is not # ``cluster.local``. return f"http://{name}.{namespace}:{port}"
def _owned_by_provider(labels: Any, name: str) -> bool: if not isinstance(labels, Mapping): return False return ( labels.get("app.kubernetes.io/managed-by") == "openenv" and labels.get("app.kubernetes.io/instance") == name )
class _DefaultKubernetesAdapter: """Thin adapter over the official ``kubernetes`` client.
The provider talks to this private adapter instead of spreading SDK details through its own logic; tests inject a duck-typed fake in its place. """
def __init__( self, *, namespace: str, kubeconfig: Optional[str], context: Optional[str], ): try: from kubernetes import client, config from kubernetes.client.exceptions import ApiException except ImportError as exc: _raise_install_error(exc)
self._client = client self._ApiException = ApiException self._namespace = namespace self._load_config(config, kubeconfig=kubeconfig, context=context) configuration = client.Configuration.get_default_copy() # Readiness owns the retry deadline; SDK retries would multiply it. configuration.retries = 0 self._api = client.CoreV1Api(client.ApiClient(configuration=configuration))
def _load_config( self, config: Any, *, kubeconfig: Optional[str], context: Optional[str] ) -> None: if kubeconfig is not None or context is not None: config.load_kube_config(config_file=kubeconfig, context=context) return try: config.load_incluster_config() except config.ConfigException: config.load_kube_config()
def _api_error(self, exc: Exception, action: str, *, missing_ok: bool) -> None: status = getattr(exc, "status", None) if missing_ok and status == 404: return if status == 409: raise _CreateConflict( f"Kubernetes {action} name is already in use" ) from None if status == 404 and action.startswith("create "): raise _NamespaceMissing( "Kubernetes namespace does not exist. " "KubernetesProvider does not create namespaces." ) from None # The API body can echo object contents. Do not chain it into the error. raise RuntimeError(f"Failed to {action} Kubernetes resource") from None
def create_pod(self, manifest: Mapping[str, Any]) -> None: try: self._api.create_namespaced_pod(self._namespace, self._pod(manifest)) except self._ApiException as exc: self._api_error(exc, "create Pod", missing_ok=False)
def create_service(self, manifest: Mapping[str, Any]) -> None: try: self._api.create_namespaced_service( self._namespace, self._service(manifest) ) except self._ApiException as exc: self._api_error(exc, "create Service", missing_ok=False)
def pod_labels(self, name: str) -> Optional[dict[str, str]]: """Return Pod labels, or ``None`` when the Pod does not exist.""" return self._resource_labels(name, self._api.read_namespaced_pod, "read Pod")
def service_labels(self, name: str) -> Optional[dict[str, str]]: """Return Service labels, or ``None`` when the Service does not exist.""" return self._resource_labels( name, self._api.read_namespaced_service, "read Service" )
def _resource_labels( self, name: str, read: Any, action: str ) -> Optional[dict[str, str]]: try: obj = read(name, self._namespace) except self._ApiException as exc: if getattr(exc, "status", None) == 404: return None self._api_error(exc, action, missing_ok=False) raise RuntimeError(f"Failed to {action} Kubernetes resource") from None metadata = getattr(obj, "metadata", None) labels = getattr(metadata, "labels", None) if metadata is not None else None if not isinstance(labels, Mapping): return {} return {str(key): str(value) for key, value in labels.items()}
def delete_pod(self, name: str) -> None: try: self._api.delete_namespaced_pod(name, self._namespace) except self._ApiException as exc: self._api_error(exc, "delete Pod", missing_ok=True)
def delete_service(self, name: str) -> None: try: self._api.delete_namespaced_service(name, self._namespace) except self._ApiException as exc: self._api_error(exc, "delete Service", missing_ok=True)
def pod_status( self, name: str, timeout_s: float = 30.0 ) -> dict[str, Optional[str]]: from urllib3.exceptions import HTTPError
try: # Older supported SDKs ignore a float timeout. Split the budget # between connect and read using their supported tuple form. pod = self._api.read_namespaced_pod( name, self._namespace, _request_timeout=(timeout_s / 2, timeout_s / 2), ) except Exception as exc: status = getattr(exc, "status", None) if ( isinstance(exc, (TimeoutError, HTTPError)) or status == 429 or (isinstance(status, int) and 500 <= status < 600) ): raise _TransientStatusError( "Kubernetes Pod status read failed" ) from None self._api_error(exc, "read Pod", missing_ok=False) raise RuntimeError("Failed to read Kubernetes Pod") from None status = getattr(pod, "status", None) phase = getattr(status, "phase", None) if status is not None else None reason = None if status is not None: for container in status.container_statuses or []: state = getattr(container, "state", None) waiting = getattr(state, "waiting", None) if state is not None else None terminated = ( getattr(state, "terminated", None) if state is not None else None ) if waiting is not None and getattr(waiting, "reason", None): reason = waiting.reason elif terminated is not None and getattr(terminated, "reason", None): reason = terminated.reason return {"phase": phase or "Unknown", "reason": reason}
def _metadata(self, meta: Mapping[str, Any]) -> Any: return self._client.V1ObjectMeta( name=meta["name"], namespace=meta["namespace"], labels=dict(meta["labels"]), )
def _pod(self, manifest: Mapping[str, Any]) -> Any: spec = manifest["spec"] container = spec["containers"][0] container_kwargs: dict[str, Any] = { "name": container["name"], "image": container["image"], "ports": [ self._client.V1ContainerPort( name=port["name"], container_port=port["container_port"] ) for port in container["ports"] ], } if container.get("env"): container_kwargs["env"] = [ self._client.V1EnvVar(name=item["name"], value=item["value"]) for item in container["env"] ] resources = container.get("resources") if resources: container_kwargs["resources"] = self._client.V1ResourceRequirements( requests=resources.get("requests"), limits=resources.get("limits"), ) pod_kwargs: dict[str, Any] = { "restart_policy": spec["restart_policy"], "automount_service_account_token": spec["automount_service_account_token"], "containers": [self._client.V1Container(**container_kwargs)], } if spec.get("runtime_class_name"): pod_kwargs["runtime_class_name"] = spec["runtime_class_name"] if spec.get("service_account_name"): pod_kwargs["service_account_name"] = spec["service_account_name"] if spec.get("image_pull_secrets"): pod_kwargs["image_pull_secrets"] = [ self._client.V1LocalObjectReference(name=secret) for secret in spec["image_pull_secrets"] ] return self._client.V1Pod( metadata=self._metadata(manifest["metadata"]), spec=self._client.V1PodSpec(**pod_kwargs), )
def _service(self, manifest: Mapping[str, Any]) -> Any: spec = manifest["spec"] port = spec["ports"][0] return self._client.V1Service( metadata=self._metadata(manifest["metadata"]), spec=self._client.V1ServiceSpec( selector=dict(spec["selector"]), ports=[ self._client.V1ServicePort( name=port["name"], port=port["port"], target_port=port["target_port"], protocol=port["protocol"], ) ], ), )
class KubernetesProvider(ContainerProvider): """ Container provider that runs one environment as one Pod and one Service.
``start_container`` returns ``http://{name}.{namespace}:{port}``. That address is reachable only from inside the cluster: Pod DNS search expands it under ``svc.<cluster-domain>``. It is plaintext on purpose: in-cluster HTTP is the connectivity decision for this provider. Cloud sandbox providers keep their own HTTPS requirement.
The namespace must already exist. This provider does not create namespaces, Deployments, Ingress objects, or port-forwards.
Only one Pod is active per provider. Calling ``start_container`` again before ``stop_container()`` / ``close()`` raises ``RuntimeError`` rather than orphaning the running Pod. A failed start deletes a resource only after its OpenEnv ownership labels match. When a create response is lost and that read fails, the resource stays unconfirmed: ``stop_container`` reads the labels again and deletes only on a match. ``stop_container`` is safe to call more than once.
The Pod does not mount a service-account token unless ``automount_service_account_token=True`` is passed to ``start_container``.
Example: ```python from openenv.core.containers.runtime.kubernetes_provider import ( KubernetesProvider, )
provider = KubernetesProvider(namespace="openenv") base_url = provider.start_container("echo-env:latest") provider.wait_for_ready(base_url) provider.stop_container() ``` """
def __init__( self, *, image: str | None = None, env_vars: dict[str, str] | None = None, namespace: str = _DEFAULT_NAMESPACE, kubeconfig: str | None = None, context: str | None = None, _adapter: Any = None, ): """ Args: image (`str`, *optional*): Registry image used when ``start_container()`` is called without an image. env_vars (`dict`, *optional*): Environment variables used when ``start_container()`` is called without ``env_vars``. namespace (`str`, *optional*, defaults to ``"default"``): Existing namespace for the Pod and Service. Not created. kubeconfig (`str`, *optional*): Kubeconfig path. When omitted, in-cluster config is tried and then the default kubeconfig. context (`str`, *optional*): Kubeconfig context. Implies kubeconfig loading rather than in-cluster config. """ self._image = image self._env_vars = env_vars self._namespace = _dns_label(namespace, max_length=63, what="namespace") self._name: str | None = None self._base_url: str | None = None self._service_port: int | None = None self._pod_created = False self._service_created = False self._pod_unconfirmed = False self._service_unconfirmed = False
if _adapter is None: self._adapter: Any = _DefaultKubernetesAdapter( namespace=self._namespace, kubeconfig=kubeconfig, context=context, ) else: self._adapter = _adapter
@property def base_url(self) -> str: """URL returned by the last successful ``start_container``.""" if self._base_url is None: raise RuntimeError( "KubernetesProvider has no active base_url. Start the provider " "before reading base_url." ) return self._base_url
def start_container( self, image: str | None = None, port: int | None = None, env_vars: dict[str, str] | None = None, **kwargs: Any, ) -> str: """ Create one Pod and one Service and return the in-cluster base URL.
Args: image (`str`, *optional*): Registry image. May be omitted when supplied to the constructor. port (`int`, *optional*): Service port. Defaults to 8000. The container always listens on 8000, matching ``LocalDockerProvider``. env_vars (`dict`, *optional*): Environment variables for the container. Replaces constructor ``env_vars`` when passed, including an empty dict. **kwargs: ``resources``, ``runtime_class_name``, ``image_pull_secrets``, ``labels``, ``service_account_name``, and ``automount_service_account_token``. Unknown keys raise ``ValueError``.
Returns: `str`: ``http://{name}.{namespace}:{port}``. """ if self._has_tracked_resources() or self._base_url is not None: raise RuntimeError( "KubernetesProvider already has an active Pod. Call " "stop_container() (or close()) before starting another — a " "second start would orphan the running Pod." )
unknown = set(kwargs) - _START_KWARGS if unknown: raise ValueError( f"Unsupported kwargs for KubernetesProvider: {sorted(unknown)}" )
effective_image = image if image is not None else self._image if not isinstance(effective_image, str) or not effective_image: raise ValueError( "KubernetesProvider requires an image. Pass it to the " "constructor or start_container()." ) service_port = _CONTAINER_PORT if port is None else port if isinstance(service_port, bool) or not isinstance(service_port, int): raise ValueError("port must be an integer.") if not 1 <= service_port <= 65535: raise ValueError("port must be between 1 and 65535.")
effective_env = self._env_vars if env_vars is None else env_vars env_list = _env_list(effective_env) resources = _resources(kwargs.get("resources")) runtime_class_name = _optional_dns_subdomain( kwargs.get("runtime_class_name"), what="runtime_class_name" ) service_account_name = _optional_dns_subdomain( kwargs.get("service_account_name"), what="service_account_name" ) image_pull_secrets = _secret_names(kwargs.get("image_pull_secrets")) automount = kwargs.get("automount_service_account_token", False) if not isinstance(automount, bool): raise ValueError("automount_service_account_token must be a bool.")
name = _resource_name(effective_image) labels = _merged_labels(name, kwargs.get("labels")) self._name = name self._service_port = service_port try: self._adapter.create_pod( _pod_manifest( name=name, namespace=self._namespace, labels=labels, image=effective_image, env_list=env_list, resources=resources, runtime_class_name=runtime_class_name, service_account_name=service_account_name, image_pull_secrets=image_pull_secrets, automount_service_account_token=automount, ) ) self._pod_created = True self._adapter.create_service( _service_manifest( name=name, namespace=self._namespace, labels=labels, service_port=service_port, ) ) self._service_created = True except BaseException as exc: # Interrupts can also arrive after the API created a resource. # A cleanup failure must not mask the original error. try: self._cleanup_after_failed_start(exc) except Exception: pass raise
self._base_url = _incluster_base_url(name, self._namespace, service_port) return self._base_url
def _cleanup_after_failed_start(self, exc: BaseException) -> None: """Delete objects this start may have created.
A 409 is someone else's name, and a 404 means the namespace is missing, so those do not probe. Any other create error may mean the API server applied the object and the client lost the response. Only the resource whose create was attempted is checked. It is deleted only when the OpenEnv ownership labels match. A failed read is recorded as unconfirmed, which is not the same as a successful create: a later ``stop_container()`` reads the labels again before deleting. """ uncertain = not isinstance(exc, (_CreateConflict, _NamespaceMissing)) # Service create runs only after Pod create has succeeded. service_was_attempted = self._pod_created self._release("pod", uncertain=uncertain) self._release("service", uncertain=uncertain and service_was_attempted) if not self._has_tracked_resources(): self._name = None self._base_url = None self._service_port = None
def _release(self, kind: str, *, uncertain: bool) -> None: if self._created(kind): self._delete_tracked(kind) return if not uncertain: return owned = self._lookup_owned(kind) if owned is None: self._set_unconfirmed(kind, True) return if not owned: return self._set_created(kind, True) self._delete_tracked(kind)
def _lookup_owned(self, kind: str) -> Optional[bool]: """Return whether *kind* at ``_name`` is ours.
``None`` means the read itself failed. Callers record that as unconfirmed. They do not treat it as a confirmed create. """ if self._name is None: return False try: if kind == "pod": labels = self._adapter.pod_labels(self._name) else: labels = self._adapter.service_labels(self._name) except Exception: return None if labels is None: return False return _owned_by_provider(labels, self._name)
def _delete_tracked(self, kind: str) -> None: """Delete a resource already known to be ours.
A failed delete stays confirmed so ``stop_container()`` can retry it. """ if self._name is None: return try: if kind == "pod": self._adapter.delete_pod(self._name) else: self._adapter.delete_service(self._name) except Exception: self._set_created(kind, True) return self._set_created(kind, False)
def _created(self, kind: str) -> bool: if kind == "pod": return self._pod_created return self._service_created
def _set_created(self, kind: str, created: bool) -> None: if kind == "pod": self._pod_created = created else: self._service_created = created
def _unconfirmed(self, kind: str) -> bool: if kind == "pod": return self._pod_unconfirmed return self._service_unconfirmed
def _set_unconfirmed(self, kind: str, unconfirmed: bool) -> None: if kind == "pod": self._pod_unconfirmed = unconfirmed else: self._service_unconfirmed = unconfirmed
def _has_tracked_resources(self) -> bool: return ( self._pod_created or self._service_created or self._pod_unconfirmed or self._service_unconfirmed )
def stop_container(self) -> None: """Delete the Pod and Service this provider created.
Safe when nothing was started and safe to call twice. A 404 from the API is treated as already deleted. A confirmed resource is deleted by name. An unconfirmed one is deleted only after a fresh ownership-label match. If that read fails, the unconfirmed state is kept for another retry. Objects this instance does not own are left in place, including a name that was already taken. """ if self._name is None and not self._has_tracked_resources(): self._base_url = None self._service_port = None return
errors: list[str] = [] self._stop_kind("pod", errors) self._stop_kind("service", errors) if errors: raise RuntimeError( "Failed to delete Kubernetes resources created by this provider. " "Call stop_container() again to retry." ) self._name = None self._base_url = None self._service_port = None
def _stop_kind(self, kind: str, errors: list[str]) -> None: if self._name is None: return if self._unconfirmed(kind): owned = self._lookup_owned(kind) if owned is None: errors.append(kind) return self._set_unconfirmed(kind, False) if not owned: return self._set_created(kind, True) if not self._created(kind): return try: if kind == "pod": self._adapter.delete_pod(self._name) else: self._adapter.delete_service(self._name) except Exception: errors.append(kind) return self._set_created(kind, False)
def close(self) -> None: """Stop the active Pod and Service.
Overrides the base no-op so a caller holding a bare ``ContainerProvider`` reference can release the Pod polymorphically (also invoked on context-manager exit). Equivalent to ``stop_container()``. """ self.stop_container()
def __exit__(self, exc_type, exc, tb) -> None: try: self.close() except Exception: if exc_type is None: raise
def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: """ Wait until the Pod is Running and ``GET /health`` returns 200.
A Failed or Succeeded Pod raises immediately instead of consuming the timeout. The URL is not included in errors: this method only polls the Service URL returned by ``start_container``.
Args: base_url (`str`): URL returned by ``start_container()``. timeout_s (`float`, *optional*, defaults to `120.0`): Maximum seconds to wait. Image pulls are slower than local Docker.
Raises: TimeoutError: If the Pod does not become ready in time. RuntimeError: If the Pod has already ended. ValueError: If ``base_url`` is not the URL this provider returned. """ import requests
expected = self._base_url if expected is None or not isinstance(base_url, str): raise ValueError( "base_url does not match the in-cluster Service URL for this provider." ) if base_url.rstrip("/") != expected: raise ValueError( "base_url does not match the in-cluster Service URL for this provider." ) if isinstance(timeout_s, bool) or not isinstance(timeout_s, (int, float)): raise ValueError("timeout_s must be a number.") if timeout_s < 0: raise ValueError("timeout_s must be non-negative.")
health_url = f"{expected}/health" proxies = {"http": "", "https": "", "all": ""} deadline = time.monotonic() + timeout_s while (remaining := deadline - time.monotonic()) > 0: try: phase, reason = self._phase(remaining) except _TransientStatusError: phase, reason = "Unknown", None if phase in ("Failed", "Succeeded"): raise RuntimeError(self._ended_message(phase, reason)) remaining = deadline - time.monotonic() if remaining <= 0: break if phase == "Running": try: response = requests.get( health_url, timeout=min(2.0, remaining), proxies=proxies ) if response.status_code == 200: return except requests.RequestException: pass time.sleep(min(0.5, max(0.0, deadline - time.monotonic())))
raise TimeoutError(f"Kubernetes Pod did not become ready within {timeout_s}s.")
def _phase(self, timeout_s: float) -> tuple[str, Optional[str]]: if self._name is None: raise RuntimeError( "KubernetesProvider has no active Pod. Start the provider " "before waiting for readiness." ) status = self._adapter.pod_status(self._name, timeout_s=timeout_s) phase = status.get("phase") if isinstance(status, Mapping) else None reason = status.get("reason") if isinstance(status, Mapping) else None if not isinstance(phase, str) or not _SAFE_REASON.fullmatch(phase): phase = "Unknown" return phase, _safe_reason(reason if isinstance(reason, str) else None)
def _ended_message(self, phase: str, reason: Optional[str]) -> str: if reason is None: return ( f"Kubernetes Pod entered phase {phase} before it became ready. " "The Service URL and Pod status message are omitted." ) return ( f"Kubernetes Pod entered phase {phase} ({reason}) before it became " "ready. The Service URL and Pod status message are omitted." )
def _env_list(env_vars: Optional[Mapping[str, str]]) -> list[dict[str, str]]: if env_vars is None: return [] if not isinstance(env_vars, Mapping): raise ValueError("env_vars must be a mapping of strings.") items: list[dict[str, str]] = [] for key, value in env_vars.items(): if not isinstance(key, str) or not isinstance(value, str): raise ValueError("env_vars keys and values must be strings.") items.append({"name": key, "value": value}) return items
def _resources(resources: Any) -> Optional[dict[str, dict[str, str]]]: if resources is None: return None if not isinstance(resources, Mapping): raise ValueError("resources must be a mapping of requests and limits.") unknown = set(resources) - {"requests", "limits"} if unknown: raise ValueError( f"Unsupported resources keys for KubernetesProvider: {sorted(unknown)}" ) parsed: dict[str, dict[str, str]] = {} for section in ("requests", "limits"): values = resources.get(section) if values is None: continue if not isinstance(values, Mapping) or not values: raise ValueError(f"resources.{section} must be a non-empty mapping.") parsed[section] = {} for key, value in values.items(): if not isinstance(key, str) or not isinstance(value, str) or not value: raise ValueError( f"resources.{section} keys and values must be non-empty strings." ) parsed[section][key] = value return parsed or None
def _optional_dns_subdomain(value: Any, *, what: str) -> Optional[str]: if value is None: return None if not isinstance(value, str) or not _dns_subdomain(value): raise ValueError( f"{what} must be a DNS-1123 subdomain: lowercase labels separated by '.'." ) return value
def _secret_names(value: Any) -> list[str]: if value is None: return [] if isinstance(value, str) or not isinstance(value, (list, tuple)): raise ValueError("image_pull_secrets must be a list of secret names.") names: list[str] = [] for item in value: if not isinstance(item, str) or not _dns_subdomain(item): raise ValueError("image_pull_secrets entries must be DNS-1123 subdomains.") names.append(item) return names
def _pod_manifest( *, name: str, namespace: str, labels: dict[str, str], image: str, env_list: list[dict[str, str]], resources: Optional[dict[str, dict[str, str]]], runtime_class_name: Optional[str], service_account_name: Optional[str], image_pull_secrets: list[str], automount_service_account_token: bool,) -> dict[str, Any]: container: dict[str, Any] = { "name": _CONTAINER_NAME, "image": image, "ports": [{"name": "http", "container_port": _CONTAINER_PORT}], } if env_list: container["env"] = env_list if resources: container["resources"] = resources spec: dict[str, Any] = { "restart_policy": "Never", "automount_service_account_token": automount_service_account_token, "containers": [container], } if runtime_class_name: spec["runtime_class_name"] = runtime_class_name if service_account_name: spec["service_account_name"] = service_account_name if image_pull_secrets: spec["image_pull_secrets"] = image_pull_secrets return { "metadata": {"name": name, "namespace": namespace, "labels": labels}, "spec": spec, }
def _service_manifest( *, name: str, namespace: str, labels: dict[str, str], service_port: int,) -> dict[str, Any]: return { "metadata": {"name": name, "namespace": namespace, "labels": labels}, "spec": { "selector": {_SELECTOR_KEY: name}, "ports": [ { "name": "http", "port": service_port, "target_port": _CONTAINER_PORT, "protocol": "TCP", } ], }, }
__all__ = ["KubernetesProvider"]2 unmodified lines3456789101112131415161718192021222324252627282930313225 unmodified lines5859606162636465666768697071727374757677787980818283848525 unmodified lines11111211311411511611711811912043 unmodified lines1641651661671681691701711721731744 unmodified lines17918018118218318418512 unmodified lines19819920020120220320420520620720820915 unmodified lines2252262272282292302312322332346 unmodified lines2412422432442452462472482492502512522532542552562572582592602 unmodified lines"""Modal container provider for running OpenEnv environments in Modal sandboxes.Requires the ``modal`` SDK: ``pip install modal>=1.4``The provider boots an OpenEnv server inside a Modal sandbox, exposes it on anencrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects toover ``wss://``.Supports both the stable Sandbox API (``modal.Sandbox.create``) and the betaSandbox v2 API (``modal.Sandbox._experimental_create``). Sandbox v2 is opt-invia ``use_sandbox_v2=True`` because it is an experimental, private SDK feature;see https://modal.com/docs/guide/sandbox-v2 ."""from __future__ import annotationsimport loggingimport shleximport timefrom typing import Any, Dict, Optionalfrom ._server_config import parse_dockerfile_cmd, parse_openenv_app_fieldfrom .providers import ContainerProviderlogger = logging.getLogger(__name__)_DEFAULT_MODAL_PORT = 8000# Modal's default per-container resource requests. We pass configured cpu/memory25 unmodified lines"""Thin adapter over the ``modal`` SDK.The provider talks to this private adapter instead of spreading SDK detailsthrough its own logic; tests inject a duck-typed fake in its place. Keepingthe SDK surface here also localizes the feature check for the privateSandbox v2 (``_experimental_create``) API."""def __init__(self, *, app_name: str, use_sandbox_v2: bool):import modalself._modal = modalself._app_name = app_nameself._use_sandbox_v2 = use_sandbox_v2# Sandbox v2 rides on a private SDK entry point that is not present in# every modal release. Fail fast at construction with clear guidance# rather than at start_container time with an AttributeError.if use_sandbox_v2 and not hasattr(modal.Sandbox, "_experimental_create"):raise RuntimeError("use_sandbox_v2=True requires modal.Sandbox._experimental_create, ""which is not available in the installed modal SDK. Upgrade modal, ""or use the stable Sandbox API (use_sandbox_v2=False). Sandbox v2 ""is an experimental feature; contact support@modal.com for access.")def image_from_registry(self, tag: str) -> Any:return self._modal.Image.from_registry(tag)25 unmodified lines# The sandbox is started with a keep-alive entrypoint; the server# command is launched via exec afterwards (see ModalProvider).if self._use_sandbox_v2:return self._modal.Sandbox._experimental_create("sleep", "infinity", **kwargs)return self._modal.Sandbox.create("sleep", "infinity", **kwargs)def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str:43 unmodified linesprovider.wait_for_ready(base_url)# sandbox terminated on exit```Sandbox v2 (beta) is opt-in:```pythonprovider = ModalProvider(app_name="openenv", use_sandbox_v2=True)```"""_dockerfile_registry: Dict[str, Dict[str, Any]] = {}4 unmodified linesimage: str | None = None,env_vars: dict[str, str] | None = None,app_name: str = "openenv",use_sandbox_v2: bool = False,timeout: int = 300,cmd: str | None = None,cpu: float | None = None,12 unmodified linesapp_name (`str`, *optional*, defaults to `"openenv"`):Modal app name the sandbox is created under. Looked up (andcreated if missing) via ``modal.App.lookup``.use_sandbox_v2 (`bool`, *optional*, defaults to `False`):When `True`, sandboxes are created via the beta``modal.Sandbox._experimental_create`` API (Sandbox v2). This isan experimental, private SDK feature and is therefore off bydefault; a feature check fails fast at construction if theinstalled SDK lacks it. See https://modal.com/docs/guide/sandbox-v2 .timeout (`int`, *optional*, defaults to `300`):Maximum sandbox lifetime in seconds.cmd (`str`, *optional*):15 unmodified linesorchestrator/CI logs. When `True`, a best-effort redacted,length-bounded excerpt is included in startup-crash errors."""self._image = imageself._env_vars = env_varsself._app_name = app_nameself._use_sandbox_v2 = use_sandbox_v2self._timeout = timeoutself._cmd = cmdself._cpu = cpu6 unmodified linesself._redact_values: set[str] = set()if _adapter is None:# Import eagerly (inside the adapter) so SDK/configuration errors —# including the Sandbox v2 feature check — surface at construction.self._adapter: Any = _DefaultModalAdapter(app_name=app_name, use_sandbox_v2=use_sandbox_v2)else:self._adapter = _adapterif use_sandbox_v2:logger.info("Using Modal Sandbox v2 (experimental). This feature must be ""explicitly enabled. Contact support@modal.com to get access.")def _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str:"""Discover the server command from ``openenv.yaml`` inside the sandbox.2 unmodified lines34567891011121314151617181920212223242525 unmodified lines515253545556575859606162636425 unmodified lines90919293949543 unmodified lines1391401411421431444 unmodified lines14915015115215315415512 unmodified lines16816917017117217317417517617717815 unmodified lines1941951961971981992002012022032042052062072082092102116 unmodified lines2182192202212222232242252262272282292 unmodified lines"""Modal container provider for running OpenEnv environments in Modal sandboxes.Requires the ``modal`` SDK: ``pip install modal>=1.6.3``The provider boots an OpenEnv server inside a Modal sandbox, exposes it on anencrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects toover ``wss://``."""from __future__ import annotationsimport shleximport timeimport warningsfrom typing import Any, Dict, Optionalfrom ._server_config import parse_dockerfile_cmd, parse_openenv_app_fieldfrom .providers import ContainerProvider_DEFAULT_MODAL_PORT = 8000# Modal's default per-container resource requests. We pass configured cpu/memory25 unmodified lines"""Thin adapter over the ``modal`` SDK.The provider talks to this private adapter instead of spreading SDK detailsthrough its own logic; tests inject a duck-typed fake in its place."""def __init__(self, *, app_name: str):import modalself._modal = modalself._app_name = app_namedef image_from_registry(self, tag: str) -> Any:return self._modal.Image.from_registry(tag)25 unmodified lines# The sandbox is started with a keep-alive entrypoint; the server# command is launched via exec afterwards (see ModalProvider).return self._modal.Sandbox.create("sleep", "infinity", **kwargs)def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str:43 unmodified linesprovider.wait_for_ready(base_url)# sandbox terminated on exit```"""_dockerfile_registry: Dict[str, Dict[str, Any]] = {}4 unmodified linesimage: str | None = None,env_vars: dict[str, str] | None = None,app_name: str = "openenv",use_sandbox_v2: bool | None = None,timeout: int = 300,cmd: str | None = None,cpu: float | None = None,12 unmodified linesapp_name (`str`, *optional*, defaults to `"openenv"`):Modal app name the sandbox is created under. Looked up (andcreated if missing) via ``modal.App.lookup``.use_sandbox_v2 (`bool`, *optional*):Deprecated and ignored; will be removed in OpenEnv 0.15.0.Modal 1.6+ creates Sandbox v2 sandboxes through``modal.Sandbox.create`` by default. Set ``MODAL_SANDBOX_V2=0``to use Sandbox v1.timeout (`int`, *optional*, defaults to `300`):Maximum sandbox lifetime in seconds.cmd (`str`, *optional*):15 unmodified linesorchestrator/CI logs. When `True`, a best-effort redacted,length-bounded excerpt is included in startup-crash errors."""if use_sandbox_v2 is not None:warnings.warn("`use_sandbox_v2` is deprecated, has no effect, and will be removed ""in OpenEnv 0.15.0. Remove the argument: Modal 1.6+ creates Sandbox ""v2 sandboxes through `modal.Sandbox.create` by default. Set ""`MODAL_SANDBOX_V2=0` to use Sandbox v1.",FutureWarning,stacklevel=2,)self._image = imageself._env_vars = env_varsself._app_name = app_nameself._timeout = timeoutself._cmd = cmdself._cpu = cpu6 unmodified linesself._redact_values: set[str] = set()if _adapter is None:# Import eagerly (inside the adapter) so SDK/configuration errors# surface at construction.self._adapter: Any = _DefaultModalAdapter(app_name=app_name)else:self._adapter = _adapterdef _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str:"""Discover the server command from ``openenv.yaml`` inside the sandbox.
8 unmodified lines9101112131415161718192021222324252627147 unmodified lines1751761771781791801811821 unmodified line18418518618718818912 unmodified lines202203204205206207208209210211212213214215216217218222 unmodified lines44144244344444544644744844945017 unmodified lines468469470471472473474475476477478479164 unmodified lines6446456466476486496506516526536546556566576586596606616628 unmodified linesfrom __future__ import annotationsfrom abc import ABC, abstractmethodfrom typing import Any, Dict, Optional, Sequence, TypeVar_ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider")class ContainerProvider(ABC):"""Abstract base class for container providers.Providers implement this interface to support different container platforms:- LocalDockerProvider: Runs containers on local Docker daemon- KubernetesProvider: Runs containers in Kubernetes cluster- FargateProvider: Runs containers on AWS Fargate- CloudRunProvider: Runs containers on Google Cloud Run147 unmodified linesPort to expose. If `None`, finds an available port.env_vars (`dict`, *optional*):Environment variables for the container.**kwargs:Additional Docker run options.Returns:`str`: Base URL to connect to the container.1 unmodified lineimport subprocessimport time# Find available port if not specifiedif port is None:port = self._find_available_port()12 unmodified linesf"{port}:8000", # Map port]# Add environment variablesif env_vars:for key, value in env_vars.items():cmd.extend(["-e", f"{key}={value}"])# Add imagecmd.append(image)# Run containertry:result = subprocess.run(cmd, capture_output=True, text=True, check=True)self._container_id = result.stdout.strip()except subprocess.CalledProcessError as e:error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}"222 unmodified linesif self._overlay_network:cmd.extend(["--network", self._overlay_network])if env_vars:for key, value in env_vars.items():cmd.extend(["--env", f"{key}={value}"])if cpu_limit is not None:cmd.extend(["--limit-cpu", str(cpu_limit)])17 unmodified linescmd.extend(command_override)try:result = subprocess.run(cmd,capture_output=True,text=True,check=True,)self._service_id = result.stdout.strip()except subprocess.CalledProcessError as e:error_msg = (164 unmodified linesreturn f"{clean_image}-swarm-{timestamp}"class KubernetesProvider(ContainerProvider):"""Planned container provider for Kubernetes clusters.Not yet implemented: this is a placeholder for the planned Kubernetesbackend and does not implement the abstract `ContainerProvider` methods, soit cannot be instantiated. Use `LocalDockerProvider`, `DockerSwarmProvider`,`DaytonaProvider`, or `ACASandboxProvider` instead."""passclass RuntimeProvider(ABC):"""Abstract base class for runtime providers that are not container providers.8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384147 unmodified lines2322332342352362372382392402411 unmodified line24324424524624724824925012 unmodified lines263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295222 unmodified lines51851952052152252317 unmodified lines541542543544545546547548549550551552553554164 unmodified lines7197207217227237248 unmodified linesfrom __future__ import annotationsimport osimport tempfilefrom abc import ABC, abstractmethodfrom contextlib import contextmanagerfrom typing import (Any,Dict,Iterator,List,Mapping,Optional,Sequence,Tuple,TypeVar,)_ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider")@contextmanagerdef _env_file_args(env_vars: Optional[Mapping[str, str]],) -> Iterator[Tuple[List[str], Optional[str]]]:"""Yield `--env-file` arguments for the container's environment variables,and the text to send to docker's stdin.The values (often tokens) stay out of the command line, which otherprocesses can read and errors include, and out of the docker CLI's ownenvironment, where names like `DOCKER_HOST` or `PATH` would change howthe CLI runs. Docker reads them from its stdin (`/dev/stdin`), so no fileis written and a CLI with a private `/tmp` (snap) still gets them. Windowshas no `/dev/stdin`: there they go in a temporary file only this user canread, removed once docker returns."""if not env_vars:yield [], Nonereturnlines = []for key, value in env_vars.items():key, value = str(key), str(value)if not key or key.startswith("#") or any(c in key for c in "= \t\r\n\0"):raise ValueError(f"Invalid environment variable name: {key!r}")if any(c in value for c in "\r\n\0"):raise ValueError(f"Environment variable {key!r}: values can't contain line breaks ""or NUL characters")lines.append(f"{key}={value}\n")if os.name != "nt":yield ["--env-file", "/dev/stdin"], "".join(lines)returnfd, path = tempfile.mkstemp(prefix="openenv-env-")try:with os.fdopen(fd, "w") as env_file:env_file.writelines(lines)yield ["--env-file", path], Nonefinally:os.unlink(path)class ContainerProvider(ABC):"""Abstract base class for container providers.Providers implement this interface to support different container platforms:- LocalDockerProvider: Runs containers on local Docker daemon- DockerSwarmProvider: Runs containers as a Docker Swarm service- KubernetesProvider: optional ``openenv[kubernetes]`` extra(``kubernetes_provider.py``)- FargateProvider: Runs containers on AWS Fargate- CloudRunProvider: Runs containers on Google Cloud Run147 unmodified linesPort to expose. If `None`, finds an available port.env_vars (`dict`, *optional*):Environment variables for the container.volumes (`dict`, *optional*):Mapping of host paths or volume names to mount configuration.Each configuration must contain a `bind` container path and maycontain a `mode` such as `"ro"` or `"rw"`.Returns:`str`: Base URL to connect to the container.1 unmodified lineimport subprocessimport timevolumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes")# Find available port if not specifiedif port is None:port = self._find_available_port()12 unmodified linesf"{port}:8000", # Map port]# Add volume mounts before the image name.if volumes:for source, config in volumes.items():bind = config.get("bind")if not bind:raise ValueError(f"Volume config for {source!r} must include a non-empty 'bind'")mode = config.get("mode")volume_spec = f"{source}:{bind}"if mode:volume_spec = f"{volume_spec}:{mode}"cmd.extend(["--volume", volume_spec])# Add imagecmd.append(image)# Run containertry:with _env_file_args(env_vars) as (env_args, env_input):result = subprocess.run(cmd[:2] + env_args + cmd[2:],input=env_input,capture_output=True,text=True,check=True,)self._container_id = result.stdout.strip()except subprocess.CalledProcessError as e:error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}"222 unmodified linesif self._overlay_network:cmd.extend(["--network", self._overlay_network])if cpu_limit is not None:cmd.extend(["--limit-cpu", str(cpu_limit)])17 unmodified linescmd.extend(command_override)try:with _env_file_args(env_vars) as (env_args, env_input):result = subprocess.run(cmd[:3] + env_args + cmd[3:],input=env_input,capture_output=True,text=True,check=True,)self._service_id = result.stdout.strip()except subprocess.CalledProcessError as e:error_msg = (164 unmodified linesreturn f"{clean_image}-swarm-{timestamp}"class RuntimeProvider(ABC):"""Abstract base class for runtime providers that are not container providers.
1 unmodified line2345674 unmodified lines121314151617119 unmodified lines13713813914014114214351 unmodified lines19519619719819920020130 unmodified lines2322332342352362372382392402412422432441 unmodified linefrom __future__ import annotationsimport osimport shutilimport socket4 unmodified linesimport requestsfrom .providers import RuntimeProviderGIT_URL_PREFIX = "git+"119 unmodified linesreload (`bool`, *optional*, defaults to `False`):Whether to enable uvicorn's reload mode.env_vars (`dict`, *optional*):Environment variables to pass through to the spawned process.context_timeout_s (`float`, *optional*, defaults to `60.0`):How long to wait for the environment to become ready.51 unmodified linesport (`int`, *optional*):The port to bind the environment to.env_vars (`dict`, *optional*):Environment variables to pass to the environment.workers (`int`, *optional*, defaults to `1`):The number of workers to use.30 unmodified linesproject_path=project_path,)env = os.environ.copy()if self.env_vars:env.update(self.env_vars)if env_vars:env.update(env_vars)try:self._process = subprocess.Popen(command, env=env)except OSError as exc:1 unmodified line23456784 unmodified lines131415161718192021119 unmodified lines14114214314414514614714814915015151 unmodified lines20320420520620720820921030 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622631 unmodified linefrom __future__ import annotationsimport loggingimport osimport shutilimport socket4 unmodified linesimport requestsfrom ...utils import _SECRET_ENV_NAMElogger = logging.getLogger(__name__)from .providers import RuntimeProviderGIT_URL_PREFIX = "git+"119 unmodified linesreload (`bool`, *optional*, defaults to `False`):Whether to enable uvicorn's reload mode.env_vars (`dict`, *optional*):Environment variables to pass through to the spawned process. Theserver inherits this process's environment except variables namedlike credentials (`TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a partof the name, such as `HF_TOKEN`), so a credential the server needshas to be passed here.context_timeout_s (`float`, *optional*, defaults to `60.0`):How long to wait for the environment to become ready.51 unmodified linesport (`int`, *optional*):The port to bind the environment to.env_vars (`dict`, *optional*):Environment variables to pass to the environment, on top ofthe constructor's. Credentials reach the server only this way.workers (`int`, *optional*, defaults to `1`):The number of workers to use.30 unmodified linesproject_path=project_path,)# Environment servers can run code a model wrote: they don't inherit# this process's credentials, only the ones passed in env_vars.env = {k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)}if self.env_vars:env.update(self.env_vars)if env_vars:env.update(env_vars)dropped = sorted(k for k in os.environ if k not in env)if dropped:logger.warning("Not passing %s to the environment server. Pass the ones it ""needs with env_vars.",", ".join(dropped),)try:self._process = subprocess.Popen(command, env=env)except OSError as exc:
274 unmodified lines275276277278279280105 unmodified lines386387388389390391125 unmodified lines5175185195205215222 unmodified lines5255265275285295305315325334 unmodified lines538539540541542543544545546547548549550551552100 unmodified lines653654655656657658270 unmodified lines92993093193293393461 unmodified lines996997998999100010011002100315 unmodified lines101910201021102210231024102510266 unmodified lines10331034103510361037103810391040104110421043120 unmodified lines1164116511661167116811691170274 unmodified linesawait _best_effort_close(ws)class EnvClient(ABC, Generic[ActT, ObsT, StateT]):"""Async environment client for persistent sessions.105 unmodified lines# Strong references for fire-and-forget socket closes (see _receive),# so the task isn't garbage-collected mid-close. Discarded on done.self._pending_close_tasks: set[asyncio.Task] = set()if base_url is not None:self._set_base_url(base_url)125 unmodified linescoro_factory: Callable[[], Any],*,allow_async_handoff: bool = False,) -> Any:"""Run an async operation through the sync wrapper."""if allow_async_handoff and self._execution_mode == "async":2 unmodified linesself._claim_execution_mode("sync")if self._sync_client is None:self._sync_client = self.sync()return self._sync_client._run(coro_factory())def _dispatch(self, coro_factory: Callable[[], Any]) -> Any:"""Return an awaitable in async code and a concrete result in sync code."""try:running_loop = asyncio.get_running_loop()4 unmodified linessync_loop = (self._sync_client._loop if self._sync_client is not None else None)if running_loop is sync_loop:return coro_factory()return self._run_sync(coro_factory)if running_loop is not None:if self._execution_mode == "async":return coro_factory()return _AutoAsyncResult(self, coro_factory)return self._run_sync(coro_factory, allow_async_handoff=True)def connect(self) -> Any:return self._dispatch(self._connect_async)100 unmodified lines# leave a stale socket cached for a later operation.self._ws = Noneself._ws_loop = Nonesame_loop = ws_loop is asyncio.get_running_loop()if same_loop:# Keep ownership of the handshake if this caller is cancelled.270 unmodified lines`start_container` (docker) or to the `UVProvider` constructor/start (uv).When `use_docker=False`, the `project_path` argument can be used to overridethe default git URL (`git+https://huggingface.co/spaces/{repo_id}`).Returns:`_BootstrapResult`: `await` for a connected async client, or call61 unmodified lines"type": "reset","data": kwargs,}response = await self._send_and_receive(message)return self._parse_result(response.get("data", {}))def step(self, action: ActT, **kwargs: Any) -> Any:return self._dispatch(lambda: self._step_async(action, **kwargs))15 unmodified lines"type": "step","data": self._step_payload(action),}response = await self._send_and_receive(message)return self._parse_result(response.get("data", {}))def state(self) -> Any:return self._dispatch(self._state_async)6 unmodified linesState object with environment state information"""message = {"type": "state"}response = await self._send_and_receive(message)return self._parse_state(response.get("data", {}))def close(self) -> Any:return self._dispatch(self._close_async)async def _close_child_clients(self) -> asyncio.CancelledError | None:"""Close every captured child while deferring caller cancellation."""120 unmodified linesdef __exit__(self, exc_type, exc_val, exc_tb) -> None:"""Exit sync context manager, closing connection."""self._run_sync(self._close_async)def sync(self) -> "SyncEnvClient":"""274 unmodified lines275276277278279280281282283284285286287288289105 unmodified lines395396397398399400401402125 unmodified lines5285295305315325335342 unmodified lines5375385395405415425435445455465475485495505514 unmodified lines556557558559560561562563564565566567568569570571572100 unmodified lines673674675676677678679270 unmodified lines95095195295395495595695761 unmodified lines10191020102110221023102410251026102710281029103015 unmodified lines1046104710481049105010511052105310541055105610576 unmodified lines106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096120 unmodified lines1217121812191220122112221223274 unmodified linesawait _best_effort_close(ws)class SessionLostError(ConnectionError):"""The connection to the server was lost in the middle of an episode.The server keeps one environment per WebSocket connection, so reconnectingopens a new session with an environment this client never reset. Call`reset()` to start a new episode."""class EnvClient(ABC, Generic[ActT, ObsT, StateT]):"""Async environment client for persistent sessions.105 unmodified lines# Strong references for fire-and-forget socket closes (see _receive),# so the task isn't garbage-collected mid-close. Discarded on done.self._pending_close_tasks: set[asyncio.Task] = set()# The socket that carries the episode started by `reset()`, if one is open.self._episode_ws: Optional[ClientConnection] = Noneif base_url is not None:self._set_base_url(base_url)125 unmodified linescoro_factory: Callable[[], Any],*,allow_async_handoff: bool = False,stop_loop: bool = False,) -> Any:"""Run an async operation through the sync wrapper."""if allow_async_handoff and self._execution_mode == "async":2 unmodified linesself._claim_execution_mode("sync")if self._sync_client is None:self._sync_client = self.sync()try:return self._sync_client._run(coro_factory())finally:if stop_loop:self._sync_client._stop_loop()def _dispatch(self, coro_factory: Callable[[], Any], *, stop_loop: bool = False) -> Any:"""Return an awaitable in async code and a concrete result in sync code."""try:running_loop = asyncio.get_running_loop()4 unmodified linessync_loop = (self._sync_client._loop if self._sync_client is not None else None)if running_loop is not None and running_loop is sync_loop:return coro_factory()return self._run_sync(coro_factory, stop_loop=stop_loop)if running_loop is not None:if self._execution_mode == "async":return coro_factory()return _AutoAsyncResult(self, coro_factory)return self._run_sync(coro_factory, allow_async_handoff=True, stop_loop=stop_loop)def connect(self) -> Any:return self._dispatch(self._connect_async)100 unmodified lines# leave a stale socket cached for a later operation.self._ws = Noneself._ws_loop = Noneself._episode_ws = Nonesame_loop = ws_loop is asyncio.get_running_loop()if same_loop:# Keep ownership of the handshake if this caller is cancelled.270 unmodified lines`start_container` (docker) or to the `UVProvider` constructor/start (uv).When `use_docker=False`, the `project_path` argument can be used to overridethe default git URL (`git+https://huggingface.co/spaces/{repo_id}`).With `use_docker=False` the server doesn't inherit variables named likecredentials (such as `HF_TOKEN`): pass the ones it needs in `env_vars`.Returns:`_BootstrapResult`: `await` for a connected async client, or call61 unmodified lines"type": "reset","data": kwargs,}# A reset may reconnect: it starts a new episode on whatever session it lands on.self._episode_ws = Noneresponse = await self._send_and_receive(message)result = self._parse_result(response.get("data", {}))self._episode_ws = None if result.done else self._wsreturn resultdef step(self, action: ActT, **kwargs: Any) -> Any:return self._dispatch(lambda: self._step_async(action, **kwargs))15 unmodified lines"type": "step","data": self._step_payload(action),}self._raise_if_session_lost()response = await self._send_and_receive(message)result = self._parse_result(response.get("data", {}))if result.done:self._episode_ws = Nonereturn resultdef state(self) -> Any:return self._dispatch(self._state_async)6 unmodified linesState object with environment state information"""message = {"type": "state"}self._raise_if_session_lost()response = await self._send_and_receive(message)return self._parse_state(response.get("data", {}))def _raise_if_session_lost(self) -> None:"""Raise `SessionLostError` if the socket that carried the episode is gone.`_connect_async()` would replace it with a new socket, which the servertreats as a new session, and the call would run on an environment thisclient never reset. It keeps raising until `reset()`, so a retried calldoes not land on the new session either."""ws = self._episode_wsif ws is None:returnif (self._ws is not wsor ws.state in (State.CLOSING, State.CLOSED)or self._ws_loop is not asyncio.get_running_loop()):raise SessionLostError(f"Lost the connection to {self._ws_url} in the middle of an episode. ""Call reset() to start a new one.")def close(self) -> Any:return self._dispatch(self._close_async, stop_loop=True)async def _close_child_clients(self) -> asyncio.CancelledError | None:"""Close every captured child while deferring caller cancellation."""120 unmodified linesdef __exit__(self, exc_type, exc_val, exc_tb) -> None:"""Exit sync context manager, closing connection."""self._run_sync(self._close_async, stop_loop=True)def sync(self) -> "SyncEnvClient":"""
43 unmodified lines444546474849508 unmodified lines5960616263646543 unmodified linesRaised when the server cannot accept new sessions due to capacity limits.This error is raised when a new WebSocket connection is attempted butthe server has already reached max_concurrent_envs active sessions."""def __init__(8 unmodified linesif message is None:message = (f"Server at capacity: {active_sessions}/{max_sessions} sessions active. "f"Cannot accept new connections.")super().__init__(message)43 unmodified lines444546474849505152538 unmodified lines6263646566676869707172737443 unmodified linesRaised when the server cannot accept new sessions due to capacity limits.This error is raised when a new WebSocket connection is attempted butthe server has already reached max_concurrent_envs active sessions. Thedefault message tells the caller which server setting limits the number ofsessions, since the client (e.g. a trainer opening one session perconcurrent episode) usually cannot see the server configuration."""def __init__(8 unmodified linesif message is None:message = (f"Server at capacity: {active_sessions}/{max_sessions} sessions active. "f"Cannot accept new connections. To serve more concurrent sessions, "f"start the server with a higher max_concurrent_envs (most "f"environment servers read it from the MAX_CONCURRENT_ENVS "f"environment variable). Values above 1 also require an environment "f"that isolates per-session state and declares "f"SUPPORTS_CONCURRENT_SESSIONS=True. Otherwise, open fewer "f"sessions at once or close idle ones.")super().__init__(message)
13 unmodified lines14151617181920212233 unmodified lines5657585960616263646566114 unmodified lines18118218318418518621 unmodified lines20820921021121221339 unmodified lines2532542552562572581 unmodified line2602612622632642652662672 unmodified lines2702712722732742752762772 unmodified lines28028128228328428584 unmodified lines37037137237337437537623 unmodified lines4004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564577 unmodified lines46546646746846947062 unmodified lines5335345355365375385395405415425435445455465475485494 unmodified lines5545555565575585599 unmodified lines569570571572573574575576577578579580298 unmodified lines87988088188288388488588688788888989089189289389489589689789894 unmodified lines99399499599699799899933 unmodified lines1033103410351036103710387 unmodified lines10461047104810491050105147 unmodified lines1099110011011102110311042 unmodified lines1107110811091110111111125 unmodified lines11181119112011211122112318 unmodified lines11421143114411451146114716 unmodified lines11641165116611671168116911709 unmodified lines118011811182118311841185118634 unmodified lines12211222122312241225122615 unmodified lines1242124312441245124612471248165 unmodified lines1414141514161417141814191420240 unmodified lines166116621663166416651666166716681669167016711672167316 unmodified lines1690169116921693169416957 unmodified lines17031704170517061707170844 unmodified lines1753175417551756175717582 unmodified lines17611762176317641765176617671768176917709 unmodified lines178017811782178317841785178616 unmodified lines1803180418051806180718088 unmodified lines18171818181918201821182225 unmodified lines184818491850185118521853185470 unmodified lines1925192619271928192919301931193219333 unmodified lines1937193819391940194119421 unmodified line19441945194619471948194953 unmodified lines20032004200520062007200838 unmodified lines20472048204920502051205221 unmodified lines20742075207620772078207912 unmodified lines20922093209420952096209710 unmodified lines21082109211021112112211319 unmodified lines21332134213521362137213821 unmodified lines216021612162216321642165216623 unmodified lines21902191219221932194219521962 unmodified lines219922002201220222032204220522062207220822095 unmodified lines22152216221722182219222022212222222313 unmodified linesimport jsonimport loggingimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import AsyncExitStackfrom typing import (Any,33 unmodified linesListToolsAction,ListToolsObservation,McpMethod,WSMCPMessage,WSMCPResponse,)from .route_config import GetEndpointConfig, register_get_endpointsfrom .serialization import deserialize_action, serialize_observationfrom .types import (Action,ConcurrencyConfig,114 unmodified linesstate_cls: Type[State] = State,*,reset_observation_cls: Optional[Type[Observation]] = None,):"""Initialize HTTP server wrapper.21 unmodified linesThe `State` subclass this environment reports. Used for the `/state`response model and the `state` entry of `/schema`, so that fieldsdeclared by the subclass are published and serialized.Raises:`ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided.39 unmodified linesself.observation_cls = observation_clsself.reset_observation_cls = reset_observation_cls or observation_clsself.state_cls = state_clsself.env_name = env_name or self._default_env_name()# Session management for WebSocket connections1 unmodified lineself._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_stacks: Dict[str, AsyncExitStack] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_websocket_attachments: set[str] = set()self._session_pending_closes: set[str] = set()self._session_lock = asyncio.Lock()# Create thread pool for running sync code in async context2 unmodified linesself._requires_single_thread_executor = self._detect_single_thread_requirement()self._shared_session_executor: Optional[ThreadPoolExecutor] = Noneif self._requires_single_thread_executor:self._shared_session_executor = ThreadPoolExecutor(max_workers=1)# Idle session reaper configuration.# Timeout is taken from ConcurrencyConfig.session_timeout;2 unmodified linesself._concurrency_config.session_timeout)self._reaper_task: Optional[asyncio.Task[None]] = Nonedef _default_env_name(self) -> str:factory = self._env_factory84 unmodified linesreturn valid_kwargsasync def _create_session(self) -> tuple[str, Environment]:"""Create a new WebSocket session with its own environment instance.23 unmodified linesself._session_executors[session_id] = executorself._sessions[session_id] = None # placeholder until env is readytry:# Create environment in the executor thread (outside lock)loop = asyncio.get_event_loop()env = await loop.run_in_executor(executor, self._env_factory)except Exception as e:async with self._session_lock:if executor is not self._shared_session_executor:executor.shutdown(wait=False)self._session_executors.pop(session_id, None)self._sessions.pop(session_id, None)factory_name = getattr(self._env_factory, "__name__", str(self._env_factory))raise EnvironmentFactoryError(factory_name) from e# Hold the MCP session open for the lifetime of this session,# matching the WebSocket path's AsyncExitStack pattern. This# prevents per-request MCP transport teardown/reconnection and# preserves FastMCP session state (ctx.set_state / ctx.get_state)# across HTTP calls within the same OpenEnv session.stack = AsyncExitStack()try:mcp_session_factory = getattr(env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)except Exception:# MCP transport failed to start — clean up the reserved slot,# the env, and the executor so they don't leak permanently# against _max_concurrent_envs.await stack.aclose() # best-effortasync with self._session_lock:self._sessions.pop(session_id, None)self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor)raiseasync with self._session_lock:self._sessions[session_id] = envself._session_stacks[session_id] = stacknow = time.time()self._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=now,step_count=0,environment_type=type(env).__name__,)return session_id, envasync def _destroy_session(self, session_id: str) -> None:"""Destroy a WebSocket session and cleanup resources.7 unmodified linesexecutor = self._session_executors.pop(session_id, None)stack = self._session_stacks.pop(session_id, None)self._session_info.pop(session_id, None)self._session_websocket_attachments.discard(session_id)self._session_pending_closes.discard(session_id)62 unmodified linesinterval = max(timeout / 4, 5.0) # check frequently enoughwhile True:try:await asyncio.sleep(interval)now = time.time()stale_ids: list[str] = []async with self._session_lock:for sid, info in self._session_info.items():if (sid not in self._session_websocket_attachmentsand now - info.last_activity_at > timeout):stale_ids.append(sid)for sid in stale_ids:# Re-check under lock: activity may have arrived since# the snapshot was taken, making this session active again.# Refresh `now` so slow _destroy_session calls don't cause4 unmodified linesif (info is Noneor sid in self._session_websocket_attachmentsor (now - info.last_activity_at) <= timeout):continue9 unmodified linesdef _start_reaper(self) -> None:"""Start the idle-session reaper if a timeout is configured."""if self._session_idle_timeout_s is not None and self._reaper_task is None:self._reaper_task = asyncio.create_task(self._reap_idle_sessions())def _stop_reaper(self) -> None:"""Cancel the reaper background task."""if self._reaper_task is not None:self._reaper_task.cancel()self._reaper_task = Nonedef get_session_info(self, session_id: str) -> Optional[SessionInfo]:298 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Wire up idle-session reaper lifecycle via app eventsserver_ref = selfasync def _start_session_reaper() -> None:server_ref._start_reaper()async def _stop_session_reaper() -> None:server_ref._stop_reaper()if server_ref._shared_session_executor is not None:server_ref._shared_session_executor.shutdown(wait=True)if not getattr(app.router, "_openenv_reaper_registered", False):app.router.on_startup.append(_start_session_reaper)app.router.on_shutdown.append(_stop_session_reaper)app.router._openenv_reaper_registered = True # type: ignore[attr-defined]# Helper function to handle reset endpoint94 unmodified linesrequest_id=request_id,)try:created_session_id, _ = await self._create_session()except SessionCapacityError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,33 unmodified lines)async with self._session_lock:if target_session_id in self._session_websocket_attachments:env = _MISSINGattached = True7 unmodified linesexecutor = self._session_executors.pop(target_session_id, None)stack = self._session_stacks.pop(target_session_id, None)self._session_info.pop(target_session_id, None)elif not attached:executor = Nonestack = None47 unmodified lineselif requested_session_id:async with self._session_lock:_env = self._sessions.get(requested_session_id, _MISSING)if _env is _MISSING:return JsonRpcResponse.error_response(2 unmodified linesrequest_id=request_id,)if _env is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,5 unmodified linesmanaged_session_id = requested_session_idelse:_env = self._env_factory()should_close = Truetry:mcp_client = getattr(_env, "mcp_client", None)18 unmodified lines}if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif mcp_client is None and mcp_server is None:if supports_mcp_style_actions:16 unmodified linesrequest_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)9 unmodified linesreturn JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools34 unmodified linesrequest_id=request_id,)if mcp_client is None and mcp_server is None:if supports_mcp_style_actions:observation = await call_mcp_style_step(15 unmodified linesrequest_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)165 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for MCP websocket"240 unmodified linestags=["Schema"],summary="Get all JSON schemas",description="""Get JSON schemas for actions, observations, and state in a single response.Returns a combined schema object containing:- **action**: JSON schema for actions accepted by this environment- **observation**: JSON schema for observations returned by step- **reset_observation**: JSON schema for observations returned by reset- **state**: JSON schema for environment state objectsThis is more efficient than calling individual schema endpoints and providesall schema information needed to interact with the environment.16 unmodified lines"type": "object","properties": {"step_count": {"type": "integer"}},},}}},7 unmodified linesobservation=self.observation_cls.model_json_schema(),reset_observation=self.reset_observation_cls.model_json_schema(),state=self.state_cls.model_json_schema(),)# Register MCP endpoint for production mode (direct MCP access)44 unmodified linessession_env = Noneowns_session = Falseattached_session = Falsetry:requested_session_id = websocket.query_params.get("session_id")2 unmodified linesattached_env = self._sessions.get(requested_session_id, _MISSING)if attached_env is _MISSING:raise RuntimeError(f"Unknown session_id: {requested_session_id}")if attached_env is None:raise RuntimeError(f"Session {requested_session_id} is still initializing"9 unmodified linesattached_session = Trueself._update_session_activity(session_id)else:session_id, session_env = await self._create_session()owns_session = Trueif session_env is None:16 unmodified lines# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:8 unmodified linesmsg_type = message_dict.get("type", "")try:match msg_type:case "reset":25 unmodified lines))self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),70 unmodified lines})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message",3 unmodified lines)await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),1 unmodified line})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass53 unmodified lines*,mode: Optional[ServerMode | str] = None,reset_observation_cls: Optional[Type[Observation]] = None,) -> FastAPI:"""Create a FastAPI application with or without web interface.38 unmodified linesstate_cls (`Type[State]`, *optional*, defaults to `State`):The `State` subclass this environment reports, used for the `/state`response model and the `state` entry of `/schema`.mode (`ServerMode` or `str`, *optional*):Server mode. When `None`, resolved from the `OPENENV_MODE`environment variable, defaulting to simulation.21 unmodified linesmax_concurrent_envs,concurrency_config,state_cls=state_cls,reset_observation_cls=reset_observation_cls,gradio_builder=gradio_builder,custom_tab_name=custom_tab_name,12 unmodified linesconcurrency_config,env_name=env_name,state_cls=state_cls,reset_observation_cls=reset_observation_cls,mode=mode,)10 unmodified lines*,mode: Optional[ServerMode | str] = None,reset_observation_cls: Optional[Type[Observation]] = None,) -> FastAPI:"""Create a FastAPI application with comprehensive documentation.19 unmodified linesstate_cls (`Type[State]`, *optional*, defaults to `State`):The `State` subclass this environment reports, used for the `/state`response model and the `state` entry of `/schema`.mode (`ServerMode` or `str`, *optional*):Server mode. When `None`, resolved from the `OPENENV_MODE`environment variable, defaulting to simulation.21 unmodified lines* **Environment Reset**: Initialize or restart episodes* **Action Execution**: Send actions and receive observations* **State Inspection**: Query current environment state* **Schema Access**: Retrieve JSON schemas for actions and observations## Workflow23 unmodified lines},{"name": "Schema","description": "JSON Schema endpoints for actions, observations, and state",},{"name": "Health", "description": "Service health and status checks"},],2 unmodified linesopenapi_url="/openapi.json",contact={"name": "OpenEnv Team","url": "https://github.com/huggingface/OpenEnv",},license_info={"name": "BSD-3-Clause","url": "https://github.com/huggingface/OpenEnv/blob/main/LICENSE",},)5 unmodified linesconcurrency_config=concurrency_config,env_name=env_name,state_cls=state_cls,reset_observation_cls=reset_observation_cls,)if mode is None:mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value)server.register_routes(app, mode=mode)return app13 unmodified lines1415161718192021222333 unmodified lines5758596061626364656667686970717273747576777879114 unmodified lines19419519619719819920021 unmodified lines22222322422522622722822923023139 unmodified lines2712722732742752762771 unmodified line2792802812822832842852862872882892902 unmodified lines2932942952962972982993003013022 unmodified lines30530630730830931031184 unmodified lines39639739839940040140240340423 unmodified lines4284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466477 unmodified lines65565665765865966066162 unmodified lines7247257267277287297307317327337347357367377387397407417427437447457467477487494 unmodified lines7547557567577587597609 unmodified lines770771772773774775776777778779780781782783298 unmodified lines10821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111194 unmodified lines120612071208120912101211121233 unmodified lines1246124712481249125012511252125312541255125612571258125912601261126212631264126512667 unmodified lines127412751276127712781279128047 unmodified lines13281329133013311332133313342 unmodified lines13371338133913401341134213431344134513461347134813495 unmodified lines1355135613571358135913601361136218 unmodified lines13811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140716 unmodified lines14241425142614271428142914309 unmodified lines144014411442144314441445144634 unmodified lines1481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215 unmodified lines1528152915301531153215331534165 unmodified lines1700170117021703170417051706240 unmodified lines1947194819491950195119521953195419551956195719581959196016 unmodified lines19771978197919801981198219831984198519867 unmodified lines199419951996199719981999200044 unmodified lines204520462047204820492050205120522 unmodified lines2055205620572058205920602061206220632064206520662067206820699 unmodified lines207920802081208220832084208516 unmodified lines21022103210421052106210721082109211021112112211321142115211621172118211921208 unmodified lines212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219525 unmodified lines22212222222322242225222622272228222922302231223270 unmodified lines2303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023413 unmodified lines2345234623472348234923502351235223532354235523561 unmodified line2358235923602361236223632364236523662367236853 unmodified lines242224232424242524262427242838 unmodified lines24672468246924702471247224732474247521 unmodified lines249724982499250025012502250312 unmodified lines251625172518251925202521252210 unmodified lines253325342535253625372538253919 unmodified lines25592560256125622563256425652566256721 unmodified lines258925902591259225932594259523 unmodified lines26192620262126222623262426252 unmodified lines262826292630263126322633263426352636263726385 unmodified lines2644264526462647264826492650265126522653265426552656265713 unmodified linesimport jsonimport loggingimport osimport secretsimport timeimport uuidfrom concurrent.futures import Future, ThreadPoolExecutorfrom contextlib import AsyncExitStackfrom typing import (Any,33 unmodified linesListToolsAction,ListToolsObservation,McpMethod,ToolErrorType,WSMCPMessage,WSMCPResponse,)from .route_config import GetEndpointConfig, register_get_endpointsfrom .serialization import deserialize_action, serialize_observationfrom .session_telemetry import (rubric_counts,rubric_snapshot,SeedAcceptance,SessionTelemetry,ValidationOpenedData,ValidationOpenedResponse,ValidationOpenMessage,ValidationReadMessage,ValidationResponse,)from .types import (Action,ConcurrencyConfig,114 unmodified linesstate_cls: Type[State] = State,*,reset_observation_cls: Optional[Type[Observation]] = None,reset_cls: Type[ResetRequest] = ResetRequest,):"""Initialize HTTP server wrapper.21 unmodified linesThe `State` subclass this environment reports. Used for the `/state`response model and the `state` entry of `/schema`, so that fieldsdeclared by the subclass are published and serialized.reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):The `ResetRequest` subclass describing this environment's reset parameters.Published as the `reset` entry of `/schema`. It is not used to validatereset requests.Raises:`ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided.39 unmodified linesself.observation_cls = observation_clsself.reset_observation_cls = reset_observation_cls or observation_clsself.state_cls = state_clsself.reset_cls = reset_clsself.env_name = env_name or self._default_env_name()# Session management for WebSocket connections1 unmodified lineself._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_stacks: Dict[str, AsyncExitStack] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_modes: Dict[str, Optional[str]] = {}self._session_websocket_attachments: set[str] = set()self._session_pending_closes: set[str] = set()# WebSocket messages being handled, per session; such sessions are never# idle-reaped. A count, since an attached socket can share the session.self._session_operations_in_flight: Dict[str, int] = {}self._session_lock = asyncio.Lock()# Create thread pool for running sync code in async context2 unmodified linesself._requires_single_thread_executor = self._detect_single_thread_requirement()self._shared_session_executor: Optional[ThreadPoolExecutor] = Noneself._shared_session_creation_lock: Optional[asyncio.Lock] = Noneif self._requires_single_thread_executor:self._shared_session_executor = ThreadPoolExecutor(max_workers=1)self._shared_session_creation_lock = asyncio.Lock()# Idle session reaper configuration.# Timeout is taken from ConcurrencyConfig.session_timeout;2 unmodified linesself._concurrency_config.session_timeout)self._reaper_task: Optional[asyncio.Task[None]] = Noneself._reaper_stop_event = asyncio.Event()def _default_env_name(self) -> str:factory = self._env_factory84 unmodified linesreturn valid_kwargsasync def _create_session(self, mode: Optional[str | ServerMode] = None) -> tuple[str, Environment]:"""Create a new WebSocket session with its own environment instance.23 unmodified linesself._session_executors[session_id] = executorself._sessions[session_id] = None # placeholder until env is ready# Every await from here to registration runs with the slot reserved, so# cancellation has to release it. CancelledError is not an Exception, so# the handlers below never see it, and a surviving reservation is# permanent: capacity counts _sessions, while the idle reaper only scans# sessions that reached _session_info.env: Optional[Environment] = Nonestack: Optional[AsyncExitStack] = Nonefactory_future: Optional[Future[Environment]] = Nonemcp_entry_task: Optional[asyncio.Task[Any]] = Nonecleanup_task: Optional[asyncio.Task[None]] = Nonecreation_lock_acquired = Falsedef start_cleanup() -> asyncio.Task[None]:# Startup failure and cancellation share one cleanup owner. Whoever# gets here first starts the task; a later caller joins the same one# instead of submitting a second env.close().nonlocal cleanup_taskif cleanup_task is None:cleanup_task = asyncio.create_task(self._discard_reserved_session(session_id,executor,env,stack,factory_future,mcp_entry_task,))return cleanup_taskasync def drain_cleanup(task: asyncio.Task[None]) -> None:# ASGI cancel scopes may cancel a request repeatedly. Keep awaiting# the shielded cleanup task until it reaches a terminal state so# cancellation cannot escape while the reservation still exists.try:await asyncio.shield(task)except asyncio.CancelledError:while not task.done():try:await asyncio.shield(task)except asyncio.CancelledError:passtask.result()raisetry:if self._shared_session_creation_lock is not None:await self._shared_session_creation_lock.acquire()creation_lock_acquired = Truetry:# Create environment in the executor thread (outside lock).# submit() plus wrap_future() is what run_in_executor() does# internally; spelling it out keeps the thread's future, which is# the only handle on an environment still being built when the# await is cancelled.loop = asyncio.get_event_loop()factory_future = executor.submit(self._env_factory)env = await asyncio.wrap_future(factory_future, loop=loop)mode_val = (mode.valueif isinstance(mode, ServerMode)else (str(mode) if mode is not None else None))if mode_val is not None and hasattr(env, "set_mode"):env.set_mode(mode_val)except Exception as e:async with self._session_lock:if executor is not self._shared_session_executor:executor.shutdown(wait=False)self._session_executors.pop(session_id, None)self._sessions.pop(session_id, None)factory_name = getattr(self._env_factory, "__name__", str(self._env_factory))raise EnvironmentFactoryError(factory_name) from e# The factory result is delivered, so the shared executor thread is# free. Release the creation lock before MCP startup: it exists to# order factory calls (and disposal of a factory cancelled# mid-flight) on that one thread, and holding it through an MCP# handshake lets a single stalled connection starve every later# session's constructor. Cancellation during construction keeps the# lock instead, so late-factory disposal still precedes the next# constructor.if creation_lock_acquired:assert self._shared_session_creation_lock is not Noneself._shared_session_creation_lock.release()creation_lock_acquired = False# Hold the MCP session open for the lifetime of this session,# matching the WebSocket path's AsyncExitStack pattern. This# prevents per-request MCP transport teardown/reconnection and# preserves FastMCP session state (ctx.set_state / ctx.get_state)# across HTTP calls within the same OpenEnv session.stack = AsyncExitStack()try:mcp_session_factory = getattr(env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())# Enter in its own task and await it shielded. An entry that# blocks before yielding may release resources in its own# finally, and the stack cannot replay that cleanup: it# registers the exit callback only once __aenter__ returns.# Shielding keeps repeated cancellation off the entry, so# the cleanup owner can cancel it exactly once and drain the# unwind instead of aborting it part-way.mcp_entry_task = asyncio.create_task(stack.enter_async_context(mcp_session_cm))await asyncio.shield(mcp_entry_task)except Exception:# MCP transport failed to start — clean up the reserved slot,# the env, and the executor so they don't leak permanently# against _max_concurrent_envs. Cancellation arriving mid-close# joins this same task rather than closing the env twice.await drain_cleanup(start_cleanup())raiseasync with self._session_lock:self._sessions[session_id] = envself._session_stacks[session_id] = stackif mode is not None:self._session_modes[session_id] = mode_valnow = time.time()self._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=now,step_count=0,environment_type=type(env).__name__,)except asyncio.CancelledError:# Joins the cleanup already under way if startup failure began one,# so the environment is closed by a single owner.try:await drain_cleanup(start_cleanup())except asyncio.CancelledError:passraisefinally:if creation_lock_acquired:assert self._shared_session_creation_lock is not Noneself._shared_session_creation_lock.release()return session_id, envasync def _discard_reserved_session(self,session_id: str,executor: ThreadPoolExecutor,env: Optional[Environment] = None,stack: Optional[AsyncExitStack] = None,factory_future: Optional[Future[Environment]] = None,mcp_entry_task: Optional[asyncio.Task[Any]] = None,) -> None:"""Release a session slot reserved by `_create_session` that never opened.Drops every mapping the slot may have reached and closes whatever theinterrupted creation built, so the slot stops counting against`max_concurrent_envs` and no environment outlives it.Args:session_id (`str`):The reserved session ID to release.executor (`ThreadPoolExecutor`):The executor reserved alongside the slot.env (`Environment`, *optional*):The environment, if the factory already returned one.stack (`AsyncExitStack`, *optional*):The MCP session stack, if one was already entered.factory_future (`Future`, *optional*):The factory's thread future, if the factory call was reached.Used to close an environment the thread is still building.mcp_entry_task (`asyncio.Task`, *optional*):The in-flight MCP session entry, if MCP startup was reached.Cancelled and drained here so an entry interrupted before ityielded can finish releasing what it had already acquired."""if mcp_entry_task is not None:# Cancel at most once: a second cancellation would abort the entry's# own unwind, and the stack holds no exit callback to replay it.if not mcp_entry_task.done():mcp_entry_task.cancel()try:await mcp_entry_taskexcept (asyncio.CancelledError, Exception):# A cancelled or failed entry has unwound itself. If it did# finish, `stack` owns the context and closes it below.passif env is None and factory_future is not None:# Cancelling the await can cancel a queued future, but cannot stop a# factory whose executor thread is already running. In that case,# keep the capacity reservation until its result can be disposed of.if not factory_future.cancel():try:env = await asyncio.wrap_future(factory_future)except (asyncio.CancelledError, Exception):# A cancelled or failed factory produced no environment to# close. Its capacity reservation still has to be released.env = Noneawait self._cleanup_session_resources(env, executor, stack)async with self._session_lock:self._sessions.pop(session_id, None)self._session_executors.pop(session_id, None)self._session_stacks.pop(session_id, None)self._session_info.pop(session_id, None)self._session_modes.pop(session_id, None)async def _destroy_session(self, session_id: str) -> None:"""Destroy a WebSocket session and cleanup resources.7 unmodified linesexecutor = self._session_executors.pop(session_id, None)stack = self._session_stacks.pop(session_id, None)self._session_info.pop(session_id, None)self._session_modes.pop(session_id, None)self._session_websocket_attachments.discard(session_id)self._session_pending_closes.discard(session_id)62 unmodified linesinterval = max(timeout / 4, 5.0) # check frequently enoughwhile True:try:try:await asyncio.wait_for(self._reaper_stop_event.wait(), timeout=interval)returnexcept asyncio.TimeoutError:passnow = time.time()stale_ids: list[str] = []async with self._session_lock:for sid, info in self._session_info.items():if (sid not in self._session_websocket_attachmentsand sid not in self._session_operations_in_flightand now - info.last_activity_at > timeout):stale_ids.append(sid)for sid in stale_ids:if self._reaper_stop_event.is_set():return# Re-check under lock: activity may have arrived since# the snapshot was taken, making this session active again.# Refresh `now` so slow _destroy_session calls don't cause4 unmodified linesif (info is Noneor sid in self._session_websocket_attachmentsor sid in self._session_operations_in_flightor (now - info.last_activity_at) <= timeout):continue9 unmodified linesdef _start_reaper(self) -> None:"""Start the idle-session reaper if a timeout is configured."""if self._session_idle_timeout_s is not None and self._reaper_task is None:self._reaper_stop_event.clear()self._reaper_task = asyncio.create_task(self._reap_idle_sessions())async def _stop_reaper(self) -> None:"""Stop the reaper after any in-progress session cleanup finishes."""if self._reaper_task is not None:self._reaper_stop_event.set()await self._reaper_taskself._reaper_task = Nonedef get_session_info(self, session_id: str) -> Optional[SessionInfo]:298 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Only explicitly provisioned simulation servers accept validation controls.validation_token = os.environ.get("OPENENV_VALIDATION_TOKEN", "")validation_enabled = (mode == ServerMode.SIMULATION and 32 <= len(validation_token) <= 256)# Wire up session lifecycle via app eventsserver_ref = selfasync def _start_session_reaper() -> None:server_ref._start_reaper()async def _shutdown_sessions() -> None:await server_ref._stop_reaper()async with server_ref._session_lock:session_ids = list(server_ref._sessions)for session_id in session_ids:await server_ref._destroy_session(session_id)if server_ref._shared_session_executor is not None:server_ref._shared_session_executor.shutdown(wait=True)if not getattr(app.router, "_openenv_reaper_registered", False):app.router.on_startup.append(_start_session_reaper)app.router.on_shutdown.append(_shutdown_sessions)app.router._openenv_reaper_registered = True # type: ignore[attr-defined]# Helper function to handle reset endpoint94 unmodified linesrequest_id=request_id,)try:created_session_id, _ = await self._create_session(mode=mode)except SessionCapacityError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,33 unmodified lines)async with self._session_lock:session_mode = self._session_modes.get(target_session_id)if ((target_session_id in self._sessionsor target_session_id in self._session_websocket_attachments)and session_mode is not Noneand session_mode != mode.value):return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",request_id=request_id,)if target_session_id in self._session_websocket_attachments:env = _MISSINGattached = True7 unmodified linesexecutor = self._session_executors.pop(target_session_id, None)stack = self._session_stacks.pop(target_session_id, None)self._session_info.pop(target_session_id, None)self._session_modes.pop(target_session_id, None)elif not attached:executor = Nonestack = None47 unmodified lineselif requested_session_id:async with self._session_lock:_env = self._sessions.get(requested_session_id, _MISSING)session_mode = self._session_modes.get(requested_session_id)if _env is _MISSING:return JsonRpcResponse.error_response(2 unmodified linesrequest_id=request_id,)if session_mode is not None and session_mode != mode.value:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",request_id=request_id,)if _env is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,5 unmodified linesmanaged_session_id = requested_session_idelse:_env = self._env_factory()if hasattr(_env, "set_mode"):_env.set_mode(mode.value)should_close = Truetry:mcp_client = getattr(_env, "mcp_client", None)18 unmodified lines}if method == McpMethod.TOOLS_LIST:if hasattr(_env, "_async_handle_list_tools"):obs = await _env._async_handle_list_tools()if obs.metadata and "error" in obs.metadata:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,obs.metadata["error"],request_id=request_id,)tools = [{"name": t.name,"description": t.description or "","inputSchema": t.input_schema,}for t in obs.tools]return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,)# Check if environment is MCP-enabledif mcp_client is None and mcp_server is None:if supports_mcp_style_actions:16 unmodified linesrequest_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,"Environment does not support MCP",request_id=request_id,)9 unmodified linesreturn JsonRpcResponse.success(result={"tools": [t.model_dump(by_alias=True)if hasattr(t, "model_dump")else dict(t)for t in tools34 unmodified linesrequest_id=request_id,)if hasattr(_env, "_mode_tools") and any(m is not None for m in _env._mode_tools.get(tool_name, {})):obs = await _env._async_handle_call_tool(CallToolAction(tool_name=tool_name, arguments=arguments))if obs.error:err_code = (JsonRpcErrorCode.INVALID_PARAMSif obs.error.error_typein (ToolErrorType.INVALID_ARGS,ToolErrorType.TOOL_NOT_FOUND,)else JsonRpcErrorCode.INTERNAL_ERROR)return JsonRpcResponse.error_response(err_code,obs.error.message,request_id=request_id,)return JsonRpcResponse.success(result=_make_json_serializable(obs.result),request_id=request_id,)if mcp_client is None and mcp_server is None:if supports_mcp_style_actions:observation = await call_mcp_style_step(15 unmodified linesrequest_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,"Environment does not support MCP",request_id=request_id,)165 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session(mode=mode)if session_env is None:raise RuntimeError("Session environment not initialized for MCP websocket"240 unmodified linestags=["Schema"],summary="Get all JSON schemas",description="""Get JSON schemas for actions, observations, state, and reset parameters in a single response.Returns a combined schema object containing:- **action**: JSON schema for actions accepted by this environment- **observation**: JSON schema for observations returned by step- **reset_observation**: JSON schema for observations returned by reset- **state**: JSON schema for environment state objects- **reset**: JSON schema for reset parameters accepted by this environmentThis is more efficient than calling individual schema endpoints and providesall schema information needed to interact with the environment.16 unmodified lines"type": "object","properties": {"step_count": {"type": "integer"}},},"reset": {"type": "object","properties": {"seed": {"type": "integer"}},},}}},7 unmodified linesobservation=self.observation_cls.model_json_schema(),reset_observation=self.reset_observation_cls.model_json_schema(),state=self.state_cls.model_json_schema(),reset=self.reset_cls.model_json_schema(),)# Register MCP endpoint for production mode (direct MCP access)44 unmodified linessession_env = Noneowns_session = Falseattached_session = Falsetelemetry = Noneoperations_started = Falsetry:requested_session_id = websocket.query_params.get("session_id")2 unmodified linesattached_env = self._sessions.get(requested_session_id, _MISSING)session_mode = self._session_modes.get(requested_session_id)if attached_env is _MISSING:raise RuntimeError(f"Unknown session_id: {requested_session_id}")if session_mode is not None and session_mode != mode.value:raise RuntimeError(f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'")if attached_env is None:raise RuntimeError(f"Session {requested_session_id} is still initializing"9 unmodified linesattached_session = Trueself._update_session_activity(session_id)else:session_id, session_env = await self._create_session(mode=mode)owns_session = Trueif session_env is None:16 unmodified lines# Receive message from clientraw_message = await websocket.receive_text()# The reaper or shutdown may have destroyed this# session (closing its env and freeing its slot).if session_id not in self._sessions:error_resp = WSErrorResponse(data={"message": "Session expired or was closed; ""open a new connection","code": WSErrorCode.SESSION_ERROR,})await websocket.send_text(error_resp.model_dump_json())breaktry:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:8 unmodified linesmsg_type = message_dict.get("type", "")if msg_type in {"validation_open", "validation_read"}:# Do not return Pydantic input/error details: these messages# contain credentials and must never echo or log them.try:if not validation_enabled or not owns_session:raise ValueError("Validation unavailable")if msg_type == "validation_open":auth = ValidationOpenMessage.model_validate(message_dict)if telemetry is not None or operations_started:raise ValueError("Validation already started")if not secrets.compare_digest(validation_token.encode(),auth.data.token.get_secret_value().encode(),):raise ValueError("Unauthorized")telemetry = SessionTelemetry()response = ValidationOpenedResponse(data=ValidationOpenedData(capability=telemetry.capability))else:auth = ValidationReadMessage.model_validate(message_dict)if telemetry is None or not telemetry.authorized(auth.data.capability.get_secret_value()):raise ValueError("Unauthorized")response = ValidationResponse(data=telemetry.snapshot)except Exception:response = WSErrorResponse(data={"message": "Validation unavailable or unauthorized","code": WSErrorCode.VALIDATION_ERROR,})await websocket.send_text(response.model_dump_json())continueseed_acceptance = Nonebefore_scores = Noneif msg_type in {"reset", "step", "state"}:operations_started = Trueif telemetry is not None and msg_type == "step":try:before_scores = rubric_counts(getattr(session_env, "rubric", None))except Exception:telemetry.snapshot.rubric_error = ("Rubric introspection unavailable")in_flight = self._session_operations_in_flightin_flight[session_id] = in_flight.get(session_id, 0) + 1self._update_session_activity(session_id)try:match msg_type:case "reset":25 unmodified lines))if telemetry is not None:seed_acceptance = SeedAcceptance(requested="seed" in msg.data,value=msg.data.get("seed"),accepted="seed" in valid_kwargs,)response = WSObservationResponse(data=serialize_observation(observation),70 unmodified lines})if telemetry is not None and msg_type in {"reset","step","state",}:nodes = Nonetry:if msg_type in {"reset", "step"}:nodes = rubric_snapshot(getattr(session_env, "rubric", None),before_scores,)except Exception:nodes = []telemetry.snapshot.rubric_error = ("Rubric introspection unavailable")telemetry.append(msg_type,message_dict,response.model_dump(mode="json"),seed=seed_acceptance,rubric=nodes,)await websocket.send_text(response.model_dump_json())except ValidationError as e:if telemetry is not None and msg_type in {"reset","step","state",}:telemetry.incomplete("Session operation failed")error_resp = WSErrorResponse(data={"message": "Invalid message",3 unmodified lines)await websocket.send_text(error_resp.model_dump_json())except Exception as e:if telemetry is not None and msg_type in {"reset","step","state",}:telemetry.incomplete("Session operation failed")error_resp = WSErrorResponse(data={"message": str(e),1 unmodified line})await websocket.send_text(error_resp.model_dump_json())finally:in_flight[session_id] -= 1if in_flight[session_id] == 0:del in_flight[session_id]self._update_session_activity(session_id)except WebSocketDisconnect:pass53 unmodified lines*,mode: Optional[ServerMode | str] = None,reset_observation_cls: Optional[Type[Observation]] = None,reset_cls: Type[ResetRequest] = ResetRequest,) -> FastAPI:"""Create a FastAPI application with or without web interface.38 unmodified linesstate_cls (`Type[State]`, *optional*, defaults to `State`):The `State` subclass this environment reports, used for the `/state`response model and the `state` entry of `/schema`.reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):The `ResetRequest` subclass describing this environment's reset parameters,published as the `reset` entry of `/schema`. Not used for validation.mode (`ServerMode` or `str`, *optional*):Server mode. When `None`, resolved from the `OPENENV_MODE`environment variable, defaulting to simulation.21 unmodified linesmax_concurrent_envs,concurrency_config,state_cls=state_cls,reset_cls=reset_cls,reset_observation_cls=reset_observation_cls,gradio_builder=gradio_builder,custom_tab_name=custom_tab_name,12 unmodified linesconcurrency_config,env_name=env_name,state_cls=state_cls,reset_cls=reset_cls,reset_observation_cls=reset_observation_cls,mode=mode,)10 unmodified lines*,mode: Optional[ServerMode | str] = None,reset_observation_cls: Optional[Type[Observation]] = None,reset_cls: Type[ResetRequest] = ResetRequest,) -> FastAPI:"""Create a FastAPI application with comprehensive documentation.19 unmodified linesstate_cls (`Type[State]`, *optional*, defaults to `State`):The `State` subclass this environment reports, used for the `/state`response model and the `state` entry of `/schema`.reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):The `ResetRequest` subclass describing this environment's reset parameters,published as the `reset` entry of `/schema`. Not used for validation.mode (`ServerMode` or `str`, *optional*):Server mode. When `None`, resolved from the `OPENENV_MODE`environment variable, defaulting to simulation.21 unmodified lines* **Environment Reset**: Initialize or restart episodes* **Action Execution**: Send actions and receive observations* **State Inspection**: Query current environment state* **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters## Workflow23 unmodified lines},{"name": "Schema","description": "JSON Schema endpoints for actions, observations, state, and reset parameters",},{"name": "Health", "description": "Service health and status checks"},],2 unmodified linesopenapi_url="/openapi.json",contact={"name": "OpenEnv Team","url": "https://github.com/openenv/OpenEnv",},license_info={"name": "BSD-3-Clause","url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE",},)5 unmodified linesconcurrency_config=concurrency_config,env_name=env_name,state_cls=state_cls,reset_cls=reset_cls,reset_observation_cls=reset_observation_cls,)if mode is None:mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value)server.register_routes(app, mode=mode)from .security import attach_guardattach_guard(app)return app
104 unmodified lines105106107108109110111111 unmodified lines223224225226227228229104 unmodified linesSelecting a task is not part of this protocol — pass the chosen split andindex to `reset()` instead. See the[Task API guide](https://huggingface.co/docs/openenv/guides/task-api).Examples:111 unmodified linesclass Environment(ABC, Generic[ActT, ObsT, StateT]):"""Base class for all environment servers following Gym/Gymnasium API.See [rfcs/004-rubrics.md](https://github.com/huggingface/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details.Args:transform (`Transform`, *optional*):104 unmodified lines105106107108109110111111 unmodified lines223224225226227228229104 unmodified linesSelecting a task is not part of this protocol — pass the chosen split andindex to `reset()` instead. See the[Task API guide](https://openenv.github.io/OpenEnv/main/guides/task-api).Examples:111 unmodified linesclass Environment(ABC, Generic[ActT, ObsT, StateT]):"""Base class for all environment servers following Gym/Gymnasium API.See [rfcs/004-rubrics.md](https://github.com/openenv/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details.Args:transform (`Transform`, *optional*):
85 unmodified lines86878889909192939495969798991001011025 unmodified lines10810911011111211311472 unmodified lines1871881891901911921931 unmodified line19519619719819920048 unmodified lines249250251252253254255240 unmodified lines49649749849950050150216 unmodified lines51952052152252352452552652752852953053153253353453553653753853985 unmodified linesdef get_server_tools(mcp_server: Any) -> Dict[str, Any]:"""Get tools from a FastMCP server, compatible with both 2.x and 3.x.Returns:Dictionary mapping tool names to tool objects."""# FastMCP 2.x: get_tools() returns dict {name: Tool}if hasattr(mcp_server, "get_tools"):result = run_async_safely(mcp_server.get_tools())if isinstance(result, dict):return result# FastMCP 3.x: list_tools() returns list of Tool objectsif hasattr(mcp_server, "list_tools"):tools_list = run_async_safely(mcp_server.list_tools())return {t.name: t for t in tools_list}5 unmodified linesreturn Tool(name=tool.name,description=tool.description or "",input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {},)72 unmodified linesself._validate_tool_names(mcp_server)self.mcp_server = mcp_serverself.mcp_client = Client(mcp_server)# Track mode-specific tools: {tool_name: {mode: func}}# mode can be "production", "simulation", or None (available in all modes)1 unmodified line# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)def _require_mcp_client(self) -> Any:"""Return MCP client or raise if environment has been closed."""48 unmodified linesdef _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]:"""Get tools from a FastMCP server, compatible with both 2.x and 3.x.Returns:Dictionary mapping tool names to tool objects.240 unmodified linestools_result = await self._async_list_tools()tools = []for tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(_tool_from_server_tool(tool))for mode_schemas in self._mode_tool_schemas.values():schema = _schema_for_mode(mode_schemas, current_mode)16 unmodified linestool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]if None in mode_info:func = mode_info[None]elif current_mode in mode_info:func = mode_info[current_mode]else:return CallToolObservation(tool_name=tool_name,result=None,error=ToolError(error_type=ToolErrorType.TOOL_NOT_FOUND,message=f"Tool '{tool_name}' not available in {current_mode} mode",),)try:if inspect.iscoroutinefunction(func):result = await func(**action.arguments)85 unmodified lines86878889909192939495969798991001011025 unmodified lines10810911011111211311472 unmodified lines1871881891901911921931941951 unmodified line19719819920020120220320420520620748 unmodified lines256257258259260261262240 unmodified lines50350450550650750850951016 unmodified lines52752852953053153253353453553653753885 unmodified linesdef get_server_tools(mcp_server: Any) -> Dict[str, Any]:"""Get tools from a FastMCP server.Returns:Dictionary mapping tool names to tool objects."""# FastMCP server tools are exposed as a name-to-tool mapping.if hasattr(mcp_server, "get_tools"):result = run_async_safely(mcp_server.get_tools())if isinstance(result, dict):return result# Some server adapters expose the tools as a list instead.if hasattr(mcp_server, "list_tools"):tools_list = run_async_safely(mcp_server.list_tools())return {t.name: t for t in tools_list}5 unmodified linesreturn Tool(name=tool.name,description=tool.description or "",input_schema=tool.input_schema,)72 unmodified linesself._validate_tool_names(mcp_server)self.mcp_server = mcp_server# OpenEnv sessions keep MCP state across tool calls. FastMCP 4's default# modern protocol is sessionless, so use its supported legacy handshake.self.mcp_client = Client(mcp_server, mode="legacy")# Track mode-specific tools: {tool_name: {mode: func}}# mode can be "production", "simulation", or None (available in all modes)1 unmodified line# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)self._mode: Optional[str] = Nonedef set_mode(self, mode: Optional[str]) -> None:"""Set the active mode ('production' or 'simulation') for mode-aware tools."""self._mode = modedef _require_mcp_client(self) -> Any:"""Return MCP client or raise if environment has been closed."""48 unmodified linesdef _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]:"""Get tools from a FastMCP server.Returns:Dictionary mapping tool names to tool objects.240 unmodified linestools_result = await self._async_list_tools()tools = []for tool in tools_result:mode_schemas = self._mode_tool_schemas.get(tool.name, {})if _schema_for_mode(mode_schemas, current_mode) is None:tools.append(_tool_from_server_tool(tool))for mode_schemas in self._mode_tool_schemas.values():schema = _schema_for_mode(mode_schemas, current_mode)16 unmodified linestool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)mode_info = self._mode_tools.get(tool_name, {})if None in mode_info or current_mode in mode_info:if None in mode_info:func = mode_info[None]elif current_mode in mode_info:func = mode_info[current_mode]try:if inspect.iscoroutinefunction(func):result = await func(**action.arguments)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192# SPDX-License-Identifier: BSD-3-Clause
"""Optional fastapi-guard security middleware for environment servers.
Opt-in via the `OPENENV_GUARD_*` environment variables. When disabled (thedefault), `attach_guard` is a no-op and environment servers behave exactly asbefore.
Install the extra with `pip install "openenv[security]"` and enable with`OPENENV_GUARD_ENABLED=1` to get IP block/allow lists, rate limiting,user-agent blocking, penetration-attempt detection with auto-ban, and optionalRedis-backed distributed state (fastapi-guard).
Health and schema endpoints are excluded from detection checks soorchestrators can probe the server; global IP allow/block lists are stillenforced on those paths.
WebSocket connections (`/ws`, `/mcp`, `/harness`, `/ws/ui`) get the samechecks on the handshake: ban, IP lists, a separate rate-limit bucket andpenetration detection on the path, query and headers. A refused handshake isclosed before `accept()`, so the client gets HTTP 403 on the upgrade and nosocket. Messages on an accepted connection are not screened, for the samereason request bodies are not. With Redis configured, the guard initializes atstartup; while Redis is unreachable a handshake is closed with 1013 and HTTPrequests are refused."""
from __future__ import annotations
import osfrom contextlib import asynccontextmanagerfrom typing import Any
from starlette import statusfrom starlette.exceptions import WebSocketExceptionfrom starlette.websockets import WebSocket
DEFAULT_EXCLUDED_PATHS = [ "/health", "/schema", "/metadata", "/docs", "/redoc", "/openapi.json",]# Empty by default on purpose: trusting private-range peers would let# any of them spoof X-Forwarded-For past the blocklist and rate limits.# Behind a reverse proxy, list the proxy's addresses in# OPENENV_GUARD_TRUSTED_PROXIES.DEFAULT_TRUSTED_PROXIES = ""
def _env_list(name: str, default: str = "") -> list[str]: raw = os.environ.get(name, default) return [item.strip() for item in raw.split(",") if item.strip()]
def _env_bool(name: str) -> bool: raw = os.environ.get(name) if raw is None or not raw.strip(): return False normalized = raw.strip().lower() if normalized in ("1", "true", "yes", "on"): return True if normalized in ("0", "false", "no", "off"): return False msg = f"{name} must be a boolean (1/true/yes/on or 0/false/no/off), got {raw!r}" raise ValueError(msg)
def _build_security_config() -> Any: from guard import SecurityConfig
kwargs: dict[str, Any] = { "enable_rate_limiting": True, "rate_limit": int(os.environ.get("OPENENV_GUARD_RATE_LIMIT", "100")), "rate_limit_window": int( os.environ.get("OPENENV_GUARD_RATE_LIMIT_WINDOW", "60") ), "enable_ip_banning": True, "auto_ban_threshold": int( os.environ.get("OPENENV_GUARD_AUTO_BAN_THRESHOLD", "10") ), "auto_ban_duration": int( os.environ.get("OPENENV_GUARD_AUTO_BAN_DURATION", "300") ), # Environment/request bodies are model input (observations, prompts, # completions), not commands this server executes: signature-scanning # them false-positives on ordinary content. URL, query, and header # screening stay on. "detection_scan_body": False, "enable_penetration_detection": True, # In-memory state unless a Redis URL is configured: never implicitly # depend on a Redis server being reachable at localhost. "enable_redis": False, "blacklist": tuple(_env_list("OPENENV_GUARD_BLOCKED_IPS")), "blocked_user_agents": _env_list("OPENENV_GUARD_BLOCKED_USER_AGENTS"), "trusted_proxies": tuple( _env_list("OPENENV_GUARD_TRUSTED_PROXIES", DEFAULT_TRUSTED_PROXIES) ), "trusted_proxy_depth": int( os.environ.get("OPENENV_GUARD_TRUSTED_PROXY_DEPTH", "1") ), "exclude_paths": DEFAULT_EXCLUDED_PATHS, # fastapi-guard sends security headers unless this is None, and its # X-Frame-Options: SAMEORIGIN stops a Space page from framing the app. "security_headers": None, }
allowed_ips = _env_list("OPENENV_GUARD_ALLOWED_IPS") if allowed_ips: kwargs["whitelist"] = tuple(allowed_ips)
redis_url = os.environ.get("OPENENV_GUARD_REDIS_URL") if redis_url: kwargs["enable_redis"] = True kwargs["redis_url"] = redis_url
return SecurityConfig(**kwargs)
class _WebSocketGuardMiddleware: # SecurityMiddleware is a BaseHTTPMiddleware, which never sees websocket # scopes, so every handshake goes through fastapi-guard's guard_websocket. def __init__(self, app: Any, config: Any) -> None: from guard import guard_websocket from guard.lifespan import _find_security_redis_handler, guard_startup
self.app = app self.config = config self.guard_websocket = guard_websocket # guard_websocket reads Redis through this; None means not connected. self.find_redis = _find_security_redis_handler self.guard_startup = guard_startup
async def __call__(self, scope: Any, receive: Any, send: Any) -> None: if scope["type"] == "websocket": websocket = WebSocket(scope, receive, send) try: if not await self._redis_ready(scope["app"]): # The HTTP side refuses too until Redis is reachable. raise WebSocketException( code=status.WS_1013_TRY_AGAIN_LATER, reason="Service temporarily unavailable", ) await self.guard_websocket(websocket) except WebSocketException as exc: await websocket.close(code=exc.code, reason=exc.reason) return await self.app(scope, receive, send)
async def _redis_ready(self, app: Any) -> bool: if not self.config.enable_redis or self.find_redis(app) is not None: return True # Retry on each handshake, like the HTTP side's first request. await self.guard_startup(app) return self.find_redis(app) is not None
def attach_guard(app: Any) -> None: """Add the fastapi-guard middleware to `app` when enabled via env.
No-op unless OPENENV_GUARD_ENABLED is set to 1/true/yes/on. """ if not _env_bool("OPENENV_GUARD_ENABLED"): return if getattr(app.state, "guard_attached", False): return try: from guard import SecurityMiddleware from guard.lifespan import guard_lifespan except ImportError as exc: raise ImportError( "OPENENV_GUARD_ENABLED requires fastapi-guard. " 'Install it with: pip install "openenv[security]"' ) from exc
config = _build_security_config() app.add_middleware(SecurityMiddleware, config=config) app.add_middleware(_WebSocketGuardMiddleware, config=config) # Initialize the guard (Redis included) at startup, so a WebSocket-only # worker never runs on in-memory state. existing_lifespan = app.router.lifespan_context
@asynccontextmanager async def lifespan(app: Any): async with guard_lifespan(app): async with existing_lifespan(app) as state: yield state
app.router.lifespan_context = lifespan app.state.guard_attached = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241# SPDX-License-Identifier: BSD-3-Clause
"""Bounded, opt-in evidence emitted by the subject's replay session."""
import jsonimport secretsfrom typing import Any, Literal
from openenv.core.rubrics.base import Rubricfrom openenv.core.rubrics.containers import Gate, Sequential, WeightedSumfrom pydantic import BaseModel, ConfigDict, Field, SecretStr
MAX_TELEMETRY_BYTES = 8 * 1024 * 1024MAX_TRAJECTORY_ACTIONS = 100MAX_TRAJECTORY_RECORDS = 202MAX_RUBRIC_NODES = 128
class _WireModel(BaseModel): model_config = ConfigDict(extra="forbid", strict=True)
class ValidationOpenData(_WireModel): schema_version: Literal[1] token: SecretStr = Field(min_length=32, max_length=256)
class ValidationOpenMessage(_WireModel): type: Literal["validation_open"] data: ValidationOpenData
class ValidationReadData(_WireModel): schema_version: Literal[1] capability: SecretStr = Field(min_length=32, max_length=256)
class ValidationReadMessage(_WireModel): type: Literal["validation_read"] data: ValidationReadData
class ValidationOpenedData(_WireModel): schema_version: Literal[1] = 1 capability: str
class ValidationOpenedResponse(_WireModel): type: Literal["validation_open"] = "validation_open" data: ValidationOpenedData
class SeedAcceptance(_WireModel): requested: bool value: Any = None accepted: bool
class RubricNode(_WireModel): name: str class_name: str children: list[str] aggregation: Literal["weighted_sum", "sequential", "gate", "leaf", "unknown"] config: dict[str, Any] config_available: bool score: Any = None evaluated: bool = False
class StepAttribution(_WireModel): step_index: int rubric: list[RubricNode]
class TrajectoryRecord(_WireModel): operation: Literal["reset", "step", "state"] request: dict[str, Any] response: dict[str, Any]
class SubjectTrajectory(_WireModel): schema_version: Literal[1] = 1 source: Literal["openenv-server"] = "openenv-server" records: list[TrajectoryRecord] = Field(default_factory=list) complete: bool = True reason: str | None = None
class ValidationSnapshot(_WireModel): schema_version: Literal[1] = 1 seed: SeedAcceptance | None = None rubric: list[RubricNode] = Field(default_factory=list) rubric_error: str | None = None attribution: list[StepAttribution] = Field(default_factory=list) trajectory: SubjectTrajectory = Field(default_factory=SubjectTrajectory)
class ValidationResponse(_WireModel): type: Literal["validation"] = "validation" data: ValidationSnapshot
def _rubrics(root: Rubric | None) -> list[tuple[str, Rubric]]: """Visit the named tree with finite size, rejecting cycles and aliases.""" if root is None: return [] result, pending, seen = [], [("root", root)], set() while pending: name, rubric = pending.pop() if id(rubric) in seen or len(result) >= MAX_RUBRIC_NODES: raise ValueError("Rubric tree is cyclic, shared, or exceeds 128 nodes") seen.add(id(rubric)) result.append((name, rubric)) children = list(rubric.named_children()) if any(not key or "." in key for key, _ in children): raise ValueError("Rubric child names must be nonempty path segments") pending.extend((f"{name}.{key}", child) for key, child in reversed(children)) return result
def rubric_counts(root: Rubric | None) -> dict[int, int]: return {id(r): r._evaluation_count for _, r in _rubrics(root)}
def rubric_snapshot( root: Rubric | None, before: dict[int, int] | None = None) -> list[RubricNode]: nodes = [] for name, rubric in _rubrics(root): children = [f"{name}.{key}" for key, _ in rubric.named_children()] aggregation = "unknown" if children else "leaf" config = None # Exact types: a subclass can override scoring, so its semantics are unknown. if type(rubric) is WeightedSum: aggregation, config = "weighted_sum", {"weights": list(rubric._weights)} elif type(rubric) is Sequential: aggregation, config = "sequential", {} elif type(rubric) is Gate: aggregation, config = "gate", {"threshold": rubric.threshold} else: config = rubric.validation_config() evaluated = before is not None and rubric._evaluation_count > before.get( id(rubric), 0 ) nodes.append( RubricNode( name=name, class_name=f"{type(rubric).__module__}.{type(rubric).__qualname__}", children=children, aggregation=aggregation, config={} if config is None else config, config_available=config is not None, score=rubric.last_score if evaluated else None, evaluated=evaluated, ) ) json.dumps([node.model_dump() for node in nodes], allow_nan=False) return nodes
class SessionTelemetry: """Own one socket's capability and a detached record of completed operations."""
def __init__(self): self.capability = secrets.token_urlsafe(32) self.snapshot = ValidationSnapshot() self._bytes = 0 self._steps = 0
def authorized(self, capability: str) -> bool: return secrets.compare_digest(self.capability.encode(), capability.encode())
def append( self, operation: Literal["reset", "step", "state"], request: dict[str, Any], response: dict[str, Any], *, seed: SeedAcceptance | None = None, rubric: list[RubricNode] | None = None, ) -> None: if not self.snapshot.trajectory.complete: return try: # JSON round-trip detaches mutable observations/actions from the record. record = TrajectoryRecord.model_validate( json.loads( json.dumps( { "operation": operation, "request": request, "response": response, }, allow_nan=False, ) ) ) attribution = ( StepAttribution(step_index=self._steps, rubric=rubric or []) if operation == "step" else None ) byte_count = len(record.model_dump_json().encode()) if attribution is not None: byte_count += len(attribution.model_dump_json().encode()) byte_count += ( len(seed.model_dump_json().encode()) if seed is not None else 0 ) # Reserve room for the current rubric, envelope, and seed metadata. current_bytes = len( json.dumps( [ node.model_dump() for node in (self.snapshot.rubric if rubric is None else rubric) ], allow_nan=False, ).encode() ) if ( len(self.snapshot.trajectory.records) >= MAX_TRAJECTORY_RECORDS or operation == "step" and self._steps >= MAX_TRAJECTORY_ACTIONS or self._bytes + byte_count + current_bytes + 4096 > MAX_TELEMETRY_BYTES ): self.incomplete("Session telemetry budget exceeded") return self._bytes += byte_count self.snapshot.trajectory.records.append(record) if seed is not None: self.snapshot.seed = seed.model_copy(deep=True) if rubric is not None: self.snapshot.rubric = [node.model_copy(deep=True) for node in rubric] if attribution is not None: self.snapshot.attribution.append(attribution.model_copy(deep=True)) self._steps += 1 except (TypeError, ValueError): self.incomplete("Session telemetry contains non-JSON data")
def incomplete(self, reason: str) -> None: self.snapshot.trajectory.complete = False self.snapshot.trajectory.reason = reason235 unmodified lines2362372382392402411 unmodified line243244245246247248235 unmodified linesstate: Dict[str, Any] = Field(description="JSON schema for environment state objects")reset_observation: Optional[Dict[str, Any]] = Field(default=None, description="JSON schema for observations returned by reset")1 unmodified line@model_serializer(mode="wrap")def _omit_undeclared_reset_schema(self, handler):data = handler(self)if self.reset_observation is None:data.pop("reset_observation", None)return data235 unmodified lines2362372382392402412422432442451 unmodified line247248249250251252253254235 unmodified linesstate: Dict[str, Any] = Field(description="JSON schema for environment state objects")reset: Optional[Dict[str, Any]] = Field(default=None,description="JSON schema for reset parameters accepted by this environment",)reset_observation: Optional[Dict[str, Any]] = Field(default=None, description="JSON schema for observations returned by reset")1 unmodified line@model_serializer(mode="wrap")def _omit_undeclared_reset_schema(self, handler):data = handler(self)if self.reset is None:data.pop("reset", None)if self.reset_observation is None:data.pop("reset_observation", None)return data
27 unmodified lines28293031323334134 unmodified lines169170171172173174175309 unmodified lines48548648748848949028 unmodified lines51952052152252352412 unmodified lines53753853954054154295 unmodified lines63863964064164264327 unmodified linesfrom .gradio_ui import build_gradio_app, get_gradio_display_titlefrom .interfaces import Environmentfrom .serialization import deserialize_action_with_preprocessing, serialize_observationfrom .types import Action, EnvironmentMetadata, Observation, State_CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"}134 unmodified lineslines += ["", after]lines += ["","More in the [OpenEnv documentation](https://huggingface.co/docs/openenv).",]return "\n".join(lines)309 unmodified lines*,mode: Optional[Any] = None,reset_observation_cls: Optional[Type[Observation]] = None,) -> FastAPI:"""Create a FastAPI application with web interface for the given environment.28 unmodified linestitle instead of the default ``"OpenEnv Agentic Environment: {name}"``.state_cls: The State subclass this environment reports. Used for the /stateresponse model and the state entry of /schema. Defaults to State.mode: Server mode (``ServerMode`` or string). When ``None``, resolvedfrom the ``OPENENV_MODE`` environment variable, defaulting tosimulation.12 unmodified linesconcurrency_config,env_name=env_name,state_cls=state_cls,reset_observation_cls=reset_observation_cls,mode=mode,)95 unmodified linescss=OPENENV_GRADIO_CSS,)return app27 unmodified lines28293031323334134 unmodified lines169170171172173174175309 unmodified lines48548648748848949049128 unmodified lines52052152252352452552652752812 unmodified lines54154254354454554654795 unmodified lines64364464564664764864965027 unmodified linesfrom .gradio_ui import build_gradio_app, get_gradio_display_titlefrom .interfaces import Environmentfrom .serialization import deserialize_action_with_preprocessing, serialize_observationfrom .types import Action, EnvironmentMetadata, Observation, ResetRequest, State_CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"}134 unmodified lineslines += ["", after]lines += ["","More in the [OpenEnv documentation](https://openenv.github.io/OpenEnv/).",]return "\n".join(lines)309 unmodified lines*,mode: Optional[Any] = None,reset_observation_cls: Optional[Type[Observation]] = None,reset_cls: Type[ResetRequest] = ResetRequest,) -> FastAPI:"""Create a FastAPI application with web interface for the given environment.28 unmodified linestitle instead of the default ``"OpenEnv Agentic Environment: {name}"``.state_cls: The State subclass this environment reports. Used for the /stateresponse model and the state entry of /schema. Defaults to State.reset_cls: The ResetRequest subclass describing reset parameters. Publishedas the reset entry of /schema; not used for validation. Defaults toResetRequest.mode: Server mode (``ServerMode`` or string). When ``None``, resolvedfrom the ``OPENENV_MODE`` environment variable, defaulting tosimulation.12 unmodified linesconcurrency_config,env_name=env_name,state_cls=state_cls,reset_cls=reset_cls,reset_observation_cls=reset_observation_cls,mode=mode,)95 unmodified linescss=OPENENV_GRADIO_CSS,)# Security middleware is attached inside create_fastapi_app, before the# gradio mount at /web; it is app-level middleware, so it covers the mount.return app
13 unmodified lines1415161718192031 unmodified lines52535455565758596010 unmodified lines71727374757677787980818213 unmodified linesasync def _source_tools(mcp_server: Any) -> dict[str, Any]:"""Return {name: FastMCP tool}, compatible with FastMCP 2.x and 3.x.Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`],which wraps the same calls in `run_async_safely`; awaiting directly avoids31 unmodified linesreturn mcp_serverfrom fastmcp import Clientfrom fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClientfrom fastmcp.server.transforms import ToolTransformfrom fastmcp.tools.tool_transform import ToolTransformConfigsource_tools = await _source_tools(mcp_server)missing = sorted(set(renames.values()) - set(source_tools))10 unmodified linesasync with Client(mcp_server):yield {}# Forward callbacks in the current request context. Each harness MCP# connection gets its own source session, closed on disconnect.client = StatefulProxyClient(mcp_server)view = FastMCPProxy(name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view",client_factory=client.new_stateful,lifespan=lifespan,)view.add_transform(13 unmodified lines1415161718192031 unmodified lines525354555657585960616210 unmodified lines737475767778798081828384858687888990919213 unmodified linesasync def _source_tools(mcp_server: Any) -> dict[str, Any]:"""Return {name: FastMCP tool}.Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`],which wraps the same calls in `run_async_safely`; awaiting directly avoids31 unmodified linesreturn mcp_serverfrom fastmcp import Clientfrom fastmcp.server.dependencies import get_contextfrom fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClientfrom fastmcp.server.transforms import ToolTransformfrom fastmcp.tools.tool_transform import ToolTransformConfigfrom mcp_types.version import MODERN_PROTOCOL_VERSIONSsource_tools = await _source_tools(mcp_server)missing = sorted(set(renames.values()) - set(source_tools))10 unmodified linesasync with Client(mcp_server):yield {}# Keep one backend client per front connection, and mirror its protocol era.# StatefulProxyClient defaults to legacy, which cannot carry sampling guards.client = StatefulProxyClient(mcp_server)def client_factory():backend = client.new_stateful()if not backend.is_connected():version = get_context().request_context.protocol_versionbackend.mode = version if version in MODERN_PROTOCOL_VERSIONS else "legacy"return backendview = FastMCPProxy(name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view",client_factory=client_factory,lifespan=lifespan,)view.add_transform(
32 unmodified lines3334353637383 unmodified lines42434445464799 unmodified lines1471481491501511521 unmodified line15415515615715815932 unmodified linesfrom __future__ import annotationsimport loggingimport reimport secrets3 unmodified linesimport threadingimport timefrom abc import ABC, abstractmethodlogger = logging.getLogger(__name__)99 unmodified linesf"gradio is required for GradioForwarder: {exc}") from excdef start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str:from gradio.networking import setup_tunnelfrom gradio.tunneling import CURRENT_TUNNELS1 unmodified lineself.stop()share_token = secrets.token_hex(16)try:url = setup_tunnel(local_host=local_host,local_port=local_port,32 unmodified lines333435363738393 unmodified lines43444546474849505152535499 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781 unmodified line18018118218318418518632 unmodified linesfrom __future__ import annotationsimport importlibimport loggingimport reimport secrets3 unmodified linesimport threadingimport timefrom abc import ABC, abstractmethodfrom pathlib import Pathtry:import fcntlexcept ImportError: # Windows: no advisory locks, keep gradio's unlocked download.fcntl = Nonelogger = logging.getLogger(__name__)99 unmodified linesf"gradio is required for GradioForwarder: {exc}") from exc@staticmethoddef _ensure_frpc_binary() -> None:"""Download gradio's frpc binary once, under a cross-process lock.Gradio checks `Path(BINARY_PATH).exists()` and then writes the binary in place. A secondprocess that starts while the first is still writing sees the file, skips the download andexecutes a half-written binary, which fails with `Text file busy` (ETXTBSY) or a corruptexecutable. Holding an exclusive lock next to the binary makes every other process waituntil the first download has finished, after which gradio's own check skips the download."""tunneling = importlib.import_module("gradio.tunneling")binary = Path(tunneling.BINARY_PATH)binary.parent.mkdir(parents=True, exist_ok=True)with open(binary.with_name(binary.name + ".lock"), "a") as lock_file:if fcntl is not None:fcntl.flock(lock_file, fcntl.LOCK_EX)tunneling.Tunnel.download_binary()def start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str:from gradio.networking import setup_tunnelfrom gradio.tunneling import CURRENT_TUNNELS1 unmodified lineself.stop()share_token = secrets.token_hex(16)try:self._ensure_frpc_binary()url = setup_tunnel(local_host=local_host,local_port=local_port,
247 unmodified lines248249250251252253254255256247 unmodified linesself._nodes: dict[str, TurnNode] = {}self._order: list[str] = []self._children: dict[str, list[str]] = {}# --- construction --------------------------------------------------def add_turn(self, node: TurnNode) -> TurnNode:node.index = len(self._order)node.parent_id = self._find_parent(node)self._nodes[node.node_id] = node247 unmodified lines248249250251252253254255256257258259260261262263264265266267268269270271272247 unmodified linesself._nodes: dict[str, TurnNode] = {}self._order: list[str] = []self._children: dict[str, list[str]] = {}# Every request re-sends the whole history, so each turn decodes a fresh copy of every# earlier image and long text. Keep one copy per graph. Only immutable strings are shared;# message dicts and lists stay per turn.self._shared_text: dict[str, str] = {}def _share_text(self, value: Any) -> Any:if isinstance(value, str) and len(value) >= 1024:return self._shared_text.setdefault(value, value)if isinstance(value, list):return [self._share_text(item) for item in value]if isinstance(value, dict):return {key: self._share_text(item) for key, item in value.items()}return value# --- construction --------------------------------------------------def add_turn(self, node: TurnNode) -> TurnNode:node.request_messages = self._share_text(node.request_messages)node.request_tools = self._share_text(node.request_tools)node.response_message = self._share_text(node.response_message)node.index = len(self._order)node.parent_id = self._find_parent(node)self._nodes[node.node_id] = node
265 unmodified lines266267268269270271927 unmodified lines119912001201120212031204265 unmodified linesreturn replaceddef normalise_for_capture(chat_request: dict[str, Any]) -> None:"""Force the upstream call into the one shape that yields complete, capturable responses.927 unmodified linesfor key in SAMPLING_KEYS:chat_request.pop(key, None)chat_request.update(effective_sampling)normalise_response(response)_ingest(session,265 unmodified lines266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306927 unmodified lines12341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256265 unmodified linesreturn replaceddef context_window_ran_out(chat_request: dict[str, Any], response: dict[str, Any]) -> bool:"""Whether the engine cut the completion short because the context window was full.Older vLLM rejects a request whose prompt plus `max_tokens` exceeds the context window with a 400("maximum context length"), which the proxy turns into a budget stop. Newer vLLM (seen with 0.34)serves it and stops generating when the window is full instead: the completion ends with`finish_reason="length"` before reaching `max_tokens`. Forwarded as is, that truncated turn reachesthe harness, and pi answers it by compacting its context, in a summarisation call capture cannottie to the rest of the rollout: every such rollout fails validation with `turn_mismatch`. It is thesame event as the 400, so it ends the rollout the same way."""# The limit the engine applies, in its order: vLLM (like OpenAI) takes `max_completion_tokens` and# falls back to `max_tokens`. A harness that sends both with different values would otherwise turn# an output-cap stop into a context stop, or hide a real one.requested = next((chat_request[key]for key in ("max_completion_tokens", "max_tokens")if isinstance(chat_request.get(key), int)),None,)choices = response.get("choices") or []completion_tokens = (response.get("usage") or {}).get("completion_tokens")return (requested is not Noneand isinstance(completion_tokens, int)and bool(choices)and choices[0].get("finish_reason") == "length"and completion_tokens < requested)def normalise_for_capture(chat_request: dict[str, Any]) -> None:"""Force the upstream call into the one shape that yields complete, capturable responses.927 unmodified linesfor key in SAMPLING_KEYS:chat_request.pop(key, None)chat_request.update(effective_sampling)if context_window_ran_out(chat_request, response):# Like the 400 above: a stop the harness ends on, and the truncated turn is never ingestedsession.findings.append("[WARN] context_budget_exhausted: the engine stopped at the context window, ""before max_tokens")session.budget_stop_count += 1stop = _budget_stop_response(_model_of(session) or app.state.model)if client_wants_stream:return StreamingResponse(sse.replay(api_type, transformer, stop, original_request),media_type="text/event-stream",headers=sse.SSE_HEADERS,)payload = transformer.transform_response(stop, original_request)normalise_client_payload(payload, api_type)return JSONResponse(payload)normalise_response(response)_ingest(session,
43 unmodified lines444546474849505152535415 unmodified lines707172737475498 unmodified lines57457557657757857958022 unmodified lines60360460560660760821 unmodified lines63063163263363463563663763863964064164243 unmodified linesimport jsonimport osimport urllib.errorimport urllib.requestfrom dataclasses import dataclass, fieldfrom .compat import behaviour_warnings, diagnose, MAX_FIXESfrom .upstream import (auth_headers,normalise_engine_base,15 unmodified lines)@dataclassclass LLMReport:"""Outcome of the probe. `ok` means trainable; `reachable` means usable at all."""498 unmodified lines# or gate it behind different scopes than inference, and refusing there would reject an endpoint# that serves completions perfectly well. The completion probe below is the real test; a missing# list only costs us the model-name check.listed_model = model.rsplit(":", 1)[0] if provider == "hf" else modelif served and model not in served and listed_model not in served:# Worth failing on rather than warning: a mismatched name is silently accepted by some# servers and then every request 404s at rollout time instead of at startup.22 unmodified linesapplied: list = []payload: dict | None = Nonefailure = ""# Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the# capture params are the ones most likely to go, and losing them is what decides the level.21 unmodified linesfix = diagnose(json.loads(detail))except json.JSONDecodeError:fix = diagnose(detail)if fix is None or not fix.apply(body):failure = f"probe failed: HTTP {exc.code}: {detail[:300]}"breakfixes.append(str(fix))applied.append(fix)except Exception as exc: # noqa: BLE001failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}"breakif payload is None:43 unmodified lines4445464748495051525354555615 unmodified lines72737475767778798081828384858687888990919293949596498 unmodified lines59559659759859960060160260360422 unmodified lines62762862963063163263321 unmodified lines65565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369443 unmodified linesimport jsonimport osimport timeimport urllib.errorimport urllib.requestfrom dataclasses import dataclass, fieldfrom urllib.parse import urlsplitfrom .compat import behaviour_warnings, diagnose, MAX_FIXES, ParamFixfrom .upstream import (auth_headers,normalise_engine_base,15 unmodified lines)# How many times the probe repeats the SAME request after an error that names nothing it can fix.# Hosted routers occasionally answer a valid request with a 400 or 5xx that a resend clears: observed# as one task in ~150 aborting before it ran, against an endpoint that served the other 149.PROBE_RETRIES = 2PROBE_RETRY_DELAY = 1.0# Errors no resend or rewrite can fix: bad credentials, no access, no such route or model. Retrying# these only delays a message the user needs now._FATAL_HTTP = frozenset({401, 403, 404})# Statuses with which a provider rejects a request it doesn't accept, e.g. unsupported capture params._PARAM_REJECTION_HTTP = frozenset({400, 422})# What the eval fallback drops. `logprobs` also takes `top_logprobs` with it (see `ParamFix.apply`)._CAPTURE_PARAMS = ("return_token_ids", "logprobs")def _is_timeout(exc: BaseException) -> bool:reason = getattr(exc, "reason", None)return isinstance(exc, TimeoutError) or isinstance(reason, TimeoutError)@dataclassclass LLMReport:"""Outcome of the probe. `ok` means trainable; `reachable` means usable at all."""498 unmodified lines# or gate it behind different scopes than inference, and refusing there would reject an endpoint# that serves completions perfectly well. The completion probe below is the real test; a missing# list only costs us the model-name check.# The HF router lists bare ids but routes `<id>:<provider>` (also `:fastest`, `:cheapest`). The# CLI reaches it with the default provider, so recognise the router by its host as well.hf_router = urlsplit(base).hostname == "router.huggingface.co"listed_model = model.rsplit(":", 1)[0] if provider == "hf" or hf_router else modelif served and model not in served and listed_model not in served:# Worth failing on rather than warning: a mismatched name is silently accepted by some# servers and then every request 404s at rollout time instead of at startup.22 unmodified linesapplied: list = []payload: dict | None = Nonefailure = ""retries_left = PROBE_RETRIES# Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the# capture params are the ones most likely to go, and losing them is what decides the level.21 unmodified linesfix = diagnose(json.loads(detail))except json.JSONDecodeError:fix = diagnose(detail)if fix is not None and fix.apply(body):fixes.append(str(fix))applied.append(fix)continuefailure = f"probe failed: HTTP {exc.code}: {detail[:300]}"if exc.code in _FATAL_HTTP:break# An error that names no parameter is first treated as transient: the same request again.if retries_left:retries_left -= 1time.sleep(PROBE_RETRY_DELAY)continue# Still failing. Some providers reject the capture params with a bare 400 that names# nothing, so ask once more without them. If that answers, the endpoint is an eval# backend (the level is graded from what comes back), which is what `ENGINE_HINT`# promises. A `purpose="train"` rollout still refuses it, since the level is not `tokens`.# Only a request error can be about the params: a 5xx or a 429 that outlasts the retries# is reported, rather than grading a busy token-capable engine as `text`.if exc.code not in _PARAM_REJECTION_HTTP:breakdropped = [ParamFix(param=p) for p in _CAPTURE_PARAMS]dropped = [f for f in dropped if f.apply(body)]if not dropped:breakfor f in dropped:fixes.append(f"{f} (eval fallback after HTTP {exc.code})")applied.append(f)except Exception as exc: # noqa: BLE001failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}"# A timeout is worth repeating. Anything else here (connection refused, DNS) is not.if _is_timeout(exc) and retries_left:retries_left -= 1time.sleep(PROBE_RETRY_DELAY)continuebreakif payload is None:
22 unmodified lines23242526272829303132204 unmodified lines2372382392402412422432442458 unmodified lines2542552562572582592602612622632642652662672682692703 unmodified lines27427527627727827932 unmodified lines312313314315316317318194 unmodified lines51351451551651751851974 unmodified lines59459559659759859922 unmodified linesfrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, BinaryIO, Callable, Iterable, Iteratorfrom ..env_server.mcp_types import Toolfrom ..llm_client import LLMClientfrom .rollout import (_resolve_env_reward,HarnessAdapter,204 unmodified linesclass CollectRunner:"""Drive repeated rollouts into an append-only JSONL dataset.The runner is stateless across ``run()`` calls — resume state lives ondisk via the ``RolloutSerializer``. A single runner instance can bereused across runs targeting different output dirs."""def __init__(8 unmodified linesself._session_factory = session_factoryself._harness_adapter = harness_adapterself._serializer = serializerself._tasks: Iterator[Any] | None = iter(tasks) if tasks is not None else Noneself._limits = limitsdef _next_task(self) -> Any:if self._tasks is None:return Nonetry:return next(self._tasks)except StopIteration:return Nonedef run(self,*,3 unmodified linesresume: bool = True,should_keep: Callable[[EpisodeRecord], bool] | None = None,) -> CollectResult:planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)]if resume:32 unmodified lineswith progress:for episode_id in planned_ids:# Preserve task-to-episode alignment even when resume skips ids.task = self._next_task()if episode_id in already:num_skipped += 1progress.advance(task_id)194 unmodified lines"","# OpenEnv rollouts","","Collected with [OpenEnv](https://github.com/huggingface/OpenEnv) ""(`openenv collect`).","",f"- **Episodes:** {_count_episodes(results_path)}",74 unmodified linesreadme_path = output_dir / README_FILENAMEreadme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8")num_episodes = _count_episodes(results_path)message = commit_message or f"Add {num_episodes} collected episode(s)"22 unmodified lines2324252627282930313233204 unmodified lines2382392402412422432442452462478 unmodified lines2562572582592602612622632642653 unmodified lines26927027127227327427527627727827928028128228328432 unmodified lines317318319320321322323324194 unmodified lines51952052152252352452574 unmodified lines60060160260360460560660760860961061161261361461561661761822 unmodified linesfrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, BinaryIO, Callable, Iterablefrom ..env_server.mcp_types import Toolfrom ..llm_client import LLMClientfrom ..utils import redact_secretsfrom .rollout import (_resolve_env_reward,HarnessAdapter,204 unmodified linesclass CollectRunner:"""Drive repeated rollouts into an append-only JSONL dataset.Resume state lives on disk via the ``RolloutSerializer``. Repeatable taskiterables, such as lists and tuples, restart at the first task on each``run()`` so tasks stay aligned with episode ids. One-shot iterators workfor one run; reusing them raises ``ValueError`` before accessing results."""def __init__(8 unmodified linesself._session_factory = session_factoryself._harness_adapter = harness_adapterself._serializer = serializerself._tasks = tasksself._tasks_used = Falseself._limits = limitsdef run(self,*,3 unmodified linesresume: bool = True,should_keep: Callable[[EpisodeRecord], bool] | None = None,) -> CollectResult:task_iterator = iter(self._tasks) if self._tasks is not None else Noneif (task_iterator is not Noneand task_iterator is self._tasksand self._tasks_used):raise ValueError("Cannot reuse a one-shot task iterator; pass a repeatable iterable ""or create a new CollectRunner with a fresh iterator.")planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)]if resume:32 unmodified lineswith progress:for episode_id in planned_ids:# Preserve task-to-episode alignment even when resume skips ids.self._tasks_used = Truetask = next(task_iterator, None) if task_iterator is not None else Noneif episode_id in already:num_skipped += 1progress.advance(task_id)194 unmodified lines"","# OpenEnv rollouts","","Collected with [OpenEnv](https://github.com/openenv/OpenEnv) ""(`openenv collect`).","",f"- **Episodes:** {_count_episodes(results_path)}",74 unmodified linesreadme_path = output_dir / README_FILENAMEreadme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8")# Episodes hold what the agent saw and printed, which can include credentials.redacted = 0for path in output_dir.iterdir():if path.suffix in {".jsonl", ".json", ".md"}:text, count = redact_secrets(path.read_text(encoding="utf-8"))if count:path.write_text(text, encoding="utf-8")redacted += countif redacted:warnings.warn(f"Redacted {redacted} secret(s) from {output_dir} before the upload")num_episodes = _count_episodes(results_path)message = commit_message or f"Add {num_episodes} collected episode(s)"
254 unmodified lines255256257258259260254 unmodified linesreturn await super()._connect_async()async def _ensure_production_session(self) -> str:"""Create and cache a persistent HTTP MCP session id if needed."""async with self._production_session_lock:254 unmodified lines255256257258259260261262263264265266254 unmodified linesreturn await super()._connect_async()def _raise_if_session_lost(self) -> None:# In production mode a reconnect attaches to the same HTTP MCP session,# which outlives the WebSocket, so the episode carries over.if not getattr(self, "use_production_mode", False):super()._raise_if_session_lost()async def _ensure_production_session(self) -> str:"""Create and cache a persistent HTTP MCP session id if needed."""async with self._production_session_lock:
88 unmodified lines89909192939495969788 unmodified linesArgs:name: Environment name or HuggingFace Hub repo IDExamples:- "coding" / "coding-env" / "coding_env"- "openenv/coding_env" (Hub repo ID)- "https://huggingface.co/openenv/coding_env" (Hub URL)skip_install: If True, skip package installation and returnGenericAction class instead. Use this when working withGenericEnvClient to avoid installing remote packages.88 unmodified lines89909192939495969788 unmodified linesArgs:name: Environment name or HuggingFace Hub repo IDExamples:- `"coding"` / `"coding-env"` / `"coding_env"`- `"openenv/coding_env"` (Hub repo ID)- `"https://huggingface.co/openenv/coding_env"` (Hub URL)skip_install: If True, skip package installation and returnGenericAction class instead. Use this when working withGenericEnvClient to avoid installing remote packages.
517 unmodified lines518519520521522523524525526517 unmodified linesArgs:name: Environment name or HuggingFace Hub repo IDExamples:- "coding" / "coding-env" / "coding_env"- "openenv/coding_env" (Hub repo ID)- "https://huggingface.co/openenv/coding_env" (Hub URL)base_url: Optional base URL for HTTP connectiondocker_image: Optional Docker image name (overrides default)container_provider: Optional container provider517 unmodified lines518519520521522523524525526517 unmodified linesArgs:name: Environment name or HuggingFace Hub repo IDExamples:- `"coding"` / `"coding-env"` / `"coding_env"`- `"openenv/coding_env"` (Hub repo ID)- `"https://huggingface.co/openenv/coding_env"` (Hub URL)base_url: Optional base URL for HTTP connectiondocker_image: Optional Docker image name (overrides default)container_provider: Optional container provider
50 unmodified lines51525354555657585950 unmodified linesname="push",help="Push an OpenEnv environment to Hugging Face Spaces or custom registry",)(push.push)app.command(name="serve", help="Serve environments locally (TODO: Phase 4)")(serve.serve)app.command(name="fork",help="Fork (duplicate) a Hugging Face Space to your account",50 unmodified lines5152535455565758596050 unmodified linesname="push",help="Push an OpenEnv environment to Hugging Face Spaces or custom registry",)(push.push)app.command(name="serve",help="Run an environment on the host for local development (no container isolation)",)(serve.serve)app.command(name="fork",help="Fork (duplicate) a Hugging Face Space to your account",
13 unmodified lines14151617181976 unmodified lines9697989910010110210310410510610710810911011111211311411511611711811912012134 unmodified lines15615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920013 unmodified linesimport typerfrom .._cli_utils import consoleapp = typer.Typer(help="Build Docker images for OpenEnv environments")76 unmodified linespyproject_path = build_dir / "pyproject.toml"if pyproject_path.exists():with open(pyproject_path, "rb") as f:try:import tomlipyproject = tomli.load(f)deps = pyproject.get("project", {}).get("dependencies", [])# Check if openenv dependency is declaredhas_openenv = any(dep.startswith("openenv") for dep in deps)if not has_openenv:console.print("[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency",)console.print("[yellow]You may need to add:[/yellow] openenv>=0.2.0",)except ImportError:console.print("[yellow]Warning:[/yellow] tomli not available, skipping dependency check",)return build_dir34 unmodified linespyproject_path = build_dir / "pyproject.toml"if pyproject_path.exists():with open(pyproject_path, "rb") as f:try:import tomlipyproject = tomli.load(f)deps = pyproject.get("project", {}).get("dependencies", [])# Replace OpenEnv package references with local source.new_deps = []for dep in deps:if _is_openenv_runtime_dependency(dep):# Skip - we'll use local corecontinuenew_deps.append(dep)# Write back with local OpenEnv referencepyproject["project"]["dependencies"] = new_deps + ["openenv @ file:///app/env/openenv"]# Write updated pyproject.tomlwith open(pyproject_path, "wb") as out_f:import tomli_wtomli_w.dump(pyproject, out_f)console.print("[cyan]Updated pyproject.toml to use local core[/cyan]")# Remove old lockfile since dependencies changedlockfile = build_dir / "uv.lock"if lockfile.exists():lockfile.unlink()console.print("[cyan]Removed outdated uv.lock[/cyan]")except ImportError:console.print("[yellow]Warning:[/yellow] tomli/tomli_w not available, using pyproject.toml as-is",)else:console.print("[yellow]Warning:[/yellow] OpenEnv package not found, building without it"13 unmodified lines141516171819202122232476 unmodified lines10110210310410510610710810911011111211334 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117217317413 unmodified linesimport typertry:import tomllibexcept ModuleNotFoundError:import tomli as tomllibfrom .._cli_utils import consoleapp = typer.Typer(help="Build Docker images for OpenEnv environments")76 unmodified linespyproject_path = build_dir / "pyproject.toml"if pyproject_path.exists():with open(pyproject_path, "rb") as f:pyproject = tomllib.load(f)deps = pyproject.get("project", {}).get("dependencies", [])if not any(dep.startswith("openenv") for dep in deps):console.print("[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency",)console.print("[yellow]You may need to add:[/yellow] openenv>=0.2.0")return build_dir34 unmodified linespyproject_path = build_dir / "pyproject.toml"if pyproject_path.exists():with open(pyproject_path, "rb") as f:pyproject = tomllib.load(f)deps = pyproject.get("project", {}).get("dependencies", [])pyproject["project"]["dependencies"] = [dep for dep in deps if not _is_openenv_runtime_dependency(dep)] + ["openenv @ file:///app/env/openenv"]try:import tomli_wexcept ImportError:console.print("[yellow]Warning:[/yellow] tomli_w not available, using pyproject.toml as-is",)else:with open(pyproject_path, "wb") as out_f:tomli_w.dump(pyproject, out_f)console.print("[cyan]Updated pyproject.toml to use local core[/cyan]")lockfile = build_dir / "uv.lock"if lockfile.exists():lockfile.unlink()console.print("[cyan]Removed outdated uv.lock[/cyan]")else:console.print("[yellow]Warning:[/yellow] OpenEnv package not found, building without it"
123456789177 unmodified lines18718818919019119214 unmodified lines20720820921021121215 unmodified lines22822923023123223323423523623723833 unmodified lines27227327427527627727848 unmodified lines32732832933033133262 unmodified lines39539639739839940017 unmodified lines418419420421422423"""`openenv harbor` — run Harbor tasks with token-level capture.Four commands, in the order you would use them:openenv harbor info what can this machine run right now?openenv harbor rollout --task-index 0 one rollout, end to end, no serveropenenv harbor serve the env server, for trainers and clientsopenenv harbor push the same server, deployed to a Space177 unmodified linesreturn getattr(response, "status_code", None) == 404@app.command("info")def info(llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP_OPTIONAL)] = "",14 unmodified linesenv_file: Annotated[str, typer.Option("--env-file", help="dotenv file with provider credentials.")] = "",verbose: Annotated[bool,typer.Option("--verbose", help="List every harness, not only validated ones."),15 unmodified linesapi_key=api_key or None,auth_header=auth_header,)print(json.dumps(caps.to_dict(), indent=2)if json_outputelse caps.render(verbose=verbose))@app.command("rollout")33 unmodified lines] = "",reward_key: Annotated[str,typer.Option("--reward-key", help="Which reward key is the training signal."),] = "",keep_sandbox: Annotated[bool,48 unmodified linesraise typer.Exit(0 if all(r.ok for r in results) else 1)@app.command("serve")def serve(llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)] = "",62 unmodified linesreward_key: Annotated[str, typer.Option("--reward-key", help=_REWARD_KEY_HELP)] = "",) -> None:"""Serve Harbor tasks over the OpenEnv Task API and MCP.17 unmodified lines)# The UI's laptop defaults (this machine's token, private URLs) are for a loopback-only server.os.environ["OPENENV_HARBOR_UI_HOST"] = hostserve_harbor(llm_url=llm_url,model=model or None,12345678910177 unmodified lines18818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823914 unmodified lines25425525625725825926026126226326426526626715 unmodified lines28328428528628728828929029129229329429529629729829930030130230330430533 unmodified lines33934034134234334434534634734834948 unmodified lines39839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750862 unmodified lines57157257357457557657757857958058158258358458558617 unmodified lines604605606607608609610611"""`openenv harbor` — run Harbor tasks with token-level capture.Five commands, in the order you would use them:openenv harbor info what can this machine run right now?openenv harbor rollout --task-index 0 one rollout, end to end, no serveropenenv harbor export-sft results/ rollouts as SFT rows (messages + tools)openenv harbor serve the env server, for trainers and clientsopenenv harbor push the same server, deployed to a Space177 unmodified linesreturn getattr(response, "status_code", None) == 404def _check_harness(harness: str, model: str) -> dict[str, Any]:"""Construct the rollout's agent with dummy capture credentials, without setup or run."""import ioresult: dict[str, Any] = {"name": harness, "ok": False}try:# Imports, constructors and the process-env warning may print. Keep --json readable.with (contextlib.redirect_stdout(io.StringIO()),tempfile.TemporaryDirectory() as tmp,):from harbor.agents.factory import AgentFactoryfrom openenv.harbor import seamsfrom openenv.harbor.rollout import build_trial_config, process_envseam = seams.get(harness)url, session = "http://127.0.0.1:9", "openenv-harness-preflight"*_, proc_env = seam.resolve(base_url=url, session=session, model=model)config = build_trial_config(task_dir=tmp,harness=harness,sandbox="docker",intercept_url=url,session_id=session,model=model,trial_name="preflight",trials_dir=tmp,)with process_env(harness, proc_env):AgentFactory.create_agent_from_config(config.agent, logs_dir=Path(tmp))result.update(ok=True,import_path=seam.import_path,dialect=seam.dialect,host_side=seam.host_side,status=seam.status,model=config.agent.model_name,kwargs=config.agent.kwargs,agent_env=config.agent.env,process_env=proc_env,)except (Exception, SystemExit) as exc: # noqa: BLE001 - a failed check is report dataresult["detail"] = f"{type(exc).__name__}: {exc}"return result@app.command("info")def info(llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP_OPTIONAL)] = "",14 unmodified linesenv_file: Annotated[str, typer.Option("--env-file", help="dotenv file with provider credentials.")] = "",harness: Annotated[str,typer.Option("--harness",help="Check a seam name or trusted `module:Class` by constructing it with dummy ""capture credentials. Runs no agent or sandbox.",),] = "",verbose: Annotated[bool,typer.Option("--verbose", help="List every harness, not only validated ones."),15 unmodified linesapi_key=api_key or None,auth_header=auth_header,)checked = (_check_harness(harness, model or caps.llm.get("model") or "preflight-model")if harnesselse None)if json_output:data = caps.to_dict()if checked is not None:data["harness"] = checkedprint(json.dumps(data, indent=2))else:print(caps.render(verbose=verbose))if checked is not None:print("\nharness preflight (construction only; capture is untested)")print(json.dumps(checked, indent=2))if checked is not None and not checked["ok"]:raise typer.Exit(1)@app.command("rollout")33 unmodified lines] = "",reward_key: Annotated[str,typer.Option("--reward-key",help="Which reward key is the headline one, or a comma-separated preference ""order (e.g. `correctness,reward`) for a dataset whose tasks write different keys.",),] = "",keep_sandbox: Annotated[bool,48 unmodified linesraise typer.Exit(0 if all(r.ok for r in results) else 1)def _read_results(paths: list[str]) -> list[dict[str, Any]]:"""Rollouts from `rollout --out` files, or from every `*.json` in a directory."""files: list[Path] = []for spec in paths:path = Path(spec)if not path.exists():raise typer.BadParameter(f"{spec} does not exist")files.extend(sorted(path.glob("*.json")) if path.is_dir() else [path])results: list[dict[str, Any]] = []for file in files:data = json.loads(file.read_text())items = data if isinstance(data, list) else [data]# a directory can hold other JSON (a run summary): keep what looks like a rolloutresults.extend(i for i in items if isinstance(i, dict) and "turns" in i)return results@app.command("export-sft")def export_sft_command(results: Annotated[list[str],typer.Argument(help="Result JSONs written by `rollout --out`, or directories of them."),],out: Annotated[str, typer.Option("--out", help="JSON Lines file for the SFT rows.")] = "sft_rows.jsonl",min_reward: Annotated[Optional[float],typer.Option("--min-reward",help="Keep only rollouts graded at least this, e.g. 1.0 for solved tasks. Unset, every rollout is kept with its reward.",),] = None,reward_key: Annotated[str,typer.Option("--reward-key",help="Reward to read when the verifier reported several and none was picked at rollout time. A comma-separated list is a preference order, e.g. correctness,reward.",),] = "",push_to: Annotated[str,typer.Option("--push-to", help="Hub dataset repo to upload the rows to."),] = "",private: Annotated[Optional[bool],typer.Option("--private",help="Create --push-to as a private dataset. Unset, the namespace's default visibility applies.",),] = None,) -> None:"""Turn rollouts into conversational SFT rows (`messages` + `tools`), one per rollout.Works on evaluation rollouts against a hosted model: SFT needs the conversation, not token ids. To train on therows, type `messages` and `tools` with the `Json` feature of `datasets`: a schema inferred from the rows givesevery tool call the argument names of every other tool, as `None`."""from openenv.core.utils import redact_secretsfrom openenv.harbor.sft import export_sftrows, stats = export_sft(_read_results(results), min_reward=min_reward, reward_key=reward_key)# Rows hold what the agent saw and printed, which can include credentials.text, redacted = redact_secrets("".join(json.dumps(row) + "\n" for row in rows))path = Path(out)path.write_text(text)print(f"{stats.rows} rows from {stats.rollouts} rollouts -> {path}")if redacted:print(f" redacted {redacted} secret(s)")if stats.below_min_reward or stats.ungraded:print(f" dropped: {stats.below_min_reward} below --min-reward, {stats.ungraded} ungraded")skipped = {"had no agent turn": stats.no_agent_turn,"had an unusable capture": stats.capture_failed,"ended on an empty reply": stats.empty_reply,"held a tool call whose arguments aren't a JSON object": stats.malformed_tool_call,}for reason, count in skipped.items():if count:print(f" {count} rollouts {reason}, skipped")if stats.ended_on_tool_call:print(f" {len(stats.ended_on_tool_call)} rollouts ended right after a tool call, usually a failed model call"f" worth rerunning: {', '.join(stats.ended_on_tool_call)}")if push_to:from huggingface_hub import HfApiapi = HfApi()api.create_repo(push_to, repo_type="dataset", private=private, exist_ok=True)api.upload_file(path_or_fileobj=path,path_in_repo=f"data/{path.name}",repo_id=push_to,repo_type="dataset",)print(f"pushed to https://huggingface.co/datasets/{push_to}")@app.command("serve")def serve(llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)] = "",62 unmodified linesreward_key: Annotated[str, typer.Option("--reward-key", help=_REWARD_KEY_HELP)] = "",allow_harness: Annotated[Optional[list[str]],typer.Option("--allow-harness",help=("Accept this `module:Class` harness in clients' rollouts. Naming a class imports ""its module on this server, so other import paths are refused. Repeatable."),),] = None,) -> None:"""Serve Harbor tasks over the OpenEnv Task API and MCP.17 unmodified lines)# The UI's laptop defaults (this machine's token, private URLs) are for a loopback-only server.os.environ["OPENENV_HARBOR_UI_HOST"] = hostif allow_harness:os.environ["OPENENV_HARBOR_ALLOW_HARNESS"] = ",".join(allow_harness)serve_harbor(llm_url=llm_url,model=model or None,
4 unmodified lines567891011395 unmodified lines407408409410411412413414415416417418419420261 unmodified lines6826836846856866876884 unmodified linesfrom __future__ import annotationsimport shutilimport sysimport tempfilefrom fnmatch import fnmatchfrom pathlib import Path395 unmodified lines# Add base_path to existing frontmatterlines = readme_content.split("\n")new_lines = []_in_frontmatter = Truefor i, line in enumerate(lines):new_lines.append(line)if line.strip() == "---" and i > 0:# End of frontmatter, add base_path before this lineif "base_path:" not in "\n".join(new_lines):new_lines.insert(-1, "base_path: /web")_in_frontmatter = Falsereadme_path.write_text("\n".join(new_lines))else:# No frontmatter, add it261 unmodified linesif no_interface and interface:console.print("[bold red]Error:[/bold red] Cannot specify both --interface and --no-interface",file=sys.stderr,)raise typer.Exit(1)4 unmodified lines5678910395 unmodified lines406407408409410411412413414415416417418419261 unmodified lines6816826836846856864 unmodified linesfrom __future__ import annotationsimport shutilimport tempfilefrom fnmatch import fnmatchfrom pathlib import Path395 unmodified lines# Add base_path to existing frontmatterlines = readme_content.split("\n")new_lines = []for i, line in enumerate(lines):new_lines.append(line)if line.strip() == "---" and i > 0:# End of frontmatter, add base_path before this lineif "base_path:" not in "\n".join(new_lines):new_lines.insert(-1, "base_path: /web")new_lines.extend(lines[i + 1 :])breakreadme_path.write_text("\n".join(new_lines))else:# No frontmatter, add it261 unmodified linesif no_interface and interface:console.print("[bold red]Error:[/bold red] Cannot specify both --interface and --no-interface",)raise typer.Exit(1)
12345678910111213141516171819202 unmodified lines2324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# SPDX-License-Identifier: BSD-3-Clause"""Serve OpenEnv environments locally (TO BE IMPLEMENTED)."""from __future__ import annotationsfrom pathlib import Pathfrom typing import Annotatedimport typerfrom .._cli_utils import consoleapp = typer.Typer(help="Serve OpenEnv environments locally")@app.command()def serve(env_path: Annotated[str | None,2 unmodified lines),] = None,port: Annotated[int,typer.Option("--port", "-p", help="Port to serve on"),] = 8000,host: Annotated[str,typer.Option("--host", help="Host to bind to"),] = "0.0.0.0",reload: Annotated[bool,typer.Option("--reload", help="Enable auto-reload on code changes"),] = False,) -> None:"""Serve an OpenEnv environment locally.TODO: This command is currently not implemented and has been deferred for later.Planned functionality:- Run environment server locally without Docker- Support multiple deployment modes (local, notebook, cluster)- Auto-reload for development- Integration with environment's [project.scripts] entry pointFor now, use Docker-based serving:1. Build the environment: openenv build2. Run the container: docker run -p 8000:8000 <image-name>Or use uv directly:uv run --project . server --port 8000"""console.print("[bold yellow]⚠ This command is not yet implemented[/bold yellow]\n")console.print("The [bold cyan]openenv serve[/bold cyan] command has been deferred for later.")console.print("[bold]Alternative approaches:[/bold]\n")console.print("[cyan]Option 1: Docker-based serving (recommended)[/cyan]")console.print(" 1. Build the environment:")console.print(" [dim]$ openenv build[/dim]")console.print(" 2. Run the Docker container:")console.print(f" [dim]$ docker run -p {port}:{port} openenv-<env-name>:latest[/dim]\n")console.print("[cyan]Option 2: Direct execution with uv[/cyan]")# Determine environment pathif env_path is None:env_path_obj = Path.cwd()else:env_path_obj = Path(env_path)# Check for openenv.yamlopenenv_yaml = env_path_obj / "openenv.yaml"if openenv_yaml.exists():console.print(" From your environment directory:")console.print(f" [dim]$ cd {env_path_obj}[/dim]")console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n")else:console.print(" From an environment directory with pyproject.toml:")console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n")raise typer.Exit(1)12345678910111213141516171819202 unmodified lines2324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155# SPDX-License-Identifier: BSD-3-Clause"""Serve an OpenEnv environment locally (uvicorn, from ``openenv.yaml``)."""from __future__ import annotationsimport osimport sysfrom pathlib import Pathfrom typing import Annotatedimport typerimport yamlfrom .._cli_utils import console, validate_env_structuredef serve(env_path: Annotated[str | None,2 unmodified lines),] = None,port: Annotated[int | None,typer.Option("--port","-p",help="Port to bind (default: ``port`` in openenv.yaml, else 8000)",),] = None,host: Annotated[str,typer.Option("--host", help="Host interface to bind (local development only)"),] = "127.0.0.1",reload: Annotated[bool,typer.Option("--reload", help="Enable autoreload (development)"),] = False,) -> None:"""Run the environment FastAPI app on the host for local development.Uses ``openenv.yaml`` fields ``app`` (e.g. ``server.app:app``), ``port``, and``runtime`` (must be ``fastapi``). Matches ``uv run --project . server`` layout:the environment directory is the working directory. Package-qualified apppaths also support the environment package and the repo's ``envs`` package.For production or training, use Docker (``openenv build``) — this command runson the host for local development only."""import uvicornenv_path_obj = (Path.cwd().resolve() if env_path is None else Path(env_path).resolve())if not env_path_obj.exists():typer.echo(f"Error: Path does not exist: {env_path_obj}", err=True)raise typer.Exit(1)if not env_path_obj.is_dir():typer.echo(f"Error: Path is not a directory: {env_path_obj}", err=True)raise typer.Exit(1)try:validate_env_structure(env_path_obj)except FileNotFoundError as exc:raise typer.BadParameter(f"Not a valid OpenEnv environment: {exc}") from excmanifest_path = env_path_obj / "openenv.yaml"try:with manifest_path.open("r", encoding="utf-8") as handle:manifest = yaml.safe_load(handle)except OSError as exc:raise typer.BadParameter(f"Failed to read openenv.yaml: {exc}") from excexcept yaml.YAMLError as exc:raise typer.BadParameter(f"Invalid YAML in openenv.yaml: {exc}") from excif not isinstance(manifest, dict):raise typer.BadParameter("openenv.yaml must be a YAML dictionary")app_spec = manifest.get("app")if not app_spec or not isinstance(app_spec, str):raise typer.BadParameter("openenv.yaml must contain a string 'app' field (e.g. server.app:app)")if ":" not in app_spec:raise typer.BadParameter(f"openenv.yaml 'app' must look like 'module.path:attribute', got {app_spec!r}")runtime = str(manifest.get("runtime", "fastapi")).lower()if runtime != "fastapi":raise typer.BadParameter(f"openenv serve only supports runtime 'fastapi' (got {runtime!r})")raw_port = port if port is not None else manifest.get("port", 8000)try:listen_port = int(raw_port)except (TypeError, ValueError) as exc:raise typer.BadParameter(f"Invalid port {raw_port!r}; expected an integer") from excif not (1 <= listen_port <= 65535):raise typer.BadParameter(f"Invalid port {listen_port}; expected a value between 1 and 65535")original_path = list(sys.path)prev_cwd = os.getcwd()env_root = str(env_path_obj)app_dir = env_path_objmodule_name = app_spec.split(":", 1)[0]# Prefer a module inside the environment, even when its package name matches# the environment directory (for example, /work/server/server/app.py).local_module = env_path_obj.joinpath(*module_name.split("."))if not (local_module.with_suffix(".py").is_file()or (local_module / "__init__.py").is_file()):if env_path_obj.parent.name == "envs" and module_name.startswith(f"envs.{env_path_obj.name}."):app_dir = env_path_obj.parent.parentelif module_name.startswith(f"{env_path_obj.name}."):app_dir = env_path_obj.parenttry:os.chdir(env_root)console.print(f"[bold green]Serving[/bold green] [cyan]{app_spec}[/cyan] on "f"[bold]http://{host}:{listen_port}/[/bold] (cwd: {env_root})")try:uvicorn.run(app_spec,host=host,port=listen_port,reload=reload,app_dir=str(app_dir),)except OSError as exc:typer.echo(f"Error: {exc}", err=True)raise typer.Exit(1) from excfinally:try:os.chdir(prev_cwd)except OSError:passsys.path[:] = original_path
37 unmodified lines3839404142434437 unmodified linesUse `openenv <command> --help` for full flag reference.Full CLI reference: https://huggingface.co/docs/openenv/reference/cli"""CENTRAL_LOCAL = Path(".agents/skills")37 unmodified lines3839404142434437 unmodified linesUse `openenv <command> --help` for full flag reference.Full CLI reference: https://openenv.github.io/OpenEnv/main/reference/cli"""CENTRAL_LOCAL = Path(".agents/skills")
2 unmodified lines3456789101118 unmodified lines303132333435132 unmodified lines16816917017117217317417517617717817918018118211 unmodified lines19419519619719819920020147 unmodified lines2492502512522532542552562572582592602612622632642652662672682692702 unmodified lines"""OpenEnv validate command."""import jsonimport signalimport threadingfrom contextlib import contextmanagerfrom pathlib import Pathfrom typing import Annotated, Any18 unmodified linesEXIT_INTERNAL = 3@contextmanagerdef _sigterm_as_interrupt():"""Treat SIGTERM like Ctrl-C so the runner cleans up its subject."""132 unmodified linesmin=0.1,),] = 5.0,) -> None:"""Validate a local package or a running OpenEnv server.Local validation detects the package format by its well-known file (theformats this build can parse; currently `openenv.yaml`), parses it into thenormalized manifest, runs the applicable graders up to the requested level,applies the severity policy, and emits a report.Exit codes: 0 pass/warn · 1 fail · 2 unrecognized/unsupported package · 3internal or policy error.11 unmodified lines# Probe a running server (legacy runtime probe)openenv validate --url http://localhost:8000```"""runtime_target = urlif (runtime_target is not None47 unmodified linesraise typer.Exit(EXIT_INTERNAL)package_root = Path(target) if target is not None else Path.cwd()if not package_root.is_dir():typer.echo(f"Error: not a package directory: {package_root}", err=True)raise typer.Exit(EXIT_UNSUPPORTED)try:if output is not None and not output.parent.is_dir():raise OSError("report output directory does not exist")with _sigterm_as_interrupt():validation_report = run_validation(package_root,max_level=_LEVELS[level],skip_build=skip_build,policy=load_policy(policy_version) if policy_version else None,artifacts_dir=(output.parent / (output.stem + ".artifacts") if output else None),)report_json = write_report(validation_report, output)except (SignatureError, UnsupportedPackageError) as exc:2 unmodified lines345678910111213141518 unmodified lines343536373839404142434445464748495051525354555657585960616263646566676869707172132 unmodified lines20520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626711 unmodified lines27928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032147 unmodified lines3693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194202 unmodified lines"""OpenEnv validate command."""import jsonimport shutilimport signalimport tempfileimport threadingfrom contextlib import contextmanager, ExitStackfrom dataclasses import dataclassfrom functools import cached_propertyfrom pathlib import Pathfrom typing import Annotated, Any18 unmodified linesEXIT_INTERNAL = 3@dataclassclass _LazyHFSandboxProvider:"""Defer Jobs hardware preflight until the runner needs runtime capabilities."""name = "hf-sandbox"space_id: strrevision: strflavor: str@cached_propertydef _provider(self):from openenv.validation.providers.hf_sandbox import HFSandboxValidationProviderreturn HFSandboxValidationProvider(self.space_id, self.revision, flavor=self.flavor)@propertydef supported_network_modes(self):return self._provider.supported_network_modes@propertydef capabilities(self):return self._provider.capabilitiesdef build(self, root, execution):return self._provider.build(root, execution)def start(self, spec):return self._provider.start(spec)@contextmanagerdef _sigterm_as_interrupt():"""Treat SIGTERM like Ctrl-C so the runner cleans up its subject."""132 unmodified linesmin=0.1,),] = 5.0,space: Annotated[str | None,typer.Option("--space",help="Validate a Hugging Face Space (e.g. openenv/echo_env) on HF Jobs",),] = None,revision: Annotated[str | None,typer.Option("--revision",help="Space branch, tag or commit hash to validate (default: main)",),] = None,flavor: Annotated[str,typer.Option("--flavor",help=("HF Jobs hardware flavor for --space or --sandbox hf-sandbox, ""e.g. cpu-basic or t4-small"),),] = "cpu-basic",sandbox: Annotated[str,typer.Option("--sandbox",help=("Where Harbor task trials run: docker (local daemon) or ""hf-sandbox (one HF Job per trial)"),),] = "docker",namespace: Annotated[str | None,typer.Option("--namespace",help="User or organization that owns the --sandbox hf-sandbox jobs",),] = None,) -> None:"""Validate a local package or a running OpenEnv server.Local validation detects the package format by its well-known file (theformats this build can parse: `openenv.yaml` or Harbor `task.toml`), parses it into thenormalized manifest, runs the applicable graders up to the requested level,applies the severity policy, and emits a report.Native Harbor tasks require the optional Harbor dependency and an explicit`validation/openenv.json` contract. Fresh trials grade the oracle, thedo-nothing floor and any declared canaries under the semantic check ids. Theyrun on the local Docker daemon, or with `--sandbox hf-sandbox` as one HuggingFace Job per trial from the task's digest-pinned image. Checks without animplementation are named SKIPs, so the report is WARN at best.Exit codes: 0 pass/warn · 1 fail · 2 unrecognized/unsupported package · 3internal or policy error.11 unmodified lines# Probe a running server (legacy runtime probe)openenv validate --url http://localhost:8000# Validate a Hub Space on HF Jobs GPU hardwareopenenv validate --space openenv/echo_env --level runtime --flavor t4-small# Run a Harbor task's trials as HF Jobs instead of local Dockeropenenv validate path/to/task --sandbox hf-sandbox --flavor cpu-upgrade```"""if space is not None and (target is not None or url is not None or local):typer.echo("Error: --space cannot be combined with a path, --url or --local", err=True)raise typer.Exit(EXIT_FAIL)if sandbox not in ("docker", "hf-sandbox"):typer.echo(f"Error: unknown sandbox {sandbox!r}; expected docker or hf-sandbox",err=True,)raise typer.Exit(EXIT_FAIL)hf_sandbox = sandbox == "hf-sandbox"running_url = url is not None or (target is not None and _looks_like_url(target))if hf_sandbox and (space is not None or running_url):typer.echo("Error: --sandbox cannot be combined with --space or a running URL",err=True,)raise typer.Exit(EXIT_FAIL)if space is None and revision is not None:typer.echo("Error: --revision requires --space", err=True)raise typer.Exit(EXIT_FAIL)if space is None and not hf_sandbox and flavor != "cpu-basic":typer.echo("Error: --flavor requires --space or --sandbox hf-sandbox", err=True)raise typer.Exit(EXIT_FAIL)if namespace is not None and not hf_sandbox:typer.echo("Error: --namespace requires --sandbox hf-sandbox", err=True)raise typer.Exit(EXIT_FAIL)runtime_target = urlif (runtime_target is not None47 unmodified linesraise typer.Exit(EXIT_INTERNAL)package_root = Path(target) if target is not None else Path.cwd()if space is None and not package_root.is_dir():typer.echo(f"Error: not a package directory: {package_root}", err=True)raise typer.Exit(EXIT_UNSUPPORTED)try:if output is not None and not output.parent.is_dir():raise OSError("report output directory does not exist")with ExitStack() as stack:provider = Noneif space is not None:from huggingface_hub import HfApi, snapshot_download# Download and report one commit, even if a branch moves.revision = (HfApi().space_info(space, revision="main" if revision is None else revision).sha)package_root = (Path(stack.enter_context(tempfile.TemporaryDirectory())) / "source")# Copy the repository snapshot out of the SDK cache, dereferencing# its blob links without adding local_dir download metadata.shutil.copytree(snapshot_download(space, repo_type="space", revision=revision),package_root,)provider = _LazyHFSandboxProvider(space, revision, flavor)stack.enter_context(_sigterm_as_interrupt())validation_report = run_validation(package_root,max_level=_LEVELS[level],skip_build=skip_build,policy=load_policy(policy_version) if policy_version else None,provider=provider,artifacts_dir=(output.parent / (output.stem + ".artifacts") if output else None),report_target=f"spaces/{space}@{revision}"if space is not Noneelse None,sandbox=sandbox,flavor=flavor,namespace=namespace,)report_json = write_report(validation_report, output)except (SignatureError, UnsupportedPackageError) as exc:
123456789101112"""Deterministic source importers for OpenEnv environments."""from .base import DetectedEnvironment, EnvironmentImporter, ImporterRegistryfrom .ors import ORSImporterfrom .verifiers import VerifiersImporterDEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter()]__all__ = ["DEFAULT_IMPORTERS","DetectedEnvironment","EnvironmentImporter",1234567891011121314"""Deterministic source importers for OpenEnv environments."""from .agentenv import AgentEnvImporterfrom .base import DetectedEnvironment, EnvironmentImporter, ImporterRegistryfrom .ors import ORSImporterfrom .verifiers import VerifiersImporterDEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter(), AgentEnvImporter()]__all__ = ["AgentEnvImporter","DEFAULT_IMPORTERS","DetectedEnvironment","EnvironmentImporter",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""AgentEnv bundle source importer."""
from __future__ import annotations
import jsonfrom pathlib import Path
from packaging.requirements import InvalidRequirement, Requirementfrom packaging.specifiers import SpecifierSetfrom packaging.utils import canonicalize_name
from .._cli_utils import consolefrom .base import ( append_dependency_files, collect_source_dependencies, DetectedEnvironment, iter_directories, prepare_import_package, render_importer_template, write_text,)
_FRAMEWORK = "agentenv-framework"_FRAMEWORK_EXTRA = "openenv"_FRAMEWORK_VERSION = "0.9.1366"_FRAMEWORK_FLOOR = f">={_FRAMEWORK_VERSION}"_ADAPTER_SOURCE = ( "https://github.com/scaleapi/agentenv-framework/blob/" f"v{_FRAMEWORK_VERSION}/src/agent_env/openenv")_REQUIRES_PYTHON = ">=3.11.4"
def _is_task_file(path: Path) -> bool: try: steps = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError, ValueError): return False return ( isinstance(steps, list) and bool(steps) and all( isinstance(step, dict) and isinstance(step.get("id"), str) and isinstance(step.get("type"), str) for step in steps ) )
def detect_agentenv_bundles(source: Path) -> list[DetectedEnvironment]: """Detect AgentEnv bundles, folders whose tasks/ holds task files, without importing source.""" source = source.resolve() matches: list[DetectedEnvironment] = []
for tasks_dir in iter_directories(source, "tasks"): if not any(_is_task_file(path) for path in sorted(tasks_dir.glob("*.json"))): continue bundle = tasks_dir.parent matches.append( DetectedEnvironment( source_type="agentenv", class_name=bundle.name, module_path="" if bundle == source else bundle.relative_to(source).as_posix(), file_path=bundle, ) )
return matches
def _with_framework_floor(dependencies: list[str]) -> list[str]: """The bundle's dependencies, with agentenv-framework's openenv extra at least the version that serves bundles.""" for index, dependency in enumerate(dependencies): try: requirement = Requirement(dependency) except InvalidRequirement: continue if canonicalize_name(requirement.name) == _FRAMEWORK: if requirement.url is not None: raise ValueError( f"Cannot verify {_FRAMEWORK}{_FRAMEWORK_FLOOR} from a direct " "reference. In the bundle's pyproject.toml or requirements.txt, " "replace the framework direct reference with a version constraint " f"such as {_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}, " "preserving any additional extras and environment marker." ) requirement.extras.add(_FRAMEWORK_EXTRA) requirement.specifier &= SpecifierSet(_FRAMEWORK_FLOOR) dependencies[index] = str(requirement) return dependencies return [*dependencies, f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}"]
class AgentEnvImporter: """Importer for AgentEnv bundles, served by agentenv-framework's OpenEnv server."""
source_type = "agentenv"
def detect(self, source: Path) -> list[DetectedEnvironment]: return detect_agentenv_bundles(source)
def generate( self, *, source: Path, destination: Path, env_name: str, detected: DetectedEnvironment, ) -> None: bundle = detected.file_path dependencies = _with_framework_floor(collect_source_dependencies(bundle)) package = prepare_import_package( bundle, destination, env_name, vendor_dir=bundle.name ) client = f"{package.class_name_prefix}Env" (destination / "server" / f"{env_name}_environment.py").unlink() (destination / "models.py").unlink() for name, template in ( ("client.py", "agentenv_client.py.tpl"), ("__init__.py", "agentenv_init.py.tpl"), ): write_text( destination / name, render_importer_template(template, env_name=env_name, client=client), ) write_text( destination / "server" / "__init__.py", f'"""{env_name} environment server: an AgentEnv bundle."""\n', ) write_text( destination / "server" / "app.py", render_importer_template( "agentenv_app.py.tpl", bundle=json.dumps(bundle.name) ), ) write_text( destination / "README.md", render_importer_template( "agentenv_README.md.tpl", env_name=env_name, bundle=bundle.name, framework=f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}", adapter=_ADAPTER_SOURCE, client=client, ), ) console.print( "[yellow]Warning:[/yellow] AgentEnv requires local Docker: a Docker CLI " "and a running daemon accessible to the server for image builds and episode " "containers. The generated server/Dockerfile does not provide this " "runtime; openenv build / openenv push alone do not produce a working " "deployment. See README.md for prerequisites." ) append_dependency_files( destination, env_name, dependencies, requires_python=_REQUIRES_PYTHON, )132 unmodified lines13313413513613713857 unmodified lines19619719819920020129 unmodified lines23123223323423523629 unmodified lines2662672682692702712729 unmodified lines282283284285286287288132 unmodified lines]def module_path(source: Path, file_path: Path) -> str:rel = file_path.relative_to(source).with_suffix("")parts = list(rel.parts)57 unmodified linesenv_dir: Path,env_name: str,dependencies: list[str],) -> None:requirements = env_dir / "server" / "requirements.txt"if requirements.exists():29 unmodified linesproject_dependencies.append(dependency)existing.add(_dependency_name(dependency))project["dependencies"] = project_dependenciestool = data.setdefault("tool", {})setuptools = tool.setdefault("setuptools", {})29 unmodified linesdef prepare_import_package(source: Path, destination: Path, env_name: str) -> ImportPackageContext:from openenv.cli.commands.init import (_copy_template_directory,9 unmodified linesenv_name,)vendor_dir = safe_vendor_dir_name(source)vendor_path = destination / "vendor" / vendor_dircopy_source_tree(source, vendor_path)ensure_vendor_package(vendor_path)132 unmodified lines13313413513613713813914014114214314414514657 unmodified lines20420520620720820921029 unmodified lines24024124224324424524624729 unmodified lines2772782792802812822839 unmodified lines293294295296297298299132 unmodified lines]def iter_directories(source: Path, name: str) -> list[Path]:return [pathfor path in sorted(source.rglob(name))if path.is_dir() and not _is_excluded(path.relative_to(source))]def module_path(source: Path, file_path: Path) -> str:rel = file_path.relative_to(source).with_suffix("")parts = list(rel.parts)57 unmodified linesenv_dir: Path,env_name: str,dependencies: list[str],requires_python: str | None = None,) -> None:requirements = env_dir / "server" / "requirements.txt"if requirements.exists():29 unmodified linesproject_dependencies.append(dependency)existing.add(_dependency_name(dependency))project["dependencies"] = project_dependenciesif requires_python:project["requires-python"] = requires_pythontool = data.setdefault("tool", {})setuptools = tool.setdefault("setuptools", {})29 unmodified linesdef prepare_import_package(source: Path, destination: Path, env_name: str, vendor_dir: str | None = None) -> ImportPackageContext:from openenv.cli.commands.init import (_copy_template_directory,9 unmodified linesenv_name,)vendor_dir = vendor_dir or safe_vendor_dir_name(source)vendor_path = destination / "vendor" / vendor_dircopy_source_tree(source, vendor_path)ensure_vendor_package(vendor_path)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# ${env_name}: AgentEnv bundle
This package serves the vendored `${bundle}` bundle through`agent_env.openenv.build_app`. The bundle keeps its original folder name at`vendor/${bundle}`; the generated package name is `${env_name}`.
## Prerequisites
- Python >=3.11.4 and `${framework}` (declared in `pyproject.toml` and `server/requirements.txt`).- Local Docker: a Docker CLI and a running daemon accessible to the server. The delegated server builds the bundle's environment images at startup and deploys episode containers using local Docker by default.- A self-contained bundle: tasks, environment definitions, verifiers, data and dependencies must be included in the bundle or provided by agentenv-framework. Only the selected bundle is vendored; external plugin registrations and files elsewhere in the source repository are not included.
## Run locally
From this generated package directory, after setting up Docker:
```bashuv syncMAX_CONCURRENT_ENVS=8 uv run server --host 127.0.0.1 --port 8000```
`MAX_CONCURRENT_ENVS` (default 8) caps the concurrent sessions. Each sessionplays its own episode on its own deployment.
The `server` entry point runs `server/app.py`, which passes`vendor/${bundle}` to `build_app`. Task selection, splits, tools and rewardsare defined by the bundle and agentenv-framework. The served environment is`agent_env.openenv`'s `AgentEnvEnvironment`; read it, and `build_app`, at theminimum supported version: [environment.py](${adapter}/environment.py) and[app.py](${adapter}/app.py). Follow[AgentEnv's OpenEnv documentation](https://www.agentenvframework.com/docs/openenv)for its API and client usage.
## Client
`client.py` defines `${client}`, an `MCPToolClient`: the served environmenttakes OpenEnv's MCP actions (`ListToolsAction`, `CallToolAction`), which`__init__.py` also exports.
```pythonfrom ${env_name} import ${client}
async with ${client}(base_url="http://127.0.0.1:8000") as env: await env.reset(split="all", index=0) tools = await env.list_tools() ended = await env.call_tool("end_turn", response="Done.") print(ended["done"], ended["reward"])```
The tools are the bundle environment's MCP tools plus `end_turn`, which endsthe turn with its `response`. Its result carries the next turn's prompt, or,once `done`, the task's reward. A step before `reset` raises.
`list_tools()` discovers fresh tools by default because tools can change afterreset, `end_turn`, or a bundle tool call. `get_tool()` and `has_tool()` also usefresh discovery. Pass `list_tools(use_cache=True)` explicitly to reuse the lastdiscovery result.
## Deployment limitations
**Warning:** `server/Dockerfile` does not provide the Docker runtime requiredby the delegated server. `openenv build` / `openenv push` alone do not producea working deployment, including on Hugging Face Spaces. Deployment requiresseparately provisioning the server's image-build and episode-container runtime;this importer does not configure it. Review AgentEnv's runtime requirementsbefore choosing a deployment host.
## Generated files
- `server/app.py`: delegated application and local server entry point.- `vendor/${bundle}`: the selected bundle and its data.- `pyproject.toml`: package dependencies and the `server` entry point.- `server/requirements.txt`: server dependencies.- `openenv.yaml`: generated OpenEnv manifest.- `server/Dockerfile`: shared image template with the limitation described above.- `client.py`, `__init__.py`: the client and the MCP action types it sends.Dockerfile+1-1
README.md+5-3
envs/tbench2_env/README.md+3-1
envs/tbench2_env/pyproject.toml+1-1
envs/tbench2_env/server/Dockerfile+1-1
envs/tbench2_env/server/app.py+14-3
envs/tbench2_env/server/tbench2_env_environment.py+46-6
pyproject.toml+1-1
server/Dockerfile+1-1
server/app.py+14-3
server/tbench2_env_environment.py+46-6
src/core/README.md+6-6
src/core/__init__.py+3-1
src/core/containers/runtime/__init__.py-2
src/core/containers/runtime/_server_config.py+39-2
src/core/containers/runtime/daytona_provider.py+1-1
src/core/containers/runtime/hf_sandbox_provider.py+64-12
src/core/containers/runtime/kubernetes_provider.pyAdded+985
src/core/containers/runtime/modal_provider.py+22-53
src/core/containers/runtime/providers.py+94-32
src/core/containers/runtime/uv_provider.py+22-3
src/core/env_client.py+62-9
src/core/env_server/exceptions.py+11-2
src/core/env_server/http_server.py+502-68
src/core/env_server/interfaces.py+2-2
src/core/env_server/mcp_environment.py+17-18
src/core/env_server/security.pyAdded+192
src/core/env_server/session_telemetry.pyAdded+241
src/core/env_server/types.py+6
src/core/env_server/web_interface.py+9-2
src/core/harness/bridge.py+14-4
src/core/harness/capture/forwarding.py+27
src/core/harness/capture/graph.py+16
src/core/harness/capture/server.py+52
src/core/harness/capture/validate_llm.py+58-6
src/core/harness/collect.py+34-15
src/core/mcp_client.py+6
src/core/openenv/auto/auto_action.py+3-3
src/core/openenv/auto/auto_env.py+3-3
src/core/openenv/cli/__main__.py+4-3
src/core/openenv/cli/commands/build.py+33-59
src/core/openenv/cli/commands/harbor.py+194-6
src/core/openenv/cli/commands/push.py+2-4
src/core/openenv/cli/commands/serve.py+122-57
src/core/openenv/cli/commands/skills.py+1-1
src/core/openenv/cli/commands/validate.py+154-4
src/core/openenv/cli/importers/__init__.py+3-1
src/core/openenv/cli/importers/agentenv.pyAdded+163
src/core/openenv/cli/importers/base.py+13-2
src/core/openenv/cli/importers/templates/agentenv_README.md.tplAdded+82