sergiopaniego HF Staff commited on
Commit
f628adc
·
verified ·
1 Parent(s): 36a4110

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +1 -1
  2. README.md +10 -8
  3. envs/carla_env/README.md +8 -6
  4. envs/carla_env/pyproject.toml +1 -1
  5. envs/carla_env/server/Dockerfile +1 -1
  6. envs/carla_env/server/Dockerfile.real +1 -1
  7. pyproject.toml +1 -1
  8. server/Dockerfile +1 -1
  9. server/Dockerfile.real +1 -1
  10. src/core/README.md +6 -6
  11. src/core/__init__.py +3 -1
  12. src/core/containers/runtime/__init__.py +0 -2
  13. src/core/containers/runtime/_server_config.py +39 -2
  14. src/core/containers/runtime/daytona_provider.py +1 -1
  15. src/core/containers/runtime/hf_sandbox_provider.py +64 -12
  16. src/core/containers/runtime/kubernetes_provider.py +985 -0
  17. src/core/containers/runtime/modal_provider.py +22 -53
  18. src/core/containers/runtime/providers.py +94 -32
  19. src/core/containers/runtime/uv_provider.py +22 -3
  20. src/core/env_client.py +62 -9
  21. src/core/env_server/exceptions.py +11 -2
  22. src/core/env_server/http_server.py +502 -68
  23. src/core/env_server/interfaces.py +2 -2
  24. src/core/env_server/mcp_environment.py +17 -18
  25. src/core/env_server/security.py +192 -0
  26. src/core/env_server/session_telemetry.py +241 -0
  27. src/core/env_server/types.py +6 -0
  28. src/core/env_server/web_interface.py +9 -2
  29. src/core/harness/bridge.py +14 -4
  30. src/core/harness/capture/forwarding.py +27 -0
  31. src/core/harness/capture/graph.py +16 -0
  32. src/core/harness/capture/server.py +52 -0
  33. src/core/harness/capture/validate_llm.py +58 -6
  34. src/core/harness/collect.py +34 -15
  35. src/core/mcp_client.py +6 -0
  36. src/core/openenv/auto/auto_action.py +3 -3
  37. src/core/openenv/auto/auto_env.py +3 -3
  38. src/core/openenv/cli/__main__.py +4 -3
  39. src/core/openenv/cli/commands/build.py +33 -59
  40. src/core/openenv/cli/commands/harbor.py +194 -6
  41. src/core/openenv/cli/commands/push.py +2 -4
  42. src/core/openenv/cli/commands/serve.py +122 -57
  43. src/core/openenv/cli/commands/skills.py +1 -1
  44. src/core/openenv/cli/commands/validate.py +154 -4
  45. src/core/openenv/cli/importers/__init__.py +3 -1
  46. src/core/openenv/cli/importers/agentenv.py +163 -0
  47. src/core/openenv/cli/importers/base.py +13 -2
  48. src/core/openenv/cli/importers/templates/agentenv_README.md.tpl +82 -0
  49. src/core/openenv/cli/importers/templates/agentenv_app.py.tpl +29 -0
  50. src/core/openenv/cli/importers/templates/agentenv_client.py.tpl +29 -0
Dockerfile CHANGED
@@ -90,7 +90,7 @@ RUN pip install --upgrade pip \
90
  && pip install --no-cache-dir cffi cryptography
91
 
92
  # Install OpenEnv core from GitHub
93
- RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git@v0.10.0
94
 
95
  # Copy and install environment dependencies
96
  COPY server/requirements.txt /tmp/requirements.txt
 
90
  && pip install --no-cache-dir cffi cryptography
91
 
92
  # Install OpenEnv core from GitHub
93
+ RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git@v0.15.0
94
 
95
  # Copy and install environment dependencies
96
  COPY server/requirements.txt /tmp/requirements.txt
README.md CHANGED
@@ -8,7 +8,7 @@ pinned: false
8
  app_port: 8000
9
  base_path: /web
10
  tags:
11
- - openenv-0.10.0
12
  - openenv
13
  - carla
14
  - embodied-ai
@@ -31,6 +31,8 @@ Embodied evaluation environment for testing LLM decision-making in a full 3D dri
31
  - Free-roam and maze navigation with configurable traffic
32
  - Rubric-based reward system for RL training
33
 
 
 
34
  ## What Makes This Different
35
 
36
  Traditional text benchmarks ask models "what would you do?" This environment shows **what models actually do** when:
@@ -65,7 +67,7 @@ with CarlaEnv(base_url="http://localhost:8000").sync() as env:
65
  ```bash
66
  uv run python examples/carla_env/trolley_problems.py \
67
  --model qwen3-235b --scenario classic-3v1 \
68
- --base-url https://sergiopaniego-carla-env.hf.space
69
  ```
70
 
71
  ## Scenarios
@@ -173,7 +175,7 @@ result = await env.reset(scenario_config={
173
 
174
  ## Examples
175
 
176
- The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://sergiopaniego-carla-env.hf.space` for the live Space.
177
 
178
  ### Trolley Problems
179
 
@@ -294,7 +296,7 @@ docker build -t carla-env:latest -f server/Dockerfile .
294
  docker run --gpus all -p 8000:8000 carla-env:latest
295
  ```
296
 
297
- **Live Space**: [sergiopaniego/carla-env](https://huggingface.co/spaces/sergiopaniego/carla-env)
298
 
299
  ### Specifications
300
 
@@ -353,7 +355,7 @@ Default is **RenderOffScreen** (supports `capture_image`). For text-only evaluat
353
 
354
  ## Resources
355
 
356
- - **OpenEnv Framework**: [github.com/huggingface/OpenEnv](https://github.com/huggingface/OpenEnv)
357
  - **Original carla-env**: [sinatras/carla-env](https://github.com/SinatrasC/carla-env)
358
  - **Blog Post**: [Carla-Env: Giving Models Access to World Simulation](https://blog.sinatras.dev/Carla-Env)
359
  - **CARLA Simulator**: [carla.org](https://carla.org/)
@@ -377,20 +379,20 @@ Scenarios and navigation agents adapted from [sinatras/carla-env](https://github
377
  title = {CARLA Environment for OpenEnv},
378
  author = {OpenEnv Contributors},
379
  year = {2026},
380
- url = {https://github.com/huggingface/OpenEnv}
381
  }
382
  ```
383
 
384
  ## License
385
 
386
- BSD-3-Clause License (see [LICENSE](https://github.com/huggingface/OpenEnv/blob/main/LICENSE))
387
 
388
  ## Hugging Face Space Deployment
389
 
390
  This Space is built from OpenEnv environment `carla_env`.
391
 
392
  - Space URL: `https://huggingface.co/spaces/openenv/carla_env`
393
- - OpenEnv pinned ref: `0.10.0`
394
  - Hub tag: `openenv`
395
 
396
  ### Connecting from Code
 
8
  app_port: 8000
9
  base_path: /web
10
  tags:
11
+ - openenv-0.15.0
12
  - openenv
13
  - carla
14
  - embodied-ai
 
31
  - Free-roam and maze navigation with configurable traffic
32
  - Rubric-based reward system for RL training
33
 
34
+ The [`openenv/carla_env`](https://huggingface.co/spaces/openenv/carla_env) Space is paused because CARLA needs a GPU. Duplicate it and pick an A10G in the Space settings to run your own copy.
35
+
36
  ## What Makes This Different
37
 
38
  Traditional text benchmarks ask models "what would you do?" This environment shows **what models actually do** when:
 
67
  ```bash
68
  uv run python examples/carla_env/trolley_problems.py \
69
  --model qwen3-235b --scenario classic-3v1 \
70
+ --base-url https://<your-space>.hf.space
71
  ```
72
 
73
  ## Scenarios
 
175
 
176
  ## Examples
177
 
178
+ The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://<your-space>.hf.space` for your running copy of the Space.
179
 
180
  ### Trolley Problems
181
 
 
296
  docker run --gpus all -p 8000:8000 carla-env:latest
297
  ```
298
 
299
+ **Space**: [openenv/carla_env](https://huggingface.co/spaces/openenv/carla_env) (paused, duplicate it with an A10G)
300
 
301
  ### Specifications
302
 
 
355
 
356
  ## Resources
357
 
358
+ - **OpenEnv Framework**: [github.com/openenv/OpenEnv](https://github.com/openenv/OpenEnv)
359
  - **Original carla-env**: [sinatras/carla-env](https://github.com/SinatrasC/carla-env)
360
  - **Blog Post**: [Carla-Env: Giving Models Access to World Simulation](https://blog.sinatras.dev/Carla-Env)
361
  - **CARLA Simulator**: [carla.org](https://carla.org/)
 
379
  title = {CARLA Environment for OpenEnv},
380
  author = {OpenEnv Contributors},
381
  year = {2026},
382
+ url = {https://github.com/openenv/OpenEnv}
383
  }
384
  ```
385
 
386
  ## License
387
 
388
+ BSD-3-Clause License (see [LICENSE](https://github.com/openenv/OpenEnv/blob/main/LICENSE))
389
 
390
  ## Hugging Face Space Deployment
391
 
392
  This Space is built from OpenEnv environment `carla_env`.
393
 
394
  - Space URL: `https://huggingface.co/spaces/openenv/carla_env`
395
+ - OpenEnv pinned ref: `0.15.0`
396
  - Hub tag: `openenv`
397
 
398
  ### Connecting from Code
envs/carla_env/README.md CHANGED
@@ -30,6 +30,8 @@ Embodied evaluation environment for testing LLM decision-making in a full 3D dri
30
  - Free-roam and maze navigation with configurable traffic
31
  - Rubric-based reward system for RL training
32
 
 
 
33
  ## What Makes This Different
34
 
35
  Traditional text benchmarks ask models "what would you do?" This environment shows **what models actually do** when:
@@ -64,7 +66,7 @@ with CarlaEnv(base_url="http://localhost:8000").sync() as env:
64
  ```bash
65
  uv run python examples/carla_env/trolley_problems.py \
66
  --model qwen3-235b --scenario classic-3v1 \
67
- --base-url https://sergiopaniego-carla-env.hf.space
68
  ```
69
 
70
  ## Scenarios
@@ -172,7 +174,7 @@ result = await env.reset(scenario_config={
172
 
173
  ## Examples
174
 
175
- The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://sergiopaniego-carla-env.hf.space` for the live Space.
176
 
177
  ### Trolley Problems
178
 
@@ -293,7 +295,7 @@ docker build -t carla-env:latest -f server/Dockerfile .
293
  docker run --gpus all -p 8000:8000 carla-env:latest
294
  ```
295
 
296
- **Live Space**: [sergiopaniego/carla-env](https://huggingface.co/spaces/sergiopaniego/carla-env)
297
 
298
  ### Specifications
299
 
@@ -352,7 +354,7 @@ Default is **RenderOffScreen** (supports `capture_image`). For text-only evaluat
352
 
353
  ## Resources
354
 
355
- - **OpenEnv Framework**: [github.com/huggingface/OpenEnv](https://github.com/huggingface/OpenEnv)
356
  - **Original carla-env**: [sinatras/carla-env](https://github.com/SinatrasC/carla-env)
357
  - **Blog Post**: [Carla-Env: Giving Models Access to World Simulation](https://blog.sinatras.dev/Carla-Env)
358
  - **CARLA Simulator**: [carla.org](https://carla.org/)
@@ -376,10 +378,10 @@ Scenarios and navigation agents adapted from [sinatras/carla-env](https://github
376
  title = {CARLA Environment for OpenEnv},
377
  author = {OpenEnv Contributors},
378
  year = {2026},
379
- url = {https://github.com/huggingface/OpenEnv}
380
  }
381
  ```
382
 
383
  ## License
384
 
385
- BSD-3-Clause License (see [LICENSE](https://github.com/huggingface/OpenEnv/blob/main/LICENSE))
 
30
  - Free-roam and maze navigation with configurable traffic
31
  - Rubric-based reward system for RL training
32
 
33
+ The [`openenv/carla_env`](https://huggingface.co/spaces/openenv/carla_env) Space is paused because CARLA needs a GPU. Duplicate it and pick an A10G in the Space settings to run your own copy.
34
+
35
  ## What Makes This Different
36
 
37
  Traditional text benchmarks ask models "what would you do?" This environment shows **what models actually do** when:
 
66
  ```bash
67
  uv run python examples/carla_env/trolley_problems.py \
68
  --model qwen3-235b --scenario classic-3v1 \
69
+ --base-url https://<your-space>.hf.space
70
  ```
71
 
72
  ## Scenarios
 
174
 
175
  ## Examples
176
 
177
+ The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://<your-space>.hf.space` for your running copy of the Space.
178
 
179
  ### Trolley Problems
180
 
 
295
  docker run --gpus all -p 8000:8000 carla-env:latest
296
  ```
297
 
298
+ **Space**: [openenv/carla_env](https://huggingface.co/spaces/openenv/carla_env) (paused, duplicate it with an A10G)
299
 
300
  ### Specifications
301
 
 
354
 
355
  ## Resources
356
 
357
+ - **OpenEnv Framework**: [github.com/openenv/OpenEnv](https://github.com/openenv/OpenEnv)
358
  - **Original carla-env**: [sinatras/carla-env](https://github.com/SinatrasC/carla-env)
359
  - **Blog Post**: [Carla-Env: Giving Models Access to World Simulation](https://blog.sinatras.dev/Carla-Env)
360
  - **CARLA Simulator**: [carla.org](https://carla.org/)
 
378
  title = {CARLA Environment for OpenEnv},
379
  author = {OpenEnv Contributors},
380
  year = {2026},
381
+ url = {https://github.com/openenv/OpenEnv}
382
  }
383
  ```
384
 
385
  ## License
386
 
387
+ BSD-3-Clause License (see [LICENSE](https://github.com/openenv/OpenEnv/blob/main/LICENSE))
envs/carla_env/pyproject.toml CHANGED
@@ -15,7 +15,7 @@ description = "CARLA environment for OpenEnv - embodied evaluation with temporal
15
  requires-python = ">=3.11"
16
  dependencies = [
17
  # Core OpenEnv dependencies (required for server functionality)
18
- "openenv @ git+https://github.com/huggingface/OpenEnv.git@v0.10.0",
19
  "fastapi>=0.115.0",
20
  "pydantic>=2.0.0",
21
  "uvicorn>=0.24.0",
 
15
  requires-python = ">=3.11"
16
  dependencies = [
17
  # Core OpenEnv dependencies (required for server functionality)
18
+ "openenv @ git+https://github.com/openenv/OpenEnv.git@v0.15.0",
19
  "fastapi>=0.115.0",
20
  "pydantic>=2.0.0",
21
  "uvicorn>=0.24.0",
envs/carla_env/server/Dockerfile CHANGED
@@ -90,7 +90,7 @@ RUN pip install --upgrade pip \
90
  && pip install --no-cache-dir cffi cryptography
91
 
92
  # Install OpenEnv core from GitHub
93
- RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git
94
 
95
  # Copy and install environment dependencies
96
  COPY server/requirements.txt /tmp/requirements.txt
 
90
  && pip install --no-cache-dir cffi cryptography
91
 
92
  # Install OpenEnv core from GitHub
93
+ RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git
94
 
95
  # Copy and install environment dependencies
96
  COPY server/requirements.txt /tmp/requirements.txt
envs/carla_env/server/Dockerfile.real CHANGED
@@ -25,7 +25,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
25
  WORKDIR /app
26
 
27
  # Install OpenEnv core from GitHub
28
- RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git
29
 
30
  # Copy and install environment dependencies
31
  COPY server/requirements.txt /tmp/requirements.txt
 
25
  WORKDIR /app
26
 
27
  # Install OpenEnv core from GitHub
28
+ RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git
29
 
30
  # Copy and install environment dependencies
31
  COPY server/requirements.txt /tmp/requirements.txt
pyproject.toml CHANGED
@@ -15,7 +15,7 @@ description = "CARLA environment for OpenEnv - embodied evaluation with temporal
15
  requires-python = ">=3.11"
16
  dependencies = [
17
  # Core OpenEnv dependencies (required for server functionality)
18
- "openenv @ git+https://github.com/huggingface/OpenEnv.git@v0.10.0",
19
  "fastapi>=0.115.0",
20
  "pydantic>=2.0.0",
21
  "uvicorn>=0.24.0",
 
15
  requires-python = ">=3.11"
16
  dependencies = [
17
  # Core OpenEnv dependencies (required for server functionality)
18
+ "openenv @ git+https://github.com/openenv/OpenEnv.git@v0.15.0",
19
  "fastapi>=0.115.0",
20
  "pydantic>=2.0.0",
21
  "uvicorn>=0.24.0",
server/Dockerfile CHANGED
@@ -90,7 +90,7 @@ RUN pip install --upgrade pip \
90
  && pip install --no-cache-dir cffi cryptography
91
 
92
  # Install OpenEnv core from GitHub
93
- RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git
94
 
95
  # Copy and install environment dependencies
96
  COPY server/requirements.txt /tmp/requirements.txt
 
90
  && pip install --no-cache-dir cffi cryptography
91
 
92
  # Install OpenEnv core from GitHub
93
+ RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git
94
 
95
  # Copy and install environment dependencies
96
  COPY server/requirements.txt /tmp/requirements.txt
server/Dockerfile.real CHANGED
@@ -25,7 +25,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
25
  WORKDIR /app
26
 
27
  # Install OpenEnv core from GitHub
28
- RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git
29
 
30
  # Copy and install environment dependencies
31
  COPY server/requirements.txt /tmp/requirements.txt
 
25
  WORKDIR /app
26
 
27
  # Install OpenEnv core from GitHub
28
+ RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git
29
 
30
  # Copy and install environment dependencies
31
  COPY server/requirements.txt /tmp/requirements.txt
src/core/README.md CHANGED
@@ -165,14 +165,14 @@ provider.wait_for_ready(base_url)
165
  provider.stop_container()
166
  ```
167
 
168
- ### Kubernetes Provider (Coming Soon)
169
 
170
  ```python
171
- from openenv.core.containers.runtime import KubernetesProvider
172
 
173
  provider = KubernetesProvider(namespace="envs")
174
  base_url = provider.start_container("my-env:latest")
175
- # Use environment...
176
  provider.stop_container()
177
  ```
178
 
@@ -232,6 +232,6 @@ Contributions are welcome! Please see the main OpenEnv repository for contributi
232
 
233
  ## Links
234
 
235
- - **Homepage**: https://github.com/huggingface/OpenEnv
236
- - **Documentation**: https://github.com/huggingface/OpenEnv/blob/main/README.md
237
- - **Bug Tracker**: https://github.com/huggingface/OpenEnv/issues
 
165
  provider.stop_container()
166
  ```
167
 
168
+ ### Kubernetes Provider
169
 
170
  ```python
171
+ from openenv.core.containers.runtime.kubernetes_provider import KubernetesProvider
172
 
173
  provider = KubernetesProvider(namespace="envs")
174
  base_url = provider.start_container("my-env:latest")
175
+ provider.wait_for_ready(base_url)
176
  provider.stop_container()
177
  ```
178
 
 
232
 
233
  ## Links
234
 
235
+ - **Homepage**: https://github.com/openenv/OpenEnv
236
+ - **Documentation**: https://github.com/openenv/OpenEnv/blob/main/README.md
237
+ - **Bug Tracker**: https://github.com/openenv/OpenEnv/issues
src/core/__init__.py CHANGED
@@ -11,7 +11,7 @@ from . import env_server
11
  from .env_server import * # noqa: F403
12
 
13
  if TYPE_CHECKING:
14
- from .env_client import EnvClient
15
  from .generic_client import GenericAction, GenericEnvClient
16
  from .llm_client import (
17
  AnthropicClient,
@@ -26,6 +26,7 @@ if TYPE_CHECKING:
26
 
27
  __all__ = [
28
  "EnvClient",
 
29
  "SyncEnvClient",
30
  "GenericEnvClient",
31
  "GenericAction",
@@ -42,6 +43,7 @@ __all__ = [
42
 
43
  _LAZY_ATTRS = {
44
  "EnvClient": (".env_client", "EnvClient"),
 
45
  "SyncEnvClient": (".sync_client", "SyncEnvClient"),
46
  "GenericEnvClient": (".generic_client", "GenericEnvClient"),
47
  "GenericAction": (".generic_client", "GenericAction"),
 
11
  from .env_server import * # noqa: F403
12
 
13
  if TYPE_CHECKING:
14
+ from .env_client import EnvClient, SessionLostError
15
  from .generic_client import GenericAction, GenericEnvClient
16
  from .llm_client import (
17
  AnthropicClient,
 
26
 
27
  __all__ = [
28
  "EnvClient",
29
+ "SessionLostError",
30
  "SyncEnvClient",
31
  "GenericEnvClient",
32
  "GenericAction",
 
43
 
44
  _LAZY_ATTRS = {
45
  "EnvClient": (".env_client", "EnvClient"),
46
+ "SessionLostError": (".env_client", "SessionLostError"),
47
  "SyncEnvClient": (".sync_client", "SyncEnvClient"),
48
  "GenericEnvClient": (".generic_client", "GenericEnvClient"),
49
  "GenericAction": (".generic_client", "GenericAction"),
src/core/containers/runtime/__init__.py CHANGED
@@ -5,7 +5,6 @@
5
  from .providers import (
6
  ContainerProvider,
7
  DockerSwarmProvider,
8
- KubernetesProvider,
9
  LocalDockerProvider,
10
  RuntimeProvider,
11
  )
@@ -20,7 +19,6 @@ __all__ = [
20
  "ContainerProvider",
21
  "DockerSwarmProvider",
22
  "LocalDockerProvider",
23
- "KubernetesProvider",
24
  "RuntimeProvider",
25
  "UVProvider",
26
  ]
 
5
  from .providers import (
6
  ContainerProvider,
7
  DockerSwarmProvider,
 
8
  LocalDockerProvider,
9
  RuntimeProvider,
10
  )
 
19
  "ContainerProvider",
20
  "DockerSwarmProvider",
21
  "LocalDockerProvider",
 
22
  "RuntimeProvider",
23
  "UVProvider",
24
  ]
src/core/containers/runtime/_server_config.py CHANGED
@@ -30,11 +30,48 @@ def parse_openenv_app_field(yaml_content: str) -> str | None:
30
  def parse_dockerfile_cmd(dockerfile_content: str) -> str | None:
31
  """Extract the server command from the last Dockerfile ``CMD``."""
32
  last_cmd: str | None = None
 
 
 
33
  for line in dockerfile_content.splitlines():
34
- stripped = line.strip()
35
  if stripped.startswith("#"):
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  continue
37
- match = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  if match:
39
  last_cmd = match.group(1).strip()
40
 
 
30
  def parse_dockerfile_cmd(dockerfile_content: str) -> str | None:
31
  """Extract the server command from the last Dockerfile ``CMD``."""
32
  last_cmd: str | None = None
33
+ instruction = ""
34
+ escape = "\\"
35
+ directives = True
36
  for line in dockerfile_content.splitlines():
37
+ stripped = line.lstrip()
38
  if stripped.startswith("#"):
39
+ if directives:
40
+ directive = re.fullmatch(
41
+ r"#\s*(syntax|check|escape)\s*=\s*(.+)",
42
+ stripped,
43
+ flags=re.IGNORECASE,
44
+ )
45
+ if directive is None:
46
+ directives = False
47
+ elif directive[1].lower() == "escape" and directive[2].strip() in (
48
+ "\\",
49
+ "`",
50
+ ):
51
+ escape = directive[2].strip()
52
  continue
53
+ if not stripped.strip():
54
+ directives = False
55
+ continue
56
+ directives = False
57
+ if not instruction:
58
+ match = re.match(r"\s*CMD\s+(.+)", line, flags=re.IGNORECASE)
59
+ if match:
60
+ last_cmd = match.group(1).strip()
61
+ continuation = re.search(
62
+ rf"(?<!{re.escape(escape)}){re.escape(escape)}[ \t]*$", line
63
+ )
64
+ if continuation:
65
+ instruction += line[: continuation.start()]
66
+ continue
67
+ instruction += line
68
+ match = re.match(r"\s*CMD\s+(.+)", instruction, flags=re.IGNORECASE)
69
+ if match:
70
+ last_cmd = match.group(1).strip()
71
+ instruction = ""
72
+
73
+ if instruction:
74
+ match = re.match(r"\s*CMD\s+(.+)", instruction, flags=re.IGNORECASE)
75
  if match:
76
  last_cmd = match.group(1).strip()
77
 
src/core/containers/runtime/daytona_provider.py CHANGED
@@ -3,7 +3,7 @@
3
  """
4
  Daytona container provider for running OpenEnv environments in Daytona cloud sandboxes.
5
 
6
- Requires the ``daytona`` SDK: ``pip install daytona>=0.10``
7
  """
8
 
9
  from __future__ import annotations
 
3
  """
4
  Daytona container provider for running OpenEnv environments in Daytona cloud sandboxes.
5
 
6
+ Requires the ``daytona`` SDK: ``pip install 'daytona>=0.10,<1'``
7
  """
8
 
9
  from __future__ import annotations
src/core/containers/runtime/hf_sandbox_provider.py CHANGED
@@ -10,6 +10,7 @@ from __future__ import annotations
10
 
11
  import asyncio
12
  import hashlib
 
13
  import socket
14
  import threading
15
  import time
@@ -24,6 +25,8 @@ from websockets.exceptions import ConnectionClosed
24
  from .providers import ContainerProvider
25
 
26
 
 
 
27
  _DEFAULT_PORT = 8000
28
  _SERVER_COMMAND = (
29
  'export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; '
@@ -95,6 +98,17 @@ def _get_pool(image: str, flavor: str) -> Any:
95
 
96
 
97
  class _LocalAuthProxy:
 
 
 
 
 
 
 
 
 
 
 
98
  def __init__(self, *, target_url: str, headers: dict[str, str]):
99
  self.target_url = target_url.rstrip("/")
100
  self.headers = headers
@@ -131,13 +145,20 @@ class _LocalAuthProxy:
131
  data=body,
132
  headers=headers,
133
  timeout=60.0,
134
- allow_redirects=True,
135
  )
136
  except requests.RequestException:
137
  return Response(
138
  content=b"upstream HF job unreachable",
139
  status_code=502,
140
  )
 
 
 
 
 
 
 
141
  response_headers = {
142
  key: value
143
  for key, value in upstream.headers.items()
@@ -156,7 +177,16 @@ class _LocalAuthProxy:
156
  if query:
157
  target = f"{target}?{query}"
158
  headers = {**self.headers, "accept": "*/*"}
159
- upstream = await self._connect_upstream_websocket(target, headers)
 
 
 
 
 
 
 
 
 
160
  await websocket.accept()
161
  try:
162
  to_upstream = asyncio.create_task(
@@ -201,13 +231,18 @@ class _LocalAuthProxy:
201
  ) -> Any:
202
  last_error: Exception | None = None
203
  for _ in range(5):
 
 
 
 
 
 
 
 
 
 
204
  try:
205
- return await ws_connect(
206
- target,
207
- additional_headers=headers,
208
- max_size=_MAX_WS_MESSAGE_SIZE,
209
- compression=None,
210
- )
211
  except Exception as exc:
212
  last_error = exc
213
  await asyncio.sleep(0.5)
@@ -227,10 +262,18 @@ class _LocalAuthProxy:
227
  await websocket.send_text(message)
228
 
229
  def stop(self) -> None:
 
 
 
230
  if self._server is None or self._thread is None:
231
  return
232
  self._server.should_exit = True
 
 
 
233
  self._thread.join(timeout=5.0)
 
 
234
  self._server = None
235
  self._thread = None
236
 
@@ -272,8 +315,11 @@ class HFSandboxProvider(ContainerProvider):
272
  env_vars: dict[str, str] | None = None,
273
  **kwargs: Any,
274
  ) -> str:
275
- if self._sandbox is not None:
276
- raise RuntimeError("HFSandboxProvider already has an active service")
 
 
 
277
  if kwargs:
278
  unsupported = ", ".join(sorted(kwargs))
279
  raise ValueError(
@@ -311,14 +357,20 @@ class HFSandboxProvider(ContainerProvider):
311
  raise
312
 
313
  def stop_container(self) -> None:
 
314
  if self._proxy is not None:
315
- self._proxy.stop()
316
- self._proxy = None
 
 
 
317
  if self._sandbox is not None:
318
  sandbox = self._sandbox
319
  self._sandbox = None
320
  with suppress(Exception):
321
  sandbox.kill()
 
 
322
 
323
  def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None:
324
  deadline = time.time() + timeout_s
 
10
 
11
  import asyncio
12
  import hashlib
13
+ import logging
14
  import socket
15
  import threading
16
  import time
 
25
  from .providers import ContainerProvider
26
 
27
 
28
+ logger = logging.getLogger(__name__)
29
+
30
  _DEFAULT_PORT = 8000
31
  _SERVER_COMMAND = (
32
  'export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; '
 
98
 
99
 
100
  class _LocalAuthProxy:
101
+ """Loopback proxy that adds the HF auth headers to every request.
102
+
103
+ Copied into agent_sandbox_provider._LocalAuthProxy; keep the copies
104
+ aligned.
105
+
106
+ Limitations: bodies are buffered (a streamed upstream response such as
107
+ SSE is withheld until it ends), only JSON text frames are relayed
108
+ upstream (binary client frames and close codes are not forwarded), and
109
+ upstream redirects are rejected. EnvClient uses none of these.
110
+ """
111
+
112
  def __init__(self, *, target_url: str, headers: dict[str, str]):
113
  self.target_url = target_url.rstrip("/")
114
  self.headers = headers
 
145
  data=body,
146
  headers=headers,
147
  timeout=60.0,
148
+ allow_redirects=False,
149
  )
150
  except requests.RequestException:
151
  return Response(
152
  content=b"upstream HF job unreachable",
153
  status_code=502,
154
  )
155
+ if 300 <= upstream.status_code < 400:
156
+ # Following a redirect would replay the body and the injected
157
+ # headers to another origin and could downgrade https to http.
158
+ return Response(
159
+ content=b"upstream HF job redirected; rejected",
160
+ status_code=502,
161
+ )
162
  response_headers = {
163
  key: value
164
  for key, value in upstream.headers.items()
 
177
  if query:
178
  target = f"{target}?{query}"
179
  headers = {**self.headers, "accept": "*/*"}
180
+ try:
181
+ upstream = await self._connect_upstream_websocket(target, headers)
182
+ except Exception:
183
+ # Never propagate the upstream exception: its message can embed
184
+ # the target URL, which may carry credentials. Deny generically
185
+ # instead.
186
+ logger.warning("HF sandbox WebSocket upstream handshake failed")
187
+ with suppress(Exception):
188
+ await websocket.close(code=1011)
189
+ return
190
  await websocket.accept()
191
  try:
192
  to_upstream = asyncio.create_task(
 
231
  ) -> Any:
232
  last_error: Exception | None = None
233
  for _ in range(5):
234
+ connector = ws_connect(
235
+ target,
236
+ additional_headers=headers,
237
+ max_size=_MAX_WS_MESSAGE_SIZE,
238
+ compression=None,
239
+ )
240
+ # Never follow handshake redirects: websockets replays
241
+ # additional_headers to the redirect target, which would leak the
242
+ # auth headers to another origin.
243
+ connector.process_redirect = lambda exc: exc
244
  try:
245
+ return await connector
 
 
 
 
 
246
  except Exception as exc:
247
  last_error = exc
248
  await asyncio.sleep(0.5)
 
262
  await websocket.send_text(message)
263
 
264
  def stop(self) -> None:
265
+ """Shut the proxy down. Raises `RuntimeError` if the thread will not
266
+ exit; the handles are then retained so a later call can retry, instead
267
+ of silently leaking a thread that keeps the loopback port bound."""
268
  if self._server is None or self._thread is None:
269
  return
270
  self._server.should_exit = True
271
+ # Bound the graceful drain: do not wait out long-lived upstream
272
+ # responses that would outlive the 5s join below.
273
+ self._server.force_exit = True
274
  self._thread.join(timeout=5.0)
275
+ if self._thread.is_alive():
276
+ raise RuntimeError("HF sandbox auth proxy did not stop")
277
  self._server = None
278
  self._thread = None
279
 
 
315
  env_vars: dict[str, str] | None = None,
316
  **kwargs: Any,
317
  ) -> str:
318
+ if self._sandbox is not None or self._proxy is not None:
319
+ raise RuntimeError(
320
+ "HFSandboxProvider already has an active service, or a proxy "
321
+ "still awaits cleanup. Call stop_container() first."
322
+ )
323
  if kwargs:
324
  unsupported = ", ".join(sorted(kwargs))
325
  raise ValueError(
 
357
  raise
358
 
359
  def stop_container(self) -> None:
360
+ proxy_error: RuntimeError | None = None
361
  if self._proxy is not None:
362
+ try:
363
+ self._proxy.stop()
364
+ self._proxy = None
365
+ except RuntimeError as exc:
366
+ proxy_error = exc
367
  if self._sandbox is not None:
368
  sandbox = self._sandbox
369
  self._sandbox = None
370
  with suppress(Exception):
371
  sandbox.kill()
372
+ if proxy_error is not None:
373
+ raise proxy_error
374
 
375
  def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None:
376
  deadline = time.time() + timeout_s
src/core/containers/runtime/kubernetes_provider.py ADDED
@@ -0,0 +1,985 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """
4
+ Kubernetes container provider for running OpenEnv environments in-cluster.
5
+
6
+ Requires the ``kubernetes`` client: ``pip install openenv[kubernetes]``
7
+
8
+ One provider instance owns one Pod and one Service, matching
9
+ ``LocalDockerProvider`` owning one container. The returned ``base_url`` is the
10
+ short in-cluster Service address ``http://{name}.{namespace}:{port}``. Pod DNS
11
+ search completes that to the cluster domain, so the provider does not hardcode
12
+ ``.svc.cluster.local``. That plaintext URL is the in-cluster exception
13
+ confirmed for this provider: ``ModalProvider`` and ``ACASandboxProvider`` still
14
+ refuse non-HTTPS tunnel URLs. This provider never returns a URL it did not
15
+ construct from a validated name, namespace, and port, and it does not copy
16
+ that URL or raw API bodies into errors.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ import secrets
23
+ import time
24
+ from typing import Any, Mapping, Optional
25
+
26
+ from .providers import ContainerProvider
27
+
28
+ _CONTAINER_PORT = 8000
29
+ _CONTAINER_NAME = "env"
30
+ _DEFAULT_NAMESPACE = "default"
31
+ _NAME_PREFIX = "openenv-"
32
+
33
+ # ``openenv-`` + slug + ``-`` + millisecond timestamp + ``-`` + 4 hex chars.
34
+ _SLUG_MAX = 32
35
+
36
+ _DNS_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
37
+ _LABEL_NAME = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$")
38
+ _LABEL_VALUE = re.compile(r"^([A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$")
39
+ _SAFE_REASON = re.compile(r"^[A-Za-z][A-Za-z0-9]{0,63}$")
40
+
41
+ # Applied last so a caller-supplied label cannot drop ownership or retarget
42
+ # the Service selector.
43
+ _SELECTOR_KEY = "app.kubernetes.io/instance"
44
+
45
+ _START_KWARGS = {
46
+ "resources",
47
+ "runtime_class_name",
48
+ "image_pull_secrets",
49
+ "labels",
50
+ "service_account_name",
51
+ "automount_service_account_token",
52
+ }
53
+
54
+
55
+ def _raise_install_error(exc: ImportError) -> None:
56
+ raise RuntimeError(
57
+ "KubernetesProvider requires the kubernetes client. "
58
+ "Install it with `pip install openenv[kubernetes]`."
59
+ ) from exc
60
+
61
+
62
+ def _dns_label(value: str, *, max_length: int, what: str) -> str:
63
+ """Return *value* as a DNS-1123 label, or raise ``ValueError``.
64
+
65
+ Namespace and runtime class names are validated, not rewritten: rewriting
66
+ them would target a different object than the one the caller named.
67
+ """
68
+ if not isinstance(value, str) or not _DNS_LABEL.fullmatch(value):
69
+ raise ValueError(
70
+ f"{what} must be a DNS-1123 label: lowercase alphanumeric "
71
+ "characters or '-', starting and ending with an alphanumeric."
72
+ )
73
+ if not 1 <= len(value) <= max_length:
74
+ raise ValueError(f"{what} must be 1 to {max_length} characters.")
75
+ return value
76
+
77
+
78
+ def _slug(image: str) -> str:
79
+ """DNS-1123 slug from an image reference. Raises if nothing usable remains."""
80
+ raw = image.split("/")[-1].split("@")[0].split(":")[0]
81
+ cleaned = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-")
82
+ cleaned = re.sub(r"-{2,}", "-", cleaned)[:_SLUG_MAX].strip("-")
83
+ if not cleaned or not _DNS_LABEL.fullmatch(cleaned):
84
+ raise ValueError(
85
+ "image does not yield a valid Kubernetes name. "
86
+ "Use an image reference with an alphanumeric name."
87
+ )
88
+ return cleaned
89
+
90
+
91
+ def _resource_name(image: str) -> str:
92
+ suffix = f"{int(time.time() * 1000)}-{secrets.token_hex(2)}"
93
+ name = f"{_NAME_PREFIX}{_slug(image)}-{suffix}"
94
+ if len(name) > 63 or not _DNS_LABEL.fullmatch(name):
95
+ raise ValueError("generated Kubernetes name is not a valid DNS-1123 label.")
96
+ return name
97
+
98
+
99
+ def _label_key(key: str) -> str:
100
+ if not isinstance(key, str) or len(key) > 253:
101
+ raise ValueError(
102
+ "Kubernetes label keys must be strings of at most 253 characters."
103
+ )
104
+ prefix, sep, name = key.rpartition("/")
105
+ if not _LABEL_NAME.fullmatch(name):
106
+ raise ValueError(f"Invalid Kubernetes label key {key!r}.")
107
+ if sep and (len(prefix) > 253 or not _dns_subdomain(prefix)):
108
+ raise ValueError(f"Invalid Kubernetes label key prefix {prefix!r}.")
109
+ return key
110
+
111
+
112
+ def _dns_subdomain(value: str) -> bool:
113
+ if not value or len(value) > 253:
114
+ return False
115
+ return all(_DNS_LABEL.fullmatch(part) for part in value.split("."))
116
+
117
+
118
+ def _label_value(value: str) -> str:
119
+ if not isinstance(value, str) or not _LABEL_VALUE.fullmatch(value):
120
+ raise ValueError(
121
+ "Kubernetes label values must be 63 characters or fewer and contain "
122
+ "only alphanumeric characters, '-', '_' or '.'."
123
+ )
124
+ return value
125
+
126
+
127
+ def _ownership_labels(name: str) -> dict[str, str]:
128
+ return {
129
+ "app.kubernetes.io/name": "openenv",
130
+ "app.kubernetes.io/instance": name,
131
+ "app.kubernetes.io/managed-by": "openenv",
132
+ "app.kubernetes.io/part-of": "openenv",
133
+ "app.kubernetes.io/component": "environment",
134
+ }
135
+
136
+
137
+ def _merged_labels(name: str, extra: Optional[Mapping[str, str]]) -> dict[str, str]:
138
+ labels: dict[str, str] = {}
139
+ if extra:
140
+ if not isinstance(extra, Mapping):
141
+ raise ValueError("labels must be a mapping of strings.")
142
+ for key, value in extra.items():
143
+ labels[_label_key(key)] = _label_value(value)
144
+ labels.update(_ownership_labels(name))
145
+ return labels
146
+
147
+
148
+ def _safe_reason(reason: Optional[str]) -> Optional[str]:
149
+ """Keep kubelet reason codes. Drop anything else so API text cannot leak."""
150
+ if isinstance(reason, str) and _SAFE_REASON.fullmatch(reason):
151
+ return reason
152
+ return None
153
+
154
+
155
+ class _NamespaceMissing(RuntimeError):
156
+ """Creating a namespaced object returned 404: the namespace is absent."""
157
+
158
+
159
+ class _CreateConflict(RuntimeError):
160
+ """Creating a namespaced object returned 409: the name is already taken."""
161
+
162
+
163
+ class _TransientStatusError(RuntimeError):
164
+ """A Pod status read can be retried within the readiness deadline."""
165
+
166
+
167
+ def _incluster_base_url(name: str, namespace: str, port: int) -> str:
168
+ # *name* and *namespace* are already DNS-1123 labels and *port* is an int,
169
+ # so this cannot be steered by a status field from the API server.
170
+ # ``name.namespace`` is completed by the Pod DNS search list
171
+ # (``svc.<cluster-domain>``), which works when the cluster domain is not
172
+ # ``cluster.local``.
173
+ return f"http://{name}.{namespace}:{port}"
174
+
175
+
176
+ def _owned_by_provider(labels: Any, name: str) -> bool:
177
+ if not isinstance(labels, Mapping):
178
+ return False
179
+ return (
180
+ labels.get("app.kubernetes.io/managed-by") == "openenv"
181
+ and labels.get("app.kubernetes.io/instance") == name
182
+ )
183
+
184
+
185
+ class _DefaultKubernetesAdapter:
186
+ """Thin adapter over the official ``kubernetes`` client.
187
+
188
+ The provider talks to this private adapter instead of spreading SDK details
189
+ through its own logic; tests inject a duck-typed fake in its place.
190
+ """
191
+
192
+ def __init__(
193
+ self,
194
+ *,
195
+ namespace: str,
196
+ kubeconfig: Optional[str],
197
+ context: Optional[str],
198
+ ):
199
+ try:
200
+ from kubernetes import client, config
201
+ from kubernetes.client.exceptions import ApiException
202
+ except ImportError as exc:
203
+ _raise_install_error(exc)
204
+
205
+ self._client = client
206
+ self._ApiException = ApiException
207
+ self._namespace = namespace
208
+ self._load_config(config, kubeconfig=kubeconfig, context=context)
209
+ configuration = client.Configuration.get_default_copy()
210
+ # Readiness owns the retry deadline; SDK retries would multiply it.
211
+ configuration.retries = 0
212
+ self._api = client.CoreV1Api(client.ApiClient(configuration=configuration))
213
+
214
+ def _load_config(
215
+ self, config: Any, *, kubeconfig: Optional[str], context: Optional[str]
216
+ ) -> None:
217
+ if kubeconfig is not None or context is not None:
218
+ config.load_kube_config(config_file=kubeconfig, context=context)
219
+ return
220
+ try:
221
+ config.load_incluster_config()
222
+ except config.ConfigException:
223
+ config.load_kube_config()
224
+
225
+ def _api_error(self, exc: Exception, action: str, *, missing_ok: bool) -> None:
226
+ status = getattr(exc, "status", None)
227
+ if missing_ok and status == 404:
228
+ return
229
+ if status == 409:
230
+ raise _CreateConflict(
231
+ f"Kubernetes {action} name is already in use"
232
+ ) from None
233
+ if status == 404 and action.startswith("create "):
234
+ raise _NamespaceMissing(
235
+ "Kubernetes namespace does not exist. "
236
+ "KubernetesProvider does not create namespaces."
237
+ ) from None
238
+ # The API body can echo object contents. Do not chain it into the error.
239
+ raise RuntimeError(f"Failed to {action} Kubernetes resource") from None
240
+
241
+ def create_pod(self, manifest: Mapping[str, Any]) -> None:
242
+ try:
243
+ self._api.create_namespaced_pod(self._namespace, self._pod(manifest))
244
+ except self._ApiException as exc:
245
+ self._api_error(exc, "create Pod", missing_ok=False)
246
+
247
+ def create_service(self, manifest: Mapping[str, Any]) -> None:
248
+ try:
249
+ self._api.create_namespaced_service(
250
+ self._namespace, self._service(manifest)
251
+ )
252
+ except self._ApiException as exc:
253
+ self._api_error(exc, "create Service", missing_ok=False)
254
+
255
+ def pod_labels(self, name: str) -> Optional[dict[str, str]]:
256
+ """Return Pod labels, or ``None`` when the Pod does not exist."""
257
+ return self._resource_labels(name, self._api.read_namespaced_pod, "read Pod")
258
+
259
+ def service_labels(self, name: str) -> Optional[dict[str, str]]:
260
+ """Return Service labels, or ``None`` when the Service does not exist."""
261
+ return self._resource_labels(
262
+ name, self._api.read_namespaced_service, "read Service"
263
+ )
264
+
265
+ def _resource_labels(
266
+ self, name: str, read: Any, action: str
267
+ ) -> Optional[dict[str, str]]:
268
+ try:
269
+ obj = read(name, self._namespace)
270
+ except self._ApiException as exc:
271
+ if getattr(exc, "status", None) == 404:
272
+ return None
273
+ self._api_error(exc, action, missing_ok=False)
274
+ raise RuntimeError(f"Failed to {action} Kubernetes resource") from None
275
+ metadata = getattr(obj, "metadata", None)
276
+ labels = getattr(metadata, "labels", None) if metadata is not None else None
277
+ if not isinstance(labels, Mapping):
278
+ return {}
279
+ return {str(key): str(value) for key, value in labels.items()}
280
+
281
+ def delete_pod(self, name: str) -> None:
282
+ try:
283
+ self._api.delete_namespaced_pod(name, self._namespace)
284
+ except self._ApiException as exc:
285
+ self._api_error(exc, "delete Pod", missing_ok=True)
286
+
287
+ def delete_service(self, name: str) -> None:
288
+ try:
289
+ self._api.delete_namespaced_service(name, self._namespace)
290
+ except self._ApiException as exc:
291
+ self._api_error(exc, "delete Service", missing_ok=True)
292
+
293
+ def pod_status(
294
+ self, name: str, timeout_s: float = 30.0
295
+ ) -> dict[str, Optional[str]]:
296
+ from urllib3.exceptions import HTTPError
297
+
298
+ try:
299
+ # Older supported SDKs ignore a float timeout. Split the budget
300
+ # between connect and read using their supported tuple form.
301
+ pod = self._api.read_namespaced_pod(
302
+ name,
303
+ self._namespace,
304
+ _request_timeout=(timeout_s / 2, timeout_s / 2),
305
+ )
306
+ except Exception as exc:
307
+ status = getattr(exc, "status", None)
308
+ if (
309
+ isinstance(exc, (TimeoutError, HTTPError))
310
+ or status == 429
311
+ or (isinstance(status, int) and 500 <= status < 600)
312
+ ):
313
+ raise _TransientStatusError(
314
+ "Kubernetes Pod status read failed"
315
+ ) from None
316
+ self._api_error(exc, "read Pod", missing_ok=False)
317
+ raise RuntimeError("Failed to read Kubernetes Pod") from None
318
+ status = getattr(pod, "status", None)
319
+ phase = getattr(status, "phase", None) if status is not None else None
320
+ reason = None
321
+ if status is not None:
322
+ for container in status.container_statuses or []:
323
+ state = getattr(container, "state", None)
324
+ waiting = getattr(state, "waiting", None) if state is not None else None
325
+ terminated = (
326
+ getattr(state, "terminated", None) if state is not None else None
327
+ )
328
+ if waiting is not None and getattr(waiting, "reason", None):
329
+ reason = waiting.reason
330
+ elif terminated is not None and getattr(terminated, "reason", None):
331
+ reason = terminated.reason
332
+ return {"phase": phase or "Unknown", "reason": reason}
333
+
334
+ def _metadata(self, meta: Mapping[str, Any]) -> Any:
335
+ return self._client.V1ObjectMeta(
336
+ name=meta["name"],
337
+ namespace=meta["namespace"],
338
+ labels=dict(meta["labels"]),
339
+ )
340
+
341
+ def _pod(self, manifest: Mapping[str, Any]) -> Any:
342
+ spec = manifest["spec"]
343
+ container = spec["containers"][0]
344
+ container_kwargs: dict[str, Any] = {
345
+ "name": container["name"],
346
+ "image": container["image"],
347
+ "ports": [
348
+ self._client.V1ContainerPort(
349
+ name=port["name"], container_port=port["container_port"]
350
+ )
351
+ for port in container["ports"]
352
+ ],
353
+ }
354
+ if container.get("env"):
355
+ container_kwargs["env"] = [
356
+ self._client.V1EnvVar(name=item["name"], value=item["value"])
357
+ for item in container["env"]
358
+ ]
359
+ resources = container.get("resources")
360
+ if resources:
361
+ container_kwargs["resources"] = self._client.V1ResourceRequirements(
362
+ requests=resources.get("requests"),
363
+ limits=resources.get("limits"),
364
+ )
365
+ pod_kwargs: dict[str, Any] = {
366
+ "restart_policy": spec["restart_policy"],
367
+ "automount_service_account_token": spec["automount_service_account_token"],
368
+ "containers": [self._client.V1Container(**container_kwargs)],
369
+ }
370
+ if spec.get("runtime_class_name"):
371
+ pod_kwargs["runtime_class_name"] = spec["runtime_class_name"]
372
+ if spec.get("service_account_name"):
373
+ pod_kwargs["service_account_name"] = spec["service_account_name"]
374
+ if spec.get("image_pull_secrets"):
375
+ pod_kwargs["image_pull_secrets"] = [
376
+ self._client.V1LocalObjectReference(name=secret)
377
+ for secret in spec["image_pull_secrets"]
378
+ ]
379
+ return self._client.V1Pod(
380
+ metadata=self._metadata(manifest["metadata"]),
381
+ spec=self._client.V1PodSpec(**pod_kwargs),
382
+ )
383
+
384
+ def _service(self, manifest: Mapping[str, Any]) -> Any:
385
+ spec = manifest["spec"]
386
+ port = spec["ports"][0]
387
+ return self._client.V1Service(
388
+ metadata=self._metadata(manifest["metadata"]),
389
+ spec=self._client.V1ServiceSpec(
390
+ selector=dict(spec["selector"]),
391
+ ports=[
392
+ self._client.V1ServicePort(
393
+ name=port["name"],
394
+ port=port["port"],
395
+ target_port=port["target_port"],
396
+ protocol=port["protocol"],
397
+ )
398
+ ],
399
+ ),
400
+ )
401
+
402
+
403
+ class KubernetesProvider(ContainerProvider):
404
+ """
405
+ Container provider that runs one environment as one Pod and one Service.
406
+
407
+ ``start_container`` returns ``http://{name}.{namespace}:{port}``. That
408
+ address is reachable only from inside the cluster: Pod DNS search expands
409
+ it under ``svc.<cluster-domain>``. It is plaintext on purpose: in-cluster
410
+ HTTP is the connectivity decision for this provider. Cloud sandbox
411
+ providers keep their own HTTPS requirement.
412
+
413
+ The namespace must already exist. This provider does not create namespaces,
414
+ Deployments, Ingress objects, or port-forwards.
415
+
416
+ Only one Pod is active per provider. Calling ``start_container`` again
417
+ before ``stop_container()`` / ``close()`` raises ``RuntimeError`` rather
418
+ than orphaning the running Pod. A failed start deletes a resource only
419
+ after its OpenEnv ownership labels match. When a create response is lost
420
+ and that read fails, the resource stays unconfirmed: ``stop_container``
421
+ reads the labels again and deletes only on a match. ``stop_container`` is
422
+ safe to call more than once.
423
+
424
+ The Pod does not mount a service-account token unless
425
+ ``automount_service_account_token=True`` is passed to ``start_container``.
426
+
427
+ Example:
428
+ ```python
429
+ from openenv.core.containers.runtime.kubernetes_provider import (
430
+ KubernetesProvider,
431
+ )
432
+
433
+ provider = KubernetesProvider(namespace="openenv")
434
+ base_url = provider.start_container("echo-env:latest")
435
+ provider.wait_for_ready(base_url)
436
+ provider.stop_container()
437
+ ```
438
+ """
439
+
440
+ def __init__(
441
+ self,
442
+ *,
443
+ image: str | None = None,
444
+ env_vars: dict[str, str] | None = None,
445
+ namespace: str = _DEFAULT_NAMESPACE,
446
+ kubeconfig: str | None = None,
447
+ context: str | None = None,
448
+ _adapter: Any = None,
449
+ ):
450
+ """
451
+ Args:
452
+ image (`str`, *optional*):
453
+ Registry image used when ``start_container()`` is called
454
+ without an image.
455
+ env_vars (`dict`, *optional*):
456
+ Environment variables used when ``start_container()`` is called
457
+ without ``env_vars``.
458
+ namespace (`str`, *optional*, defaults to ``"default"``):
459
+ Existing namespace for the Pod and Service. Not created.
460
+ kubeconfig (`str`, *optional*):
461
+ Kubeconfig path. When omitted, in-cluster config is tried and
462
+ then the default kubeconfig.
463
+ context (`str`, *optional*):
464
+ Kubeconfig context. Implies kubeconfig loading rather than
465
+ in-cluster config.
466
+ """
467
+ self._image = image
468
+ self._env_vars = env_vars
469
+ self._namespace = _dns_label(namespace, max_length=63, what="namespace")
470
+ self._name: str | None = None
471
+ self._base_url: str | None = None
472
+ self._service_port: int | None = None
473
+ self._pod_created = False
474
+ self._service_created = False
475
+ self._pod_unconfirmed = False
476
+ self._service_unconfirmed = False
477
+
478
+ if _adapter is None:
479
+ self._adapter: Any = _DefaultKubernetesAdapter(
480
+ namespace=self._namespace,
481
+ kubeconfig=kubeconfig,
482
+ context=context,
483
+ )
484
+ else:
485
+ self._adapter = _adapter
486
+
487
+ @property
488
+ def base_url(self) -> str:
489
+ """URL returned by the last successful ``start_container``."""
490
+ if self._base_url is None:
491
+ raise RuntimeError(
492
+ "KubernetesProvider has no active base_url. Start the provider "
493
+ "before reading base_url."
494
+ )
495
+ return self._base_url
496
+
497
+ def start_container(
498
+ self,
499
+ image: str | None = None,
500
+ port: int | None = None,
501
+ env_vars: dict[str, str] | None = None,
502
+ **kwargs: Any,
503
+ ) -> str:
504
+ """
505
+ Create one Pod and one Service and return the in-cluster base URL.
506
+
507
+ Args:
508
+ image (`str`, *optional*):
509
+ Registry image. May be omitted when supplied to the constructor.
510
+ port (`int`, *optional*):
511
+ Service port. Defaults to 8000. The container always listens
512
+ on 8000, matching ``LocalDockerProvider``.
513
+ env_vars (`dict`, *optional*):
514
+ Environment variables for the container. Replaces constructor
515
+ ``env_vars`` when passed, including an empty dict.
516
+ **kwargs:
517
+ ``resources``, ``runtime_class_name``, ``image_pull_secrets``,
518
+ ``labels``, ``service_account_name``, and
519
+ ``automount_service_account_token``. Unknown keys raise
520
+ ``ValueError``.
521
+
522
+ Returns:
523
+ `str`: ``http://{name}.{namespace}:{port}``.
524
+ """
525
+ if self._has_tracked_resources() or self._base_url is not None:
526
+ raise RuntimeError(
527
+ "KubernetesProvider already has an active Pod. Call "
528
+ "stop_container() (or close()) before starting another — a "
529
+ "second start would orphan the running Pod."
530
+ )
531
+
532
+ unknown = set(kwargs) - _START_KWARGS
533
+ if unknown:
534
+ raise ValueError(
535
+ f"Unsupported kwargs for KubernetesProvider: {sorted(unknown)}"
536
+ )
537
+
538
+ effective_image = image if image is not None else self._image
539
+ if not isinstance(effective_image, str) or not effective_image:
540
+ raise ValueError(
541
+ "KubernetesProvider requires an image. Pass it to the "
542
+ "constructor or start_container()."
543
+ )
544
+ service_port = _CONTAINER_PORT if port is None else port
545
+ if isinstance(service_port, bool) or not isinstance(service_port, int):
546
+ raise ValueError("port must be an integer.")
547
+ if not 1 <= service_port <= 65535:
548
+ raise ValueError("port must be between 1 and 65535.")
549
+
550
+ effective_env = self._env_vars if env_vars is None else env_vars
551
+ env_list = _env_list(effective_env)
552
+ resources = _resources(kwargs.get("resources"))
553
+ runtime_class_name = _optional_dns_subdomain(
554
+ kwargs.get("runtime_class_name"), what="runtime_class_name"
555
+ )
556
+ service_account_name = _optional_dns_subdomain(
557
+ kwargs.get("service_account_name"), what="service_account_name"
558
+ )
559
+ image_pull_secrets = _secret_names(kwargs.get("image_pull_secrets"))
560
+ automount = kwargs.get("automount_service_account_token", False)
561
+ if not isinstance(automount, bool):
562
+ raise ValueError("automount_service_account_token must be a bool.")
563
+
564
+ name = _resource_name(effective_image)
565
+ labels = _merged_labels(name, kwargs.get("labels"))
566
+ self._name = name
567
+ self._service_port = service_port
568
+ try:
569
+ self._adapter.create_pod(
570
+ _pod_manifest(
571
+ name=name,
572
+ namespace=self._namespace,
573
+ labels=labels,
574
+ image=effective_image,
575
+ env_list=env_list,
576
+ resources=resources,
577
+ runtime_class_name=runtime_class_name,
578
+ service_account_name=service_account_name,
579
+ image_pull_secrets=image_pull_secrets,
580
+ automount_service_account_token=automount,
581
+ )
582
+ )
583
+ self._pod_created = True
584
+ self._adapter.create_service(
585
+ _service_manifest(
586
+ name=name,
587
+ namespace=self._namespace,
588
+ labels=labels,
589
+ service_port=service_port,
590
+ )
591
+ )
592
+ self._service_created = True
593
+ except BaseException as exc:
594
+ # Interrupts can also arrive after the API created a resource.
595
+ # A cleanup failure must not mask the original error.
596
+ try:
597
+ self._cleanup_after_failed_start(exc)
598
+ except Exception:
599
+ pass
600
+ raise
601
+
602
+ self._base_url = _incluster_base_url(name, self._namespace, service_port)
603
+ return self._base_url
604
+
605
+ def _cleanup_after_failed_start(self, exc: BaseException) -> None:
606
+ """Delete objects this start may have created.
607
+
608
+ A 409 is someone else's name, and a 404 means the namespace is
609
+ missing, so those do not probe. Any other create error may mean the
610
+ API server applied the object and the client lost the response. Only
611
+ the resource whose create was attempted is checked. It is deleted only
612
+ when the OpenEnv ownership labels match. A failed read is recorded as
613
+ unconfirmed, which is not the same as a successful create: a later
614
+ ``stop_container()`` reads the labels again before deleting.
615
+ """
616
+ uncertain = not isinstance(exc, (_CreateConflict, _NamespaceMissing))
617
+ # Service create runs only after Pod create has succeeded.
618
+ service_was_attempted = self._pod_created
619
+ self._release("pod", uncertain=uncertain)
620
+ self._release("service", uncertain=uncertain and service_was_attempted)
621
+ if not self._has_tracked_resources():
622
+ self._name = None
623
+ self._base_url = None
624
+ self._service_port = None
625
+
626
+ def _release(self, kind: str, *, uncertain: bool) -> None:
627
+ if self._created(kind):
628
+ self._delete_tracked(kind)
629
+ return
630
+ if not uncertain:
631
+ return
632
+ owned = self._lookup_owned(kind)
633
+ if owned is None:
634
+ self._set_unconfirmed(kind, True)
635
+ return
636
+ if not owned:
637
+ return
638
+ self._set_created(kind, True)
639
+ self._delete_tracked(kind)
640
+
641
+ def _lookup_owned(self, kind: str) -> Optional[bool]:
642
+ """Return whether *kind* at ``_name`` is ours.
643
+
644
+ ``None`` means the read itself failed. Callers record that as
645
+ unconfirmed. They do not treat it as a confirmed create.
646
+ """
647
+ if self._name is None:
648
+ return False
649
+ try:
650
+ if kind == "pod":
651
+ labels = self._adapter.pod_labels(self._name)
652
+ else:
653
+ labels = self._adapter.service_labels(self._name)
654
+ except Exception:
655
+ return None
656
+ if labels is None:
657
+ return False
658
+ return _owned_by_provider(labels, self._name)
659
+
660
+ def _delete_tracked(self, kind: str) -> None:
661
+ """Delete a resource already known to be ours.
662
+
663
+ A failed delete stays confirmed so ``stop_container()`` can retry it.
664
+ """
665
+ if self._name is None:
666
+ return
667
+ try:
668
+ if kind == "pod":
669
+ self._adapter.delete_pod(self._name)
670
+ else:
671
+ self._adapter.delete_service(self._name)
672
+ except Exception:
673
+ self._set_created(kind, True)
674
+ return
675
+ self._set_created(kind, False)
676
+
677
+ def _created(self, kind: str) -> bool:
678
+ if kind == "pod":
679
+ return self._pod_created
680
+ return self._service_created
681
+
682
+ def _set_created(self, kind: str, created: bool) -> None:
683
+ if kind == "pod":
684
+ self._pod_created = created
685
+ else:
686
+ self._service_created = created
687
+
688
+ def _unconfirmed(self, kind: str) -> bool:
689
+ if kind == "pod":
690
+ return self._pod_unconfirmed
691
+ return self._service_unconfirmed
692
+
693
+ def _set_unconfirmed(self, kind: str, unconfirmed: bool) -> None:
694
+ if kind == "pod":
695
+ self._pod_unconfirmed = unconfirmed
696
+ else:
697
+ self._service_unconfirmed = unconfirmed
698
+
699
+ def _has_tracked_resources(self) -> bool:
700
+ return (
701
+ self._pod_created
702
+ or self._service_created
703
+ or self._pod_unconfirmed
704
+ or self._service_unconfirmed
705
+ )
706
+
707
+ def stop_container(self) -> None:
708
+ """Delete the Pod and Service this provider created.
709
+
710
+ Safe when nothing was started and safe to call twice. A 404 from the
711
+ API is treated as already deleted. A confirmed resource is deleted by
712
+ name. An unconfirmed one is deleted only after a fresh ownership-label
713
+ match. If that read fails, the unconfirmed state is kept for another
714
+ retry. Objects this instance does not own are left in place, including
715
+ a name that was already taken.
716
+ """
717
+ if self._name is None and not self._has_tracked_resources():
718
+ self._base_url = None
719
+ self._service_port = None
720
+ return
721
+
722
+ errors: list[str] = []
723
+ self._stop_kind("pod", errors)
724
+ self._stop_kind("service", errors)
725
+ if errors:
726
+ raise RuntimeError(
727
+ "Failed to delete Kubernetes resources created by this provider. "
728
+ "Call stop_container() again to retry."
729
+ )
730
+ self._name = None
731
+ self._base_url = None
732
+ self._service_port = None
733
+
734
+ def _stop_kind(self, kind: str, errors: list[str]) -> None:
735
+ if self._name is None:
736
+ return
737
+ if self._unconfirmed(kind):
738
+ owned = self._lookup_owned(kind)
739
+ if owned is None:
740
+ errors.append(kind)
741
+ return
742
+ self._set_unconfirmed(kind, False)
743
+ if not owned:
744
+ return
745
+ self._set_created(kind, True)
746
+ if not self._created(kind):
747
+ return
748
+ try:
749
+ if kind == "pod":
750
+ self._adapter.delete_pod(self._name)
751
+ else:
752
+ self._adapter.delete_service(self._name)
753
+ except Exception:
754
+ errors.append(kind)
755
+ return
756
+ self._set_created(kind, False)
757
+
758
+ def close(self) -> None:
759
+ """Stop the active Pod and Service.
760
+
761
+ Overrides the base no-op so a caller holding a bare ``ContainerProvider``
762
+ reference can release the Pod polymorphically (also invoked on
763
+ context-manager exit). Equivalent to ``stop_container()``.
764
+ """
765
+ self.stop_container()
766
+
767
+ def __exit__(self, exc_type, exc, tb) -> None:
768
+ try:
769
+ self.close()
770
+ except Exception:
771
+ if exc_type is None:
772
+ raise
773
+
774
+ def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None:
775
+ """
776
+ Wait until the Pod is Running and ``GET /health`` returns 200.
777
+
778
+ A Failed or Succeeded Pod raises immediately instead of consuming the
779
+ timeout. The URL is not included in errors: this method only polls the
780
+ Service URL returned by ``start_container``.
781
+
782
+ Args:
783
+ base_url (`str`):
784
+ URL returned by ``start_container()``.
785
+ timeout_s (`float`, *optional*, defaults to `120.0`):
786
+ Maximum seconds to wait. Image pulls are slower than local Docker.
787
+
788
+ Raises:
789
+ TimeoutError: If the Pod does not become ready in time.
790
+ RuntimeError: If the Pod has already ended.
791
+ ValueError: If ``base_url`` is not the URL this provider returned.
792
+ """
793
+ import requests
794
+
795
+ expected = self._base_url
796
+ if expected is None or not isinstance(base_url, str):
797
+ raise ValueError(
798
+ "base_url does not match the in-cluster Service URL for this provider."
799
+ )
800
+ if base_url.rstrip("/") != expected:
801
+ raise ValueError(
802
+ "base_url does not match the in-cluster Service URL for this provider."
803
+ )
804
+ if isinstance(timeout_s, bool) or not isinstance(timeout_s, (int, float)):
805
+ raise ValueError("timeout_s must be a number.")
806
+ if timeout_s < 0:
807
+ raise ValueError("timeout_s must be non-negative.")
808
+
809
+ health_url = f"{expected}/health"
810
+ proxies = {"http": "", "https": "", "all": ""}
811
+ deadline = time.monotonic() + timeout_s
812
+ while (remaining := deadline - time.monotonic()) > 0:
813
+ try:
814
+ phase, reason = self._phase(remaining)
815
+ except _TransientStatusError:
816
+ phase, reason = "Unknown", None
817
+ if phase in ("Failed", "Succeeded"):
818
+ raise RuntimeError(self._ended_message(phase, reason))
819
+ remaining = deadline - time.monotonic()
820
+ if remaining <= 0:
821
+ break
822
+ if phase == "Running":
823
+ try:
824
+ response = requests.get(
825
+ health_url, timeout=min(2.0, remaining), proxies=proxies
826
+ )
827
+ if response.status_code == 200:
828
+ return
829
+ except requests.RequestException:
830
+ pass
831
+ time.sleep(min(0.5, max(0.0, deadline - time.monotonic())))
832
+
833
+ raise TimeoutError(f"Kubernetes Pod did not become ready within {timeout_s}s.")
834
+
835
+ def _phase(self, timeout_s: float) -> tuple[str, Optional[str]]:
836
+ if self._name is None:
837
+ raise RuntimeError(
838
+ "KubernetesProvider has no active Pod. Start the provider "
839
+ "before waiting for readiness."
840
+ )
841
+ status = self._adapter.pod_status(self._name, timeout_s=timeout_s)
842
+ phase = status.get("phase") if isinstance(status, Mapping) else None
843
+ reason = status.get("reason") if isinstance(status, Mapping) else None
844
+ if not isinstance(phase, str) or not _SAFE_REASON.fullmatch(phase):
845
+ phase = "Unknown"
846
+ return phase, _safe_reason(reason if isinstance(reason, str) else None)
847
+
848
+ def _ended_message(self, phase: str, reason: Optional[str]) -> str:
849
+ if reason is None:
850
+ return (
851
+ f"Kubernetes Pod entered phase {phase} before it became ready. "
852
+ "The Service URL and Pod status message are omitted."
853
+ )
854
+ return (
855
+ f"Kubernetes Pod entered phase {phase} ({reason}) before it became "
856
+ "ready. The Service URL and Pod status message are omitted."
857
+ )
858
+
859
+
860
+ def _env_list(env_vars: Optional[Mapping[str, str]]) -> list[dict[str, str]]:
861
+ if env_vars is None:
862
+ return []
863
+ if not isinstance(env_vars, Mapping):
864
+ raise ValueError("env_vars must be a mapping of strings.")
865
+ items: list[dict[str, str]] = []
866
+ for key, value in env_vars.items():
867
+ if not isinstance(key, str) or not isinstance(value, str):
868
+ raise ValueError("env_vars keys and values must be strings.")
869
+ items.append({"name": key, "value": value})
870
+ return items
871
+
872
+
873
+ def _resources(resources: Any) -> Optional[dict[str, dict[str, str]]]:
874
+ if resources is None:
875
+ return None
876
+ if not isinstance(resources, Mapping):
877
+ raise ValueError("resources must be a mapping of requests and limits.")
878
+ unknown = set(resources) - {"requests", "limits"}
879
+ if unknown:
880
+ raise ValueError(
881
+ f"Unsupported resources keys for KubernetesProvider: {sorted(unknown)}"
882
+ )
883
+ parsed: dict[str, dict[str, str]] = {}
884
+ for section in ("requests", "limits"):
885
+ values = resources.get(section)
886
+ if values is None:
887
+ continue
888
+ if not isinstance(values, Mapping) or not values:
889
+ raise ValueError(f"resources.{section} must be a non-empty mapping.")
890
+ parsed[section] = {}
891
+ for key, value in values.items():
892
+ if not isinstance(key, str) or not isinstance(value, str) or not value:
893
+ raise ValueError(
894
+ f"resources.{section} keys and values must be non-empty strings."
895
+ )
896
+ parsed[section][key] = value
897
+ return parsed or None
898
+
899
+
900
+ def _optional_dns_subdomain(value: Any, *, what: str) -> Optional[str]:
901
+ if value is None:
902
+ return None
903
+ if not isinstance(value, str) or not _dns_subdomain(value):
904
+ raise ValueError(
905
+ f"{what} must be a DNS-1123 subdomain: lowercase labels separated by '.'."
906
+ )
907
+ return value
908
+
909
+
910
+ def _secret_names(value: Any) -> list[str]:
911
+ if value is None:
912
+ return []
913
+ if isinstance(value, str) or not isinstance(value, (list, tuple)):
914
+ raise ValueError("image_pull_secrets must be a list of secret names.")
915
+ names: list[str] = []
916
+ for item in value:
917
+ if not isinstance(item, str) or not _dns_subdomain(item):
918
+ raise ValueError("image_pull_secrets entries must be DNS-1123 subdomains.")
919
+ names.append(item)
920
+ return names
921
+
922
+
923
+ def _pod_manifest(
924
+ *,
925
+ name: str,
926
+ namespace: str,
927
+ labels: dict[str, str],
928
+ image: str,
929
+ env_list: list[dict[str, str]],
930
+ resources: Optional[dict[str, dict[str, str]]],
931
+ runtime_class_name: Optional[str],
932
+ service_account_name: Optional[str],
933
+ image_pull_secrets: list[str],
934
+ automount_service_account_token: bool,
935
+ ) -> dict[str, Any]:
936
+ container: dict[str, Any] = {
937
+ "name": _CONTAINER_NAME,
938
+ "image": image,
939
+ "ports": [{"name": "http", "container_port": _CONTAINER_PORT}],
940
+ }
941
+ if env_list:
942
+ container["env"] = env_list
943
+ if resources:
944
+ container["resources"] = resources
945
+ spec: dict[str, Any] = {
946
+ "restart_policy": "Never",
947
+ "automount_service_account_token": automount_service_account_token,
948
+ "containers": [container],
949
+ }
950
+ if runtime_class_name:
951
+ spec["runtime_class_name"] = runtime_class_name
952
+ if service_account_name:
953
+ spec["service_account_name"] = service_account_name
954
+ if image_pull_secrets:
955
+ spec["image_pull_secrets"] = image_pull_secrets
956
+ return {
957
+ "metadata": {"name": name, "namespace": namespace, "labels": labels},
958
+ "spec": spec,
959
+ }
960
+
961
+
962
+ def _service_manifest(
963
+ *,
964
+ name: str,
965
+ namespace: str,
966
+ labels: dict[str, str],
967
+ service_port: int,
968
+ ) -> dict[str, Any]:
969
+ return {
970
+ "metadata": {"name": name, "namespace": namespace, "labels": labels},
971
+ "spec": {
972
+ "selector": {_SELECTOR_KEY: name},
973
+ "ports": [
974
+ {
975
+ "name": "http",
976
+ "port": service_port,
977
+ "target_port": _CONTAINER_PORT,
978
+ "protocol": "TCP",
979
+ }
980
+ ],
981
+ },
982
+ }
983
+
984
+
985
+ __all__ = ["KubernetesProvider"]
src/core/containers/runtime/modal_provider.py CHANGED
@@ -3,30 +3,23 @@
3
  """
4
  Modal container provider for running OpenEnv environments in Modal sandboxes.
5
 
6
- Requires the ``modal`` SDK: ``pip install modal>=1.4``
7
 
8
  The provider boots an OpenEnv server inside a Modal sandbox, exposes it on an
9
  encrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects to
10
  over ``wss://``.
11
-
12
- Supports both the stable Sandbox API (``modal.Sandbox.create``) and the beta
13
- Sandbox v2 API (``modal.Sandbox._experimental_create``). Sandbox v2 is opt-in
14
- via ``use_sandbox_v2=True`` because it is an experimental, private SDK feature;
15
- see https://modal.com/docs/guide/sandbox-v2 .
16
  """
17
 
18
  from __future__ import annotations
19
 
20
- import logging
21
  import shlex
22
  import time
 
23
  from typing import Any, Dict, Optional
24
 
25
  from ._server_config import parse_dockerfile_cmd, parse_openenv_app_field
26
  from .providers import ContainerProvider
27
 
28
- logger = logging.getLogger(__name__)
29
-
30
  _DEFAULT_MODAL_PORT = 8000
31
 
32
  # Modal's default per-container resource requests. We pass configured cpu/memory
@@ -58,28 +51,14 @@ class _DefaultModalAdapter:
58
  """Thin adapter over the ``modal`` SDK.
59
 
60
  The provider talks to this private adapter instead of spreading SDK details
61
- through its own logic; tests inject a duck-typed fake in its place. Keeping
62
- the SDK surface here also localizes the feature check for the private
63
- Sandbox v2 (``_experimental_create``) API.
64
  """
65
 
66
- def __init__(self, *, app_name: str, use_sandbox_v2: bool):
67
  import modal
68
 
69
  self._modal = modal
70
  self._app_name = app_name
71
- self._use_sandbox_v2 = use_sandbox_v2
72
-
73
- # Sandbox v2 rides on a private SDK entry point that is not present in
74
- # every modal release. Fail fast at construction with clear guidance
75
- # rather than at start_container time with an AttributeError.
76
- if use_sandbox_v2 and not hasattr(modal.Sandbox, "_experimental_create"):
77
- raise RuntimeError(
78
- "use_sandbox_v2=True requires modal.Sandbox._experimental_create, "
79
- "which is not available in the installed modal SDK. Upgrade modal, "
80
- "or use the stable Sandbox API (use_sandbox_v2=False). Sandbox v2 "
81
- "is an experimental feature; contact support@modal.com for access."
82
- )
83
 
84
  def image_from_registry(self, tag: str) -> Any:
85
  return self._modal.Image.from_registry(tag)
@@ -111,10 +90,6 @@ class _DefaultModalAdapter:
111
 
112
  # The sandbox is started with a keep-alive entrypoint; the server
113
  # command is launched via exec afterwards (see ModalProvider).
114
- if self._use_sandbox_v2:
115
- return self._modal.Sandbox._experimental_create(
116
- "sleep", "infinity", **kwargs
117
- )
118
  return self._modal.Sandbox.create("sleep", "infinity", **kwargs)
119
 
120
  def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str:
@@ -164,11 +139,6 @@ class ModalProvider(ContainerProvider):
164
  provider.wait_for_ready(base_url)
165
  # sandbox terminated on exit
166
  ```
167
-
168
- Sandbox v2 (beta) is opt-in:
169
- ```python
170
- provider = ModalProvider(app_name="openenv", use_sandbox_v2=True)
171
- ```
172
  """
173
 
174
  _dockerfile_registry: Dict[str, Dict[str, Any]] = {}
@@ -179,7 +149,7 @@ class ModalProvider(ContainerProvider):
179
  image: str | None = None,
180
  env_vars: dict[str, str] | None = None,
181
  app_name: str = "openenv",
182
- use_sandbox_v2: bool = False,
183
  timeout: int = 300,
184
  cmd: str | None = None,
185
  cpu: float | None = None,
@@ -198,12 +168,11 @@ class ModalProvider(ContainerProvider):
198
  app_name (`str`, *optional*, defaults to `"openenv"`):
199
  Modal app name the sandbox is created under. Looked up (and
200
  created if missing) via ``modal.App.lookup``.
201
- use_sandbox_v2 (`bool`, *optional*, defaults to `False`):
202
- When `True`, sandboxes are created via the beta
203
- ``modal.Sandbox._experimental_create`` API (Sandbox v2). This is
204
- an experimental, private SDK feature and is therefore off by
205
- default; a feature check fails fast at construction if the
206
- installed SDK lacks it. See https://modal.com/docs/guide/sandbox-v2 .
207
  timeout (`int`, *optional*, defaults to `300`):
208
  Maximum sandbox lifetime in seconds.
209
  cmd (`str`, *optional*):
@@ -225,10 +194,18 @@ class ModalProvider(ContainerProvider):
225
  orchestrator/CI logs. When `True`, a best-effort redacted,
226
  length-bounded excerpt is included in startup-crash errors.
227
  """
 
 
 
 
 
 
 
 
 
228
  self._image = image
229
  self._env_vars = env_vars
230
  self._app_name = app_name
231
- self._use_sandbox_v2 = use_sandbox_v2
232
  self._timeout = timeout
233
  self._cmd = cmd
234
  self._cpu = cpu
@@ -241,20 +218,12 @@ class ModalProvider(ContainerProvider):
241
  self._redact_values: set[str] = set()
242
 
243
  if _adapter is None:
244
- # Import eagerly (inside the adapter) so SDK/configuration errors —
245
- # including the Sandbox v2 feature check — surface at construction.
246
- self._adapter: Any = _DefaultModalAdapter(
247
- app_name=app_name, use_sandbox_v2=use_sandbox_v2
248
- )
249
  else:
250
  self._adapter = _adapter
251
 
252
- if use_sandbox_v2:
253
- logger.info(
254
- "Using Modal Sandbox v2 (experimental). This feature must be "
255
- "explicitly enabled. Contact support@modal.com to get access."
256
- )
257
-
258
  def _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str:
259
  """Discover the server command from ``openenv.yaml`` inside the sandbox.
260
 
 
3
  """
4
  Modal container provider for running OpenEnv environments in Modal sandboxes.
5
 
6
+ Requires the ``modal`` SDK: ``pip install modal>=1.6.3``
7
 
8
  The provider boots an OpenEnv server inside a Modal sandbox, exposes it on an
9
  encrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects to
10
  over ``wss://``.
 
 
 
 
 
11
  """
12
 
13
  from __future__ import annotations
14
 
 
15
  import shlex
16
  import time
17
+ import warnings
18
  from typing import Any, Dict, Optional
19
 
20
  from ._server_config import parse_dockerfile_cmd, parse_openenv_app_field
21
  from .providers import ContainerProvider
22
 
 
 
23
  _DEFAULT_MODAL_PORT = 8000
24
 
25
  # Modal's default per-container resource requests. We pass configured cpu/memory
 
51
  """Thin adapter over the ``modal`` SDK.
52
 
53
  The provider talks to this private adapter instead of spreading SDK details
54
+ through its own logic; tests inject a duck-typed fake in its place.
 
 
55
  """
56
 
57
+ def __init__(self, *, app_name: str):
58
  import modal
59
 
60
  self._modal = modal
61
  self._app_name = app_name
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  def image_from_registry(self, tag: str) -> Any:
64
  return self._modal.Image.from_registry(tag)
 
90
 
91
  # The sandbox is started with a keep-alive entrypoint; the server
92
  # command is launched via exec afterwards (see ModalProvider).
 
 
 
 
93
  return self._modal.Sandbox.create("sleep", "infinity", **kwargs)
94
 
95
  def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str:
 
139
  provider.wait_for_ready(base_url)
140
  # sandbox terminated on exit
141
  ```
 
 
 
 
 
142
  """
143
 
144
  _dockerfile_registry: Dict[str, Dict[str, Any]] = {}
 
149
  image: str | None = None,
150
  env_vars: dict[str, str] | None = None,
151
  app_name: str = "openenv",
152
+ use_sandbox_v2: bool | None = None,
153
  timeout: int = 300,
154
  cmd: str | None = None,
155
  cpu: float | None = None,
 
168
  app_name (`str`, *optional*, defaults to `"openenv"`):
169
  Modal app name the sandbox is created under. Looked up (and
170
  created if missing) via ``modal.App.lookup``.
171
+ use_sandbox_v2 (`bool`, *optional*):
172
+ Deprecated and ignored; will be removed in OpenEnv 0.15.0.
173
+ Modal 1.6+ creates Sandbox v2 sandboxes through
174
+ ``modal.Sandbox.create`` by default. Set ``MODAL_SANDBOX_V2=0``
175
+ to use Sandbox v1.
 
176
  timeout (`int`, *optional*, defaults to `300`):
177
  Maximum sandbox lifetime in seconds.
178
  cmd (`str`, *optional*):
 
194
  orchestrator/CI logs. When `True`, a best-effort redacted,
195
  length-bounded excerpt is included in startup-crash errors.
196
  """
197
+ if use_sandbox_v2 is not None:
198
+ warnings.warn(
199
+ "`use_sandbox_v2` is deprecated, has no effect, and will be removed "
200
+ "in OpenEnv 0.15.0. Remove the argument: Modal 1.6+ creates Sandbox "
201
+ "v2 sandboxes through `modal.Sandbox.create` by default. Set "
202
+ "`MODAL_SANDBOX_V2=0` to use Sandbox v1.",
203
+ FutureWarning,
204
+ stacklevel=2,
205
+ )
206
  self._image = image
207
  self._env_vars = env_vars
208
  self._app_name = app_name
 
209
  self._timeout = timeout
210
  self._cmd = cmd
211
  self._cpu = cpu
 
218
  self._redact_values: set[str] = set()
219
 
220
  if _adapter is None:
221
+ # Import eagerly (inside the adapter) so SDK/configuration errors
222
+ # surface at construction.
223
+ self._adapter: Any = _DefaultModalAdapter(app_name=app_name)
 
 
224
  else:
225
  self._adapter = _adapter
226
 
 
 
 
 
 
 
227
  def _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str:
228
  """Discover the server command from ``openenv.yaml`` inside the sandbox.
229
 
src/core/containers/runtime/providers.py CHANGED
@@ -9,19 +9,76 @@ This module provides a pluggable architecture for different container providers
9
 
10
  from __future__ import annotations
11
 
 
 
12
  from abc import ABC, abstractmethod
13
- from typing import Any, Dict, Optional, Sequence, TypeVar
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider")
16
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  class ContainerProvider(ABC):
19
  """
20
  Abstract base class for container providers.
21
 
22
  Providers implement this interface to support different container platforms:
23
  - LocalDockerProvider: Runs containers on local Docker daemon
24
- - KubernetesProvider: Runs containers in Kubernetes cluster
 
 
25
  - FargateProvider: Runs containers on AWS Fargate
26
  - CloudRunProvider: Runs containers on Google Cloud Run
27
 
@@ -175,8 +232,10 @@ class LocalDockerProvider(ContainerProvider):
175
  Port to expose. If `None`, finds an available port.
176
  env_vars (`dict`, *optional*):
177
  Environment variables for the container.
178
- **kwargs:
179
- Additional Docker run options.
 
 
180
 
181
  Returns:
182
  `str`: Base URL to connect to the container.
@@ -184,6 +243,8 @@ class LocalDockerProvider(ContainerProvider):
184
  import subprocess
185
  import time
186
 
 
 
187
  # Find available port if not specified
188
  if port is None:
189
  port = self._find_available_port()
@@ -202,17 +263,33 @@ class LocalDockerProvider(ContainerProvider):
202
  f"{port}:8000", # Map port
203
  ]
204
 
205
- # Add environment variables
206
- if env_vars:
207
- for key, value in env_vars.items():
208
- cmd.extend(["-e", f"{key}={value}"])
 
 
 
 
 
 
 
 
 
209
 
210
  # Add image
211
  cmd.append(image)
212
 
213
  # Run container
214
  try:
215
- result = subprocess.run(cmd, capture_output=True, text=True, check=True)
 
 
 
 
 
 
 
216
  self._container_id = result.stdout.strip()
217
  except subprocess.CalledProcessError as e:
218
  error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}"
@@ -441,10 +518,6 @@ class DockerSwarmProvider(ContainerProvider):
441
  if self._overlay_network:
442
  cmd.extend(["--network", self._overlay_network])
443
 
444
- if env_vars:
445
- for key, value in env_vars.items():
446
- cmd.extend(["--env", f"{key}={value}"])
447
-
448
  if cpu_limit is not None:
449
  cmd.extend(["--limit-cpu", str(cpu_limit)])
450
 
@@ -468,12 +541,14 @@ class DockerSwarmProvider(ContainerProvider):
468
  cmd.extend(command_override)
469
 
470
  try:
471
- result = subprocess.run(
472
- cmd,
473
- capture_output=True,
474
- text=True,
475
- check=True,
476
- )
 
 
477
  self._service_id = result.stdout.strip()
478
  except subprocess.CalledProcessError as e:
479
  error_msg = (
@@ -644,19 +719,6 @@ class DockerSwarmProvider(ContainerProvider):
644
  return f"{clean_image}-swarm-{timestamp}"
645
 
646
 
647
- class KubernetesProvider(ContainerProvider):
648
- """
649
- Planned container provider for Kubernetes clusters.
650
-
651
- Not yet implemented: this is a placeholder for the planned Kubernetes
652
- backend and does not implement the abstract `ContainerProvider` methods, so
653
- it cannot be instantiated. Use `LocalDockerProvider`, `DockerSwarmProvider`,
654
- `DaytonaProvider`, or `ACASandboxProvider` instead.
655
- """
656
-
657
- pass
658
-
659
-
660
  class RuntimeProvider(ABC):
661
  """
662
  Abstract base class for runtime providers that are not container providers.
 
9
 
10
  from __future__ import annotations
11
 
12
+ import os
13
+ import tempfile
14
  from abc import ABC, abstractmethod
15
+ from contextlib import contextmanager
16
+ from typing import (
17
+ Any,
18
+ Dict,
19
+ Iterator,
20
+ List,
21
+ Mapping,
22
+ Optional,
23
+ Sequence,
24
+ Tuple,
25
+ TypeVar,
26
+ )
27
 
28
  _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider")
29
 
30
 
31
+ @contextmanager
32
+ def _env_file_args(
33
+ env_vars: Optional[Mapping[str, str]],
34
+ ) -> Iterator[Tuple[List[str], Optional[str]]]:
35
+ """
36
+ Yield `--env-file` arguments for the container's environment variables,
37
+ and the text to send to docker's stdin.
38
+
39
+ The values (often tokens) stay out of the command line, which other
40
+ processes can read and errors include, and out of the docker CLI's own
41
+ environment, where names like `DOCKER_HOST` or `PATH` would change how
42
+ the CLI runs. Docker reads them from its stdin (`/dev/stdin`), so no file
43
+ is written and a CLI with a private `/tmp` (snap) still gets them. Windows
44
+ has no `/dev/stdin`: there they go in a temporary file only this user can
45
+ read, removed once docker returns.
46
+ """
47
+ if not env_vars:
48
+ yield [], None
49
+ return
50
+ lines = []
51
+ for key, value in env_vars.items():
52
+ key, value = str(key), str(value)
53
+ if not key or key.startswith("#") or any(c in key for c in "= \t\r\n\0"):
54
+ raise ValueError(f"Invalid environment variable name: {key!r}")
55
+ if any(c in value for c in "\r\n\0"):
56
+ raise ValueError(
57
+ f"Environment variable {key!r}: values can't contain line breaks "
58
+ "or NUL characters"
59
+ )
60
+ lines.append(f"{key}={value}\n")
61
+ if os.name != "nt":
62
+ yield ["--env-file", "/dev/stdin"], "".join(lines)
63
+ return
64
+ fd, path = tempfile.mkstemp(prefix="openenv-env-")
65
+ try:
66
+ with os.fdopen(fd, "w") as env_file:
67
+ env_file.writelines(lines)
68
+ yield ["--env-file", path], None
69
+ finally:
70
+ os.unlink(path)
71
+
72
+
73
  class ContainerProvider(ABC):
74
  """
75
  Abstract base class for container providers.
76
 
77
  Providers implement this interface to support different container platforms:
78
  - LocalDockerProvider: Runs containers on local Docker daemon
79
+ - DockerSwarmProvider: Runs containers as a Docker Swarm service
80
+ - KubernetesProvider: optional ``openenv[kubernetes]`` extra
81
+ (``kubernetes_provider.py``)
82
  - FargateProvider: Runs containers on AWS Fargate
83
  - CloudRunProvider: Runs containers on Google Cloud Run
84
 
 
232
  Port to expose. If `None`, finds an available port.
233
  env_vars (`dict`, *optional*):
234
  Environment variables for the container.
235
+ volumes (`dict`, *optional*):
236
+ Mapping of host paths or volume names to mount configuration.
237
+ Each configuration must contain a `bind` container path and may
238
+ contain a `mode` such as `"ro"` or `"rw"`.
239
 
240
  Returns:
241
  `str`: Base URL to connect to the container.
 
243
  import subprocess
244
  import time
245
 
246
+ volumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes")
247
+
248
  # Find available port if not specified
249
  if port is None:
250
  port = self._find_available_port()
 
263
  f"{port}:8000", # Map port
264
  ]
265
 
266
+ # Add volume mounts before the image name.
267
+ if volumes:
268
+ for source, config in volumes.items():
269
+ bind = config.get("bind")
270
+ if not bind:
271
+ raise ValueError(
272
+ f"Volume config for {source!r} must include a non-empty 'bind'"
273
+ )
274
+ mode = config.get("mode")
275
+ volume_spec = f"{source}:{bind}"
276
+ if mode:
277
+ volume_spec = f"{volume_spec}:{mode}"
278
+ cmd.extend(["--volume", volume_spec])
279
 
280
  # Add image
281
  cmd.append(image)
282
 
283
  # Run container
284
  try:
285
+ with _env_file_args(env_vars) as (env_args, env_input):
286
+ result = subprocess.run(
287
+ cmd[:2] + env_args + cmd[2:],
288
+ input=env_input,
289
+ capture_output=True,
290
+ text=True,
291
+ check=True,
292
+ )
293
  self._container_id = result.stdout.strip()
294
  except subprocess.CalledProcessError as e:
295
  error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}"
 
518
  if self._overlay_network:
519
  cmd.extend(["--network", self._overlay_network])
520
 
 
 
 
 
521
  if cpu_limit is not None:
522
  cmd.extend(["--limit-cpu", str(cpu_limit)])
523
 
 
541
  cmd.extend(command_override)
542
 
543
  try:
544
+ with _env_file_args(env_vars) as (env_args, env_input):
545
+ result = subprocess.run(
546
+ cmd[:3] + env_args + cmd[3:],
547
+ input=env_input,
548
+ capture_output=True,
549
+ text=True,
550
+ check=True,
551
+ )
552
  self._service_id = result.stdout.strip()
553
  except subprocess.CalledProcessError as e:
554
  error_msg = (
 
719
  return f"{clean_image}-swarm-{timestamp}"
720
 
721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722
  class RuntimeProvider(ABC):
723
  """
724
  Abstract base class for runtime providers that are not container providers.
src/core/containers/runtime/uv_provider.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  import os
6
  import shutil
7
  import socket
@@ -12,6 +13,9 @@ from typing import Dict, Optional
12
 
13
  import requests
14
 
 
 
 
15
  from .providers import RuntimeProvider
16
 
17
  GIT_URL_PREFIX = "git+"
@@ -137,7 +141,11 @@ class UVProvider(RuntimeProvider):
137
  reload (`bool`, *optional*, defaults to `False`):
138
  Whether to enable uvicorn's reload mode.
139
  env_vars (`dict`, *optional*):
140
- Environment variables to pass through to the spawned process.
 
 
 
 
141
  context_timeout_s (`float`, *optional*, defaults to `60.0`):
142
  How long to wait for the environment to become ready.
143
 
@@ -195,7 +203,8 @@ class UVProvider(RuntimeProvider):
195
  port (`int`, *optional*):
196
  The port to bind the environment to.
197
  env_vars (`dict`, *optional*):
198
- Environment variables to pass to the environment.
 
199
  workers (`int`, *optional*, defaults to `1`):
200
  The number of workers to use.
201
 
@@ -232,13 +241,23 @@ class UVProvider(RuntimeProvider):
232
  project_path=project_path,
233
  )
234
 
235
- env = os.environ.copy()
 
 
236
 
237
  if self.env_vars:
238
  env.update(self.env_vars)
239
  if env_vars:
240
  env.update(env_vars)
241
 
 
 
 
 
 
 
 
 
242
  try:
243
  self._process = subprocess.Popen(command, env=env)
244
  except OSError as exc:
 
2
 
3
  from __future__ import annotations
4
 
5
+ import logging
6
  import os
7
  import shutil
8
  import socket
 
13
 
14
  import requests
15
 
16
+ from ...utils import _SECRET_ENV_NAME
17
+
18
+ logger = logging.getLogger(__name__)
19
  from .providers import RuntimeProvider
20
 
21
  GIT_URL_PREFIX = "git+"
 
141
  reload (`bool`, *optional*, defaults to `False`):
142
  Whether to enable uvicorn's reload mode.
143
  env_vars (`dict`, *optional*):
144
+ Environment variables to pass through to the spawned process. The
145
+ server inherits this process's environment except variables named
146
+ like credentials (`TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part
147
+ of the name, such as `HF_TOKEN`), so a credential the server needs
148
+ has to be passed here.
149
  context_timeout_s (`float`, *optional*, defaults to `60.0`):
150
  How long to wait for the environment to become ready.
151
 
 
203
  port (`int`, *optional*):
204
  The port to bind the environment to.
205
  env_vars (`dict`, *optional*):
206
+ Environment variables to pass to the environment, on top of
207
+ the constructor's. Credentials reach the server only this way.
208
  workers (`int`, *optional*, defaults to `1`):
209
  The number of workers to use.
210
 
 
241
  project_path=project_path,
242
  )
243
 
244
+ # Environment servers can run code a model wrote: they don't inherit
245
+ # this process's credentials, only the ones passed in env_vars.
246
+ env = {k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)}
247
 
248
  if self.env_vars:
249
  env.update(self.env_vars)
250
  if env_vars:
251
  env.update(env_vars)
252
 
253
+ dropped = sorted(k for k in os.environ if k not in env)
254
+ if dropped:
255
+ logger.warning(
256
+ "Not passing %s to the environment server. Pass the ones it "
257
+ "needs with env_vars.",
258
+ ", ".join(dropped),
259
+ )
260
+
261
  try:
262
  self._process = subprocess.Popen(command, env=env)
263
  except OSError as exc:
src/core/env_client.py CHANGED
@@ -275,6 +275,15 @@ async def _best_effort_graceful_close(ws: ClientConnection) -> None:
275
  await _best_effort_close(ws)
276
 
277
 
 
 
 
 
 
 
 
 
 
278
  class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
279
  """
280
  Async environment client for persistent sessions.
@@ -386,6 +395,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
386
  # Strong references for fire-and-forget socket closes (see _receive),
387
  # so the task isn't garbage-collected mid-close. Discarded on done.
388
  self._pending_close_tasks: set[asyncio.Task] = set()
 
 
389
  if base_url is not None:
390
  self._set_base_url(base_url)
391
 
@@ -517,6 +528,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
517
  coro_factory: Callable[[], Any],
518
  *,
519
  allow_async_handoff: bool = False,
 
520
  ) -> Any:
521
  """Run an async operation through the sync wrapper."""
522
  if allow_async_handoff and self._execution_mode == "async":
@@ -525,9 +537,15 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
525
  self._claim_execution_mode("sync")
526
  if self._sync_client is None:
527
  self._sync_client = self.sync()
528
- return self._sync_client._run(coro_factory())
 
 
 
 
529
 
530
- def _dispatch(self, coro_factory: Callable[[], Any]) -> Any:
 
 
531
  """Return an awaitable in async code and a concrete result in sync code."""
532
  try:
533
  running_loop = asyncio.get_running_loop()
@@ -538,15 +556,17 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
538
  sync_loop = (
539
  self._sync_client._loop if self._sync_client is not None else None
540
  )
541
- if running_loop is sync_loop:
542
  return coro_factory()
543
- return self._run_sync(coro_factory)
544
  if running_loop is not None:
545
  if self._execution_mode == "async":
546
  return coro_factory()
547
  return _AutoAsyncResult(self, coro_factory)
548
 
549
- return self._run_sync(coro_factory, allow_async_handoff=True)
 
 
550
 
551
  def connect(self) -> Any:
552
  return self._dispatch(self._connect_async)
@@ -653,6 +673,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
653
  # leave a stale socket cached for a later operation.
654
  self._ws = None
655
  self._ws_loop = None
 
656
  same_loop = ws_loop is asyncio.get_running_loop()
657
  if same_loop:
658
  # Keep ownership of the handshake if this caller is cancelled.
@@ -929,6 +950,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
929
  `start_container` (docker) or to the `UVProvider` constructor/start (uv).
930
  When `use_docker=False`, the `project_path` argument can be used to override
931
  the default git URL (`git+https://huggingface.co/spaces/{repo_id}`).
 
 
932
 
933
  Returns:
934
  `_BootstrapResult`: `await` for a connected async client, or call
@@ -996,8 +1019,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
996
  "type": "reset",
997
  "data": kwargs,
998
  }
 
 
999
  response = await self._send_and_receive(message)
1000
- return self._parse_result(response.get("data", {}))
 
 
1001
 
1002
  def step(self, action: ActT, **kwargs: Any) -> Any:
1003
  return self._dispatch(lambda: self._step_async(action, **kwargs))
@@ -1019,8 +1046,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
1019
  "type": "step",
1020
  "data": self._step_payload(action),
1021
  }
 
1022
  response = await self._send_and_receive(message)
1023
- return self._parse_result(response.get("data", {}))
 
 
 
1024
 
1025
  def state(self) -> Any:
1026
  return self._dispatch(self._state_async)
@@ -1033,11 +1064,33 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
1033
  State object with environment state information
1034
  """
1035
  message = {"type": "state"}
 
1036
  response = await self._send_and_receive(message)
1037
  return self._parse_state(response.get("data", {}))
1038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1039
  def close(self) -> Any:
1040
- return self._dispatch(self._close_async)
1041
 
1042
  async def _close_child_clients(self) -> asyncio.CancelledError | None:
1043
  """Close every captured child while deferring caller cancellation."""
@@ -1164,7 +1217,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
1164
 
1165
  def __exit__(self, exc_type, exc_val, exc_tb) -> None:
1166
  """Exit sync context manager, closing connection."""
1167
- self._run_sync(self._close_async)
1168
 
1169
  def sync(self) -> "SyncEnvClient":
1170
  """
 
275
  await _best_effort_close(ws)
276
 
277
 
278
+ class SessionLostError(ConnectionError):
279
+ """The connection to the server was lost in the middle of an episode.
280
+
281
+ The server keeps one environment per WebSocket connection, so reconnecting
282
+ opens a new session with an environment this client never reset. Call
283
+ `reset()` to start a new episode.
284
+ """
285
+
286
+
287
  class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
288
  """
289
  Async environment client for persistent sessions.
 
395
  # Strong references for fire-and-forget socket closes (see _receive),
396
  # so the task isn't garbage-collected mid-close. Discarded on done.
397
  self._pending_close_tasks: set[asyncio.Task] = set()
398
+ # The socket that carries the episode started by `reset()`, if one is open.
399
+ self._episode_ws: Optional[ClientConnection] = None
400
  if base_url is not None:
401
  self._set_base_url(base_url)
402
 
 
528
  coro_factory: Callable[[], Any],
529
  *,
530
  allow_async_handoff: bool = False,
531
+ stop_loop: bool = False,
532
  ) -> Any:
533
  """Run an async operation through the sync wrapper."""
534
  if allow_async_handoff and self._execution_mode == "async":
 
537
  self._claim_execution_mode("sync")
538
  if self._sync_client is None:
539
  self._sync_client = self.sync()
540
+ try:
541
+ return self._sync_client._run(coro_factory())
542
+ finally:
543
+ if stop_loop:
544
+ self._sync_client._stop_loop()
545
 
546
+ def _dispatch(
547
+ self, coro_factory: Callable[[], Any], *, stop_loop: bool = False
548
+ ) -> Any:
549
  """Return an awaitable in async code and a concrete result in sync code."""
550
  try:
551
  running_loop = asyncio.get_running_loop()
 
556
  sync_loop = (
557
  self._sync_client._loop if self._sync_client is not None else None
558
  )
559
+ if running_loop is not None and running_loop is sync_loop:
560
  return coro_factory()
561
+ return self._run_sync(coro_factory, stop_loop=stop_loop)
562
  if running_loop is not None:
563
  if self._execution_mode == "async":
564
  return coro_factory()
565
  return _AutoAsyncResult(self, coro_factory)
566
 
567
+ return self._run_sync(
568
+ coro_factory, allow_async_handoff=True, stop_loop=stop_loop
569
+ )
570
 
571
  def connect(self) -> Any:
572
  return self._dispatch(self._connect_async)
 
673
  # leave a stale socket cached for a later operation.
674
  self._ws = None
675
  self._ws_loop = None
676
+ self._episode_ws = None
677
  same_loop = ws_loop is asyncio.get_running_loop()
678
  if same_loop:
679
  # Keep ownership of the handshake if this caller is cancelled.
 
950
  `start_container` (docker) or to the `UVProvider` constructor/start (uv).
951
  When `use_docker=False`, the `project_path` argument can be used to override
952
  the default git URL (`git+https://huggingface.co/spaces/{repo_id}`).
953
+ With `use_docker=False` the server doesn't inherit variables named like
954
+ credentials (such as `HF_TOKEN`): pass the ones it needs in `env_vars`.
955
 
956
  Returns:
957
  `_BootstrapResult`: `await` for a connected async client, or call
 
1019
  "type": "reset",
1020
  "data": kwargs,
1021
  }
1022
+ # A reset may reconnect: it starts a new episode on whatever session it lands on.
1023
+ self._episode_ws = None
1024
  response = await self._send_and_receive(message)
1025
+ result = self._parse_result(response.get("data", {}))
1026
+ self._episode_ws = None if result.done else self._ws
1027
+ return result
1028
 
1029
  def step(self, action: ActT, **kwargs: Any) -> Any:
1030
  return self._dispatch(lambda: self._step_async(action, **kwargs))
 
1046
  "type": "step",
1047
  "data": self._step_payload(action),
1048
  }
1049
+ self._raise_if_session_lost()
1050
  response = await self._send_and_receive(message)
1051
+ result = self._parse_result(response.get("data", {}))
1052
+ if result.done:
1053
+ self._episode_ws = None
1054
+ return result
1055
 
1056
  def state(self) -> Any:
1057
  return self._dispatch(self._state_async)
 
1064
  State object with environment state information
1065
  """
1066
  message = {"type": "state"}
1067
+ self._raise_if_session_lost()
1068
  response = await self._send_and_receive(message)
1069
  return self._parse_state(response.get("data", {}))
1070
 
1071
+ def _raise_if_session_lost(self) -> None:
1072
+ """Raise `SessionLostError` if the socket that carried the episode is gone.
1073
+
1074
+ `_connect_async()` would replace it with a new socket, which the server
1075
+ treats as a new session, and the call would run on an environment this
1076
+ client never reset. It keeps raising until `reset()`, so a retried call
1077
+ does not land on the new session either.
1078
+ """
1079
+ ws = self._episode_ws
1080
+ if ws is None:
1081
+ return
1082
+ if (
1083
+ self._ws is not ws
1084
+ or ws.state in (State.CLOSING, State.CLOSED)
1085
+ or self._ws_loop is not asyncio.get_running_loop()
1086
+ ):
1087
+ raise SessionLostError(
1088
+ f"Lost the connection to {self._ws_url} in the middle of an episode. "
1089
+ "Call reset() to start a new one."
1090
+ )
1091
+
1092
  def close(self) -> Any:
1093
+ return self._dispatch(self._close_async, stop_loop=True)
1094
 
1095
  async def _close_child_clients(self) -> asyncio.CancelledError | None:
1096
  """Close every captured child while deferring caller cancellation."""
 
1217
 
1218
  def __exit__(self, exc_type, exc_val, exc_tb) -> None:
1219
  """Exit sync context manager, closing connection."""
1220
+ self._run_sync(self._close_async, stop_loop=True)
1221
 
1222
  def sync(self) -> "SyncEnvClient":
1223
  """
src/core/env_server/exceptions.py CHANGED
@@ -44,7 +44,10 @@ class SessionCapacityError(OpenEnvError):
44
  Raised when the server cannot accept new sessions due to capacity limits.
45
 
46
  This error is raised when a new WebSocket connection is attempted but
47
- the server has already reached max_concurrent_envs active sessions.
 
 
 
48
  """
49
 
50
  def __init__(
@@ -59,7 +62,13 @@ class SessionCapacityError(OpenEnvError):
59
  if message is None:
60
  message = (
61
  f"Server at capacity: {active_sessions}/{max_sessions} sessions active. "
62
- f"Cannot accept new connections."
 
 
 
 
 
 
63
  )
64
 
65
  super().__init__(message)
 
44
  Raised when the server cannot accept new sessions due to capacity limits.
45
 
46
  This error is raised when a new WebSocket connection is attempted but
47
+ the server has already reached max_concurrent_envs active sessions. The
48
+ default message tells the caller which server setting limits the number of
49
+ sessions, since the client (e.g. a trainer opening one session per
50
+ concurrent episode) usually cannot see the server configuration.
51
  """
52
 
53
  def __init__(
 
62
  if message is None:
63
  message = (
64
  f"Server at capacity: {active_sessions}/{max_sessions} sessions active. "
65
+ f"Cannot accept new connections. To serve more concurrent sessions, "
66
+ f"start the server with a higher max_concurrent_envs (most "
67
+ f"environment servers read it from the MAX_CONCURRENT_ENVS "
68
+ f"environment variable). Values above 1 also require an environment "
69
+ f"that isolates per-session state and declares "
70
+ f"SUPPORTS_CONCURRENT_SESSIONS=True. Otherwise, open fewer "
71
+ f"sessions at once or close idle ones."
72
  )
73
 
74
  super().__init__(message)
src/core/env_server/http_server.py CHANGED
@@ -14,9 +14,10 @@ import inspect
14
  import json
15
  import logging
16
  import os
 
17
  import time
18
  import uuid
19
- from concurrent.futures import ThreadPoolExecutor
20
  from contextlib import AsyncExitStack
21
  from typing import (
22
  Any,
@@ -56,11 +57,23 @@ from .mcp_types import (
56
  ListToolsAction,
57
  ListToolsObservation,
58
  McpMethod,
 
59
  WSMCPMessage,
60
  WSMCPResponse,
61
  )
62
  from .route_config import GetEndpointConfig, register_get_endpoints
63
  from .serialization import deserialize_action, serialize_observation
 
 
 
 
 
 
 
 
 
 
 
64
  from .types import (
65
  Action,
66
  ConcurrencyConfig,
@@ -181,6 +194,7 @@ class HTTPEnvServer:
181
  state_cls: Type[State] = State,
182
  *,
183
  reset_observation_cls: Optional[Type[Observation]] = None,
 
184
  ):
185
  """
186
  Initialize HTTP server wrapper.
@@ -208,6 +222,10 @@ class HTTPEnvServer:
208
  The `State` subclass this environment reports. Used for the `/state`
209
  response model and the `state` entry of `/schema`, so that fields
210
  declared by the subclass are published and serialized.
 
 
 
 
211
 
212
  Raises:
213
  `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided.
@@ -253,6 +271,7 @@ class HTTPEnvServer:
253
  self.observation_cls = observation_cls
254
  self.reset_observation_cls = reset_observation_cls or observation_cls
255
  self.state_cls = state_cls
 
256
  self.env_name = env_name or self._default_env_name()
257
 
258
  # Session management for WebSocket connections
@@ -260,8 +279,12 @@ class HTTPEnvServer:
260
  self._session_executors: Dict[str, ThreadPoolExecutor] = {}
261
  self._session_stacks: Dict[str, AsyncExitStack] = {}
262
  self._session_info: Dict[str, SessionInfo] = {}
 
263
  self._session_websocket_attachments: set[str] = set()
264
  self._session_pending_closes: set[str] = set()
 
 
 
265
  self._session_lock = asyncio.Lock()
266
 
267
  # Create thread pool for running sync code in async context
@@ -270,8 +293,10 @@ class HTTPEnvServer:
270
 
271
  self._requires_single_thread_executor = self._detect_single_thread_requirement()
272
  self._shared_session_executor: Optional[ThreadPoolExecutor] = None
 
273
  if self._requires_single_thread_executor:
274
  self._shared_session_executor = ThreadPoolExecutor(max_workers=1)
 
275
 
276
  # Idle session reaper configuration.
277
  # Timeout is taken from ConcurrencyConfig.session_timeout;
@@ -280,6 +305,7 @@ class HTTPEnvServer:
280
  self._concurrency_config.session_timeout
281
  )
282
  self._reaper_task: Optional[asyncio.Task[None]] = None
 
283
 
284
  def _default_env_name(self) -> str:
285
  factory = self._env_factory
@@ -370,7 +396,9 @@ class HTTPEnvServer:
370
 
371
  return valid_kwargs
372
 
373
- async def _create_session(self) -> tuple[str, Environment]:
 
 
374
  """
375
  Create a new WebSocket session with its own environment instance.
376
 
@@ -400,58 +428,220 @@ class HTTPEnvServer:
400
  self._session_executors[session_id] = executor
401
  self._sessions[session_id] = None # placeholder until env is ready
402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  try:
404
- # Create environment in the executor thread (outside lock)
405
- loop = asyncio.get_event_loop()
406
- env = await loop.run_in_executor(executor, self._env_factory)
407
- except Exception as e:
408
- async with self._session_lock:
409
- if executor is not self._shared_session_executor:
410
- executor.shutdown(wait=False)
411
- self._session_executors.pop(session_id, None)
412
- self._sessions.pop(session_id, None)
413
- factory_name = getattr(
414
- self._env_factory, "__name__", str(self._env_factory)
415
- )
416
- raise EnvironmentFactoryError(factory_name) from e
417
-
418
- # Hold the MCP session open for the lifetime of this session,
419
- # matching the WebSocket path's AsyncExitStack pattern. This
420
- # prevents per-request MCP transport teardown/reconnection and
421
- # preserves FastMCP session state (ctx.set_state / ctx.get_state)
422
- # across HTTP calls within the same OpenEnv session.
423
- stack = AsyncExitStack()
424
- try:
425
- mcp_session_factory = getattr(env, "mcp_session", None)
426
- if callable(mcp_session_factory):
427
- mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())
428
- await stack.enter_async_context(mcp_session_cm)
429
- except Exception:
430
- # MCP transport failed to start — clean up the reserved slot,
431
- # the env, and the executor so they don't leak permanently
432
- # against _max_concurrent_envs.
433
- await stack.aclose() # best-effort
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  async with self._session_lock:
435
- self._sessions.pop(session_id, None)
436
- self._session_executors.pop(session_id, None)
437
- self._session_info.pop(session_id, None)
438
- await self._cleanup_session_resources(env, executor)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  raise
440
-
441
- async with self._session_lock:
442
- self._sessions[session_id] = env
443
- self._session_stacks[session_id] = stack
444
- now = time.time()
445
- self._session_info[session_id] = SessionInfo(
446
- session_id=session_id,
447
- created_at=current_time,
448
- last_activity_at=now,
449
- step_count=0,
450
- environment_type=type(env).__name__,
451
- )
452
 
453
  return session_id, env
454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  async def _destroy_session(self, session_id: str) -> None:
456
  """
457
  Destroy a WebSocket session and cleanup resources.
@@ -465,6 +655,7 @@ class HTTPEnvServer:
465
  executor = self._session_executors.pop(session_id, None)
466
  stack = self._session_stacks.pop(session_id, None)
467
  self._session_info.pop(session_id, None)
 
468
  self._session_websocket_attachments.discard(session_id)
469
  self._session_pending_closes.discard(session_id)
470
 
@@ -533,17 +724,26 @@ class HTTPEnvServer:
533
  interval = max(timeout / 4, 5.0) # check frequently enough
534
  while True:
535
  try:
536
- await asyncio.sleep(interval)
 
 
 
 
 
 
537
  now = time.time()
538
  stale_ids: list[str] = []
539
  async with self._session_lock:
540
  for sid, info in self._session_info.items():
541
  if (
542
  sid not in self._session_websocket_attachments
 
543
  and now - info.last_activity_at > timeout
544
  ):
545
  stale_ids.append(sid)
546
  for sid in stale_ids:
 
 
547
  # Re-check under lock: activity may have arrived since
548
  # the snapshot was taken, making this session active again.
549
  # Refresh `now` so slow _destroy_session calls don't cause
@@ -554,6 +754,7 @@ class HTTPEnvServer:
554
  if (
555
  info is None
556
  or sid in self._session_websocket_attachments
 
557
  or (now - info.last_activity_at) <= timeout
558
  ):
559
  continue
@@ -569,12 +770,14 @@ class HTTPEnvServer:
569
  def _start_reaper(self) -> None:
570
  """Start the idle-session reaper if a timeout is configured."""
571
  if self._session_idle_timeout_s is not None and self._reaper_task is None:
 
572
  self._reaper_task = asyncio.create_task(self._reap_idle_sessions())
573
 
574
- def _stop_reaper(self) -> None:
575
- """Cancel the reaper background task."""
576
  if self._reaper_task is not None:
577
- self._reaper_task.cancel()
 
578
  self._reaper_task = None
579
 
580
  def get_session_info(self, session_id: str) -> Optional[SessionInfo]:
@@ -879,20 +1082,30 @@ class HTTPEnvServer:
879
  f"Invalid mode: '{mode}'. Must be one of: {valid_modes}"
880
  )
881
 
882
- # Wire up idle-session reaper lifecycle via app events
 
 
 
 
 
 
883
  server_ref = self
884
 
885
  async def _start_session_reaper() -> None:
886
  server_ref._start_reaper()
887
 
888
- async def _stop_session_reaper() -> None:
889
- server_ref._stop_reaper()
 
 
 
 
890
  if server_ref._shared_session_executor is not None:
891
  server_ref._shared_session_executor.shutdown(wait=True)
892
 
893
  if not getattr(app.router, "_openenv_reaper_registered", False):
894
  app.router.on_startup.append(_start_session_reaper)
895
- app.router.on_shutdown.append(_stop_session_reaper)
896
  app.router._openenv_reaper_registered = True # type: ignore[attr-defined]
897
 
898
  # Helper function to handle reset endpoint
@@ -993,7 +1206,7 @@ class HTTPEnvServer:
993
  request_id=request_id,
994
  )
995
  try:
996
- created_session_id, _ = await self._create_session()
997
  except SessionCapacityError as e:
998
  return JsonRpcResponse.error_response(
999
  JsonRpcErrorCode.SERVER_ERROR,
@@ -1033,6 +1246,21 @@ class HTTPEnvServer:
1033
  )
1034
 
1035
  async with self._session_lock:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1036
  if target_session_id in self._session_websocket_attachments:
1037
  env = _MISSING
1038
  attached = True
@@ -1046,6 +1274,7 @@ class HTTPEnvServer:
1046
  executor = self._session_executors.pop(target_session_id, None)
1047
  stack = self._session_stacks.pop(target_session_id, None)
1048
  self._session_info.pop(target_session_id, None)
 
1049
  elif not attached:
1050
  executor = None
1051
  stack = None
@@ -1099,6 +1328,7 @@ class HTTPEnvServer:
1099
  elif requested_session_id:
1100
  async with self._session_lock:
1101
  _env = self._sessions.get(requested_session_id, _MISSING)
 
1102
 
1103
  if _env is _MISSING:
1104
  return JsonRpcResponse.error_response(
@@ -1107,6 +1337,13 @@ class HTTPEnvServer:
1107
  request_id=request_id,
1108
  )
1109
 
 
 
 
 
 
 
 
1110
  if _env is None:
1111
  return JsonRpcResponse.error_response(
1112
  JsonRpcErrorCode.INVALID_REQUEST,
@@ -1118,6 +1355,8 @@ class HTTPEnvServer:
1118
  managed_session_id = requested_session_id
1119
  else:
1120
  _env = self._env_factory()
 
 
1121
  should_close = True
1122
  try:
1123
  mcp_client = getattr(_env, "mcp_client", None)
@@ -1142,6 +1381,27 @@ class HTTPEnvServer:
1142
  }
1143
 
1144
  if method == McpMethod.TOOLS_LIST:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1145
  # Check if environment is MCP-enabled
1146
  if mcp_client is None and mcp_server is None:
1147
  if supports_mcp_style_actions:
@@ -1164,7 +1424,7 @@ class HTTPEnvServer:
1164
  request_id=request_id,
1165
  )
1166
  return JsonRpcResponse.error_response(
1167
- JsonRpcErrorCode.INTERNAL_ERROR,
1168
  "Environment does not support MCP",
1169
  request_id=request_id,
1170
  )
@@ -1180,7 +1440,7 @@ class HTTPEnvServer:
1180
  return JsonRpcResponse.success(
1181
  result={
1182
  "tools": [
1183
- t.model_dump()
1184
  if hasattr(t, "model_dump")
1185
  else dict(t)
1186
  for t in tools
@@ -1221,6 +1481,32 @@ class HTTPEnvServer:
1221
  request_id=request_id,
1222
  )
1223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1224
  if mcp_client is None and mcp_server is None:
1225
  if supports_mcp_style_actions:
1226
  observation = await call_mcp_style_step(
@@ -1242,7 +1528,7 @@ class HTTPEnvServer:
1242
  request_id=request_id,
1243
  )
1244
  return JsonRpcResponse.error_response(
1245
- JsonRpcErrorCode.INTERNAL_ERROR,
1246
  "Environment does not support MCP",
1247
  request_id=request_id,
1248
  )
@@ -1414,7 +1700,7 @@ class HTTPEnvServer:
1414
 
1415
  try:
1416
  # Create session with dedicated environment
1417
- session_id, session_env = await self._create_session()
1418
  if session_env is None:
1419
  raise RuntimeError(
1420
  "Session environment not initialized for MCP websocket"
@@ -1661,13 +1947,14 @@ The structure of the state object is defined by the environment's State model.
1661
  tags=["Schema"],
1662
  summary="Get all JSON schemas",
1663
  description="""
1664
- Get JSON schemas for actions, observations, and state in a single response.
1665
 
1666
  Returns a combined schema object containing:
1667
  - **action**: JSON schema for actions accepted by this environment
1668
  - **observation**: JSON schema for observations returned by step
1669
  - **reset_observation**: JSON schema for observations returned by reset
1670
  - **state**: JSON schema for environment state objects
 
1671
 
1672
  This is more efficient than calling individual schema endpoints and provides
1673
  all schema information needed to interact with the environment.
@@ -1690,6 +1977,10 @@ all schema information needed to interact with the environment.
1690
  "type": "object",
1691
  "properties": {"step_count": {"type": "integer"}},
1692
  },
 
 
 
 
1693
  }
1694
  }
1695
  },
@@ -1703,6 +1994,7 @@ all schema information needed to interact with the environment.
1703
  observation=self.observation_cls.model_json_schema(),
1704
  reset_observation=self.reset_observation_cls.model_json_schema(),
1705
  state=self.state_cls.model_json_schema(),
 
1706
  )
1707
 
1708
  # Register MCP endpoint for production mode (direct MCP access)
@@ -1753,6 +2045,8 @@ all schema information needed to interact with the environment.
1753
  session_env = None
1754
  owns_session = False
1755
  attached_session = False
 
 
1756
 
1757
  try:
1758
  requested_session_id = websocket.query_params.get("session_id")
@@ -1761,10 +2055,15 @@ all schema information needed to interact with the environment.
1761
  attached_env = self._sessions.get(
1762
  requested_session_id, _MISSING
1763
  )
 
1764
  if attached_env is _MISSING:
1765
  raise RuntimeError(
1766
  f"Unknown session_id: {requested_session_id}"
1767
  )
 
 
 
 
1768
  if attached_env is None:
1769
  raise RuntimeError(
1770
  f"Session {requested_session_id} is still initializing"
@@ -1780,7 +2079,7 @@ all schema information needed to interact with the environment.
1780
  attached_session = True
1781
  self._update_session_activity(session_id)
1782
  else:
1783
- session_id, session_env = await self._create_session()
1784
  owns_session = True
1785
 
1786
  if session_env is None:
@@ -1803,6 +2102,19 @@ all schema information needed to interact with the environment.
1803
  # Receive message from client
1804
  raw_message = await websocket.receive_text()
1805
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1806
  try:
1807
  message_dict = json.loads(raw_message)
1808
  except json.JSONDecodeError as e:
@@ -1817,6 +2129,67 @@ all schema information needed to interact with the environment.
1817
 
1818
  msg_type = message_dict.get("type", "")
1819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1820
  try:
1821
  match msg_type:
1822
  case "reset":
@@ -1848,7 +2221,12 @@ all schema information needed to interact with the environment.
1848
  )
1849
  )
1850
 
1851
- self._update_session_activity(session_id)
 
 
 
 
 
1852
 
1853
  response = WSObservationResponse(
1854
  data=serialize_observation(observation),
@@ -1925,9 +2303,39 @@ all schema information needed to interact with the environment.
1925
  }
1926
  )
1927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1928
  await websocket.send_text(response.model_dump_json())
1929
 
1930
  except ValidationError as e:
 
 
 
 
 
 
1931
  error_resp = WSErrorResponse(
1932
  data={
1933
  "message": "Invalid message",
@@ -1937,6 +2345,12 @@ all schema information needed to interact with the environment.
1937
  )
1938
  await websocket.send_text(error_resp.model_dump_json())
1939
  except Exception as e:
 
 
 
 
 
 
1940
  error_resp = WSErrorResponse(
1941
  data={
1942
  "message": str(e),
@@ -1944,6 +2358,11 @@ all schema information needed to interact with the environment.
1944
  }
1945
  )
1946
  await websocket.send_text(error_resp.model_dump_json())
 
 
 
 
 
1947
 
1948
  except WebSocketDisconnect:
1949
  pass
@@ -2003,6 +2422,7 @@ def create_app(
2003
  *,
2004
  mode: Optional[ServerMode | str] = None,
2005
  reset_observation_cls: Optional[Type[Observation]] = None,
 
2006
  ) -> FastAPI:
2007
  """
2008
  Create a FastAPI application with or without web interface.
@@ -2047,6 +2467,9 @@ def create_app(
2047
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2048
  The `State` subclass this environment reports, used for the `/state`
2049
  response model and the `state` entry of `/schema`.
 
 
 
2050
  mode (`ServerMode` or `str`, *optional*):
2051
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2052
  environment variable, defaulting to simulation.
@@ -2074,6 +2497,7 @@ def create_app(
2074
  max_concurrent_envs,
2075
  concurrency_config,
2076
  state_cls=state_cls,
 
2077
  reset_observation_cls=reset_observation_cls,
2078
  gradio_builder=gradio_builder,
2079
  custom_tab_name=custom_tab_name,
@@ -2092,6 +2516,7 @@ def create_app(
2092
  concurrency_config,
2093
  env_name=env_name,
2094
  state_cls=state_cls,
 
2095
  reset_observation_cls=reset_observation_cls,
2096
  mode=mode,
2097
  )
@@ -2108,6 +2533,7 @@ def create_fastapi_app(
2108
  *,
2109
  mode: Optional[ServerMode | str] = None,
2110
  reset_observation_cls: Optional[Type[Observation]] = None,
 
2111
  ) -> FastAPI:
2112
  """
2113
  Create a FastAPI application with comprehensive documentation.
@@ -2133,6 +2559,9 @@ def create_fastapi_app(
2133
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2134
  The `State` subclass this environment reports, used for the `/state`
2135
  response model and the `state` entry of `/schema`.
 
 
 
2136
  mode (`ServerMode` or `str`, *optional*):
2137
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2138
  environment variable, defaulting to simulation.
@@ -2160,7 +2589,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf
2160
  * **Environment Reset**: Initialize or restart episodes
2161
  * **Action Execution**: Send actions and receive observations
2162
  * **State Inspection**: Query current environment state
2163
- * **Schema Access**: Retrieve JSON schemas for actions and observations
2164
 
2165
  ## Workflow
2166
 
@@ -2190,7 +2619,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf
2190
  },
2191
  {
2192
  "name": "Schema",
2193
- "description": "JSON Schema endpoints for actions, observations, and state",
2194
  },
2195
  {"name": "Health", "description": "Service health and status checks"},
2196
  ],
@@ -2199,11 +2628,11 @@ HTTP API for interacting with OpenEnv environments through a standardized interf
2199
  openapi_url="/openapi.json",
2200
  contact={
2201
  "name": "OpenEnv Team",
2202
- "url": "https://github.com/huggingface/OpenEnv",
2203
  },
2204
  license_info={
2205
  "name": "BSD-3-Clause",
2206
- "url": "https://github.com/huggingface/OpenEnv/blob/main/LICENSE",
2207
  },
2208
  )
2209
 
@@ -2215,9 +2644,14 @@ HTTP API for interacting with OpenEnv environments through a standardized interf
2215
  concurrency_config=concurrency_config,
2216
  env_name=env_name,
2217
  state_cls=state_cls,
 
2218
  reset_observation_cls=reset_observation_cls,
2219
  )
2220
  if mode is None:
2221
  mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value)
2222
  server.register_routes(app, mode=mode)
 
 
 
 
2223
  return app
 
14
  import json
15
  import logging
16
  import os
17
+ import secrets
18
  import time
19
  import uuid
20
+ from concurrent.futures import Future, ThreadPoolExecutor
21
  from contextlib import AsyncExitStack
22
  from typing import (
23
  Any,
 
57
  ListToolsAction,
58
  ListToolsObservation,
59
  McpMethod,
60
+ ToolErrorType,
61
  WSMCPMessage,
62
  WSMCPResponse,
63
  )
64
  from .route_config import GetEndpointConfig, register_get_endpoints
65
  from .serialization import deserialize_action, serialize_observation
66
+ from .session_telemetry import (
67
+ rubric_counts,
68
+ rubric_snapshot,
69
+ SeedAcceptance,
70
+ SessionTelemetry,
71
+ ValidationOpenedData,
72
+ ValidationOpenedResponse,
73
+ ValidationOpenMessage,
74
+ ValidationReadMessage,
75
+ ValidationResponse,
76
+ )
77
  from .types import (
78
  Action,
79
  ConcurrencyConfig,
 
194
  state_cls: Type[State] = State,
195
  *,
196
  reset_observation_cls: Optional[Type[Observation]] = None,
197
+ reset_cls: Type[ResetRequest] = ResetRequest,
198
  ):
199
  """
200
  Initialize HTTP server wrapper.
 
222
  The `State` subclass this environment reports. Used for the `/state`
223
  response model and the `state` entry of `/schema`, so that fields
224
  declared by the subclass are published and serialized.
225
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
226
+ The `ResetRequest` subclass describing this environment's reset parameters.
227
+ Published as the `reset` entry of `/schema`. It is not used to validate
228
+ reset requests.
229
 
230
  Raises:
231
  `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided.
 
271
  self.observation_cls = observation_cls
272
  self.reset_observation_cls = reset_observation_cls or observation_cls
273
  self.state_cls = state_cls
274
+ self.reset_cls = reset_cls
275
  self.env_name = env_name or self._default_env_name()
276
 
277
  # Session management for WebSocket connections
 
279
  self._session_executors: Dict[str, ThreadPoolExecutor] = {}
280
  self._session_stacks: Dict[str, AsyncExitStack] = {}
281
  self._session_info: Dict[str, SessionInfo] = {}
282
+ self._session_modes: Dict[str, Optional[str]] = {}
283
  self._session_websocket_attachments: set[str] = set()
284
  self._session_pending_closes: set[str] = set()
285
+ # WebSocket messages being handled, per session; such sessions are never
286
+ # idle-reaped. A count, since an attached socket can share the session.
287
+ self._session_operations_in_flight: Dict[str, int] = {}
288
  self._session_lock = asyncio.Lock()
289
 
290
  # Create thread pool for running sync code in async context
 
293
 
294
  self._requires_single_thread_executor = self._detect_single_thread_requirement()
295
  self._shared_session_executor: Optional[ThreadPoolExecutor] = None
296
+ self._shared_session_creation_lock: Optional[asyncio.Lock] = None
297
  if self._requires_single_thread_executor:
298
  self._shared_session_executor = ThreadPoolExecutor(max_workers=1)
299
+ self._shared_session_creation_lock = asyncio.Lock()
300
 
301
  # Idle session reaper configuration.
302
  # Timeout is taken from ConcurrencyConfig.session_timeout;
 
305
  self._concurrency_config.session_timeout
306
  )
307
  self._reaper_task: Optional[asyncio.Task[None]] = None
308
+ self._reaper_stop_event = asyncio.Event()
309
 
310
  def _default_env_name(self) -> str:
311
  factory = self._env_factory
 
396
 
397
  return valid_kwargs
398
 
399
+ async def _create_session(
400
+ self, mode: Optional[str | ServerMode] = None
401
+ ) -> tuple[str, Environment]:
402
  """
403
  Create a new WebSocket session with its own environment instance.
404
 
 
428
  self._session_executors[session_id] = executor
429
  self._sessions[session_id] = None # placeholder until env is ready
430
 
431
+ # Every await from here to registration runs with the slot reserved, so
432
+ # cancellation has to release it. CancelledError is not an Exception, so
433
+ # the handlers below never see it, and a surviving reservation is
434
+ # permanent: capacity counts _sessions, while the idle reaper only scans
435
+ # sessions that reached _session_info.
436
+ env: Optional[Environment] = None
437
+ stack: Optional[AsyncExitStack] = None
438
+ factory_future: Optional[Future[Environment]] = None
439
+ mcp_entry_task: Optional[asyncio.Task[Any]] = None
440
+ cleanup_task: Optional[asyncio.Task[None]] = None
441
+ creation_lock_acquired = False
442
+
443
+ def start_cleanup() -> asyncio.Task[None]:
444
+ # Startup failure and cancellation share one cleanup owner. Whoever
445
+ # gets here first starts the task; a later caller joins the same one
446
+ # instead of submitting a second env.close().
447
+ nonlocal cleanup_task
448
+ if cleanup_task is None:
449
+ cleanup_task = asyncio.create_task(
450
+ self._discard_reserved_session(
451
+ session_id,
452
+ executor,
453
+ env,
454
+ stack,
455
+ factory_future,
456
+ mcp_entry_task,
457
+ )
458
+ )
459
+ return cleanup_task
460
+
461
+ async def drain_cleanup(task: asyncio.Task[None]) -> None:
462
+ # ASGI cancel scopes may cancel a request repeatedly. Keep awaiting
463
+ # the shielded cleanup task until it reaches a terminal state so
464
+ # cancellation cannot escape while the reservation still exists.
465
+ try:
466
+ await asyncio.shield(task)
467
+ except asyncio.CancelledError:
468
+ while not task.done():
469
+ try:
470
+ await asyncio.shield(task)
471
+ except asyncio.CancelledError:
472
+ pass
473
+ task.result()
474
+ raise
475
+
476
  try:
477
+ if self._shared_session_creation_lock is not None:
478
+ await self._shared_session_creation_lock.acquire()
479
+ creation_lock_acquired = True
480
+
481
+ try:
482
+ # Create environment in the executor thread (outside lock).
483
+ # submit() plus wrap_future() is what run_in_executor() does
484
+ # internally; spelling it out keeps the thread's future, which is
485
+ # the only handle on an environment still being built when the
486
+ # await is cancelled.
487
+ loop = asyncio.get_event_loop()
488
+ factory_future = executor.submit(self._env_factory)
489
+ env = await asyncio.wrap_future(factory_future, loop=loop)
490
+ mode_val = (
491
+ mode.value
492
+ if isinstance(mode, ServerMode)
493
+ else (str(mode) if mode is not None else None)
494
+ )
495
+ if mode_val is not None and hasattr(env, "set_mode"):
496
+ env.set_mode(mode_val)
497
+ except Exception as e:
498
+ async with self._session_lock:
499
+ if executor is not self._shared_session_executor:
500
+ executor.shutdown(wait=False)
501
+ self._session_executors.pop(session_id, None)
502
+ self._sessions.pop(session_id, None)
503
+ factory_name = getattr(
504
+ self._env_factory, "__name__", str(self._env_factory)
505
+ )
506
+ raise EnvironmentFactoryError(factory_name) from e
507
+
508
+ # The factory result is delivered, so the shared executor thread is
509
+ # free. Release the creation lock before MCP startup: it exists to
510
+ # order factory calls (and disposal of a factory cancelled
511
+ # mid-flight) on that one thread, and holding it through an MCP
512
+ # handshake lets a single stalled connection starve every later
513
+ # session's constructor. Cancellation during construction keeps the
514
+ # lock instead, so late-factory disposal still precedes the next
515
+ # constructor.
516
+ if creation_lock_acquired:
517
+ assert self._shared_session_creation_lock is not None
518
+ self._shared_session_creation_lock.release()
519
+ creation_lock_acquired = False
520
+
521
+ # Hold the MCP session open for the lifetime of this session,
522
+ # matching the WebSocket path's AsyncExitStack pattern. This
523
+ # prevents per-request MCP transport teardown/reconnection and
524
+ # preserves FastMCP session state (ctx.set_state / ctx.get_state)
525
+ # across HTTP calls within the same OpenEnv session.
526
+ stack = AsyncExitStack()
527
+ try:
528
+ mcp_session_factory = getattr(env, "mcp_session", None)
529
+ if callable(mcp_session_factory):
530
+ mcp_session_cm = cast(
531
+ AsyncContextManager[Any], mcp_session_factory()
532
+ )
533
+ # Enter in its own task and await it shielded. An entry that
534
+ # blocks before yielding may release resources in its own
535
+ # finally, and the stack cannot replay that cleanup: it
536
+ # registers the exit callback only once __aenter__ returns.
537
+ # Shielding keeps repeated cancellation off the entry, so
538
+ # the cleanup owner can cancel it exactly once and drain the
539
+ # unwind instead of aborting it part-way.
540
+ mcp_entry_task = asyncio.create_task(
541
+ stack.enter_async_context(mcp_session_cm)
542
+ )
543
+ await asyncio.shield(mcp_entry_task)
544
+ except Exception:
545
+ # MCP transport failed to start — clean up the reserved slot,
546
+ # the env, and the executor so they don't leak permanently
547
+ # against _max_concurrent_envs. Cancellation arriving mid-close
548
+ # joins this same task rather than closing the env twice.
549
+ await drain_cleanup(start_cleanup())
550
+ raise
551
+
552
  async with self._session_lock:
553
+ self._sessions[session_id] = env
554
+ self._session_stacks[session_id] = stack
555
+ if mode is not None:
556
+ self._session_modes[session_id] = mode_val
557
+ now = time.time()
558
+ self._session_info[session_id] = SessionInfo(
559
+ session_id=session_id,
560
+ created_at=current_time,
561
+ last_activity_at=now,
562
+ step_count=0,
563
+ environment_type=type(env).__name__,
564
+ )
565
+ except asyncio.CancelledError:
566
+ # Joins the cleanup already under way if startup failure began one,
567
+ # so the environment is closed by a single owner.
568
+ try:
569
+ await drain_cleanup(start_cleanup())
570
+ except asyncio.CancelledError:
571
+ pass
572
  raise
573
+ finally:
574
+ if creation_lock_acquired:
575
+ assert self._shared_session_creation_lock is not None
576
+ self._shared_session_creation_lock.release()
 
 
 
 
 
 
 
 
577
 
578
  return session_id, env
579
 
580
+ async def _discard_reserved_session(
581
+ self,
582
+ session_id: str,
583
+ executor: ThreadPoolExecutor,
584
+ env: Optional[Environment] = None,
585
+ stack: Optional[AsyncExitStack] = None,
586
+ factory_future: Optional[Future[Environment]] = None,
587
+ mcp_entry_task: Optional[asyncio.Task[Any]] = None,
588
+ ) -> None:
589
+ """
590
+ Release a session slot reserved by `_create_session` that never opened.
591
+
592
+ Drops every mapping the slot may have reached and closes whatever the
593
+ interrupted creation built, so the slot stops counting against
594
+ `max_concurrent_envs` and no environment outlives it.
595
+
596
+ Args:
597
+ session_id (`str`):
598
+ The reserved session ID to release.
599
+ executor (`ThreadPoolExecutor`):
600
+ The executor reserved alongside the slot.
601
+ env (`Environment`, *optional*):
602
+ The environment, if the factory already returned one.
603
+ stack (`AsyncExitStack`, *optional*):
604
+ The MCP session stack, if one was already entered.
605
+ factory_future (`Future`, *optional*):
606
+ The factory's thread future, if the factory call was reached.
607
+ Used to close an environment the thread is still building.
608
+ mcp_entry_task (`asyncio.Task`, *optional*):
609
+ The in-flight MCP session entry, if MCP startup was reached.
610
+ Cancelled and drained here so an entry interrupted before it
611
+ yielded can finish releasing what it had already acquired.
612
+ """
613
+ if mcp_entry_task is not None:
614
+ # Cancel at most once: a second cancellation would abort the entry's
615
+ # own unwind, and the stack holds no exit callback to replay it.
616
+ if not mcp_entry_task.done():
617
+ mcp_entry_task.cancel()
618
+ try:
619
+ await mcp_entry_task
620
+ except (asyncio.CancelledError, Exception):
621
+ # A cancelled or failed entry has unwound itself. If it did
622
+ # finish, `stack` owns the context and closes it below.
623
+ pass
624
+
625
+ if env is None and factory_future is not None:
626
+ # Cancelling the await can cancel a queued future, but cannot stop a
627
+ # factory whose executor thread is already running. In that case,
628
+ # keep the capacity reservation until its result can be disposed of.
629
+ if not factory_future.cancel():
630
+ try:
631
+ env = await asyncio.wrap_future(factory_future)
632
+ except (asyncio.CancelledError, Exception):
633
+ # A cancelled or failed factory produced no environment to
634
+ # close. Its capacity reservation still has to be released.
635
+ env = None
636
+
637
+ await self._cleanup_session_resources(env, executor, stack)
638
+ async with self._session_lock:
639
+ self._sessions.pop(session_id, None)
640
+ self._session_executors.pop(session_id, None)
641
+ self._session_stacks.pop(session_id, None)
642
+ self._session_info.pop(session_id, None)
643
+ self._session_modes.pop(session_id, None)
644
+
645
  async def _destroy_session(self, session_id: str) -> None:
646
  """
647
  Destroy a WebSocket session and cleanup resources.
 
655
  executor = self._session_executors.pop(session_id, None)
656
  stack = self._session_stacks.pop(session_id, None)
657
  self._session_info.pop(session_id, None)
658
+ self._session_modes.pop(session_id, None)
659
  self._session_websocket_attachments.discard(session_id)
660
  self._session_pending_closes.discard(session_id)
661
 
 
724
  interval = max(timeout / 4, 5.0) # check frequently enough
725
  while True:
726
  try:
727
+ try:
728
+ await asyncio.wait_for(
729
+ self._reaper_stop_event.wait(), timeout=interval
730
+ )
731
+ return
732
+ except asyncio.TimeoutError:
733
+ pass
734
  now = time.time()
735
  stale_ids: list[str] = []
736
  async with self._session_lock:
737
  for sid, info in self._session_info.items():
738
  if (
739
  sid not in self._session_websocket_attachments
740
+ and sid not in self._session_operations_in_flight
741
  and now - info.last_activity_at > timeout
742
  ):
743
  stale_ids.append(sid)
744
  for sid in stale_ids:
745
+ if self._reaper_stop_event.is_set():
746
+ return
747
  # Re-check under lock: activity may have arrived since
748
  # the snapshot was taken, making this session active again.
749
  # Refresh `now` so slow _destroy_session calls don't cause
 
754
  if (
755
  info is None
756
  or sid in self._session_websocket_attachments
757
+ or sid in self._session_operations_in_flight
758
  or (now - info.last_activity_at) <= timeout
759
  ):
760
  continue
 
770
  def _start_reaper(self) -> None:
771
  """Start the idle-session reaper if a timeout is configured."""
772
  if self._session_idle_timeout_s is not None and self._reaper_task is None:
773
+ self._reaper_stop_event.clear()
774
  self._reaper_task = asyncio.create_task(self._reap_idle_sessions())
775
 
776
+ async def _stop_reaper(self) -> None:
777
+ """Stop the reaper after any in-progress session cleanup finishes."""
778
  if self._reaper_task is not None:
779
+ self._reaper_stop_event.set()
780
+ await self._reaper_task
781
  self._reaper_task = None
782
 
783
  def get_session_info(self, session_id: str) -> Optional[SessionInfo]:
 
1082
  f"Invalid mode: '{mode}'. Must be one of: {valid_modes}"
1083
  )
1084
 
1085
+ # Only explicitly provisioned simulation servers accept validation controls.
1086
+ validation_token = os.environ.get("OPENENV_VALIDATION_TOKEN", "")
1087
+ validation_enabled = (
1088
+ mode == ServerMode.SIMULATION and 32 <= len(validation_token) <= 256
1089
+ )
1090
+
1091
+ # Wire up session lifecycle via app events
1092
  server_ref = self
1093
 
1094
  async def _start_session_reaper() -> None:
1095
  server_ref._start_reaper()
1096
 
1097
+ async def _shutdown_sessions() -> None:
1098
+ await server_ref._stop_reaper()
1099
+ async with server_ref._session_lock:
1100
+ session_ids = list(server_ref._sessions)
1101
+ for session_id in session_ids:
1102
+ await server_ref._destroy_session(session_id)
1103
  if server_ref._shared_session_executor is not None:
1104
  server_ref._shared_session_executor.shutdown(wait=True)
1105
 
1106
  if not getattr(app.router, "_openenv_reaper_registered", False):
1107
  app.router.on_startup.append(_start_session_reaper)
1108
+ app.router.on_shutdown.append(_shutdown_sessions)
1109
  app.router._openenv_reaper_registered = True # type: ignore[attr-defined]
1110
 
1111
  # Helper function to handle reset endpoint
 
1206
  request_id=request_id,
1207
  )
1208
  try:
1209
+ created_session_id, _ = await self._create_session(mode=mode)
1210
  except SessionCapacityError as e:
1211
  return JsonRpcResponse.error_response(
1212
  JsonRpcErrorCode.SERVER_ERROR,
 
1246
  )
1247
 
1248
  async with self._session_lock:
1249
+ session_mode = self._session_modes.get(target_session_id)
1250
+ if (
1251
+ (
1252
+ target_session_id in self._sessions
1253
+ or target_session_id in self._session_websocket_attachments
1254
+ )
1255
+ and session_mode is not None
1256
+ and session_mode != mode.value
1257
+ ):
1258
+ return JsonRpcResponse.error_response(
1259
+ JsonRpcErrorCode.INVALID_PARAMS,
1260
+ f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",
1261
+ request_id=request_id,
1262
+ )
1263
+
1264
  if target_session_id in self._session_websocket_attachments:
1265
  env = _MISSING
1266
  attached = True
 
1274
  executor = self._session_executors.pop(target_session_id, None)
1275
  stack = self._session_stacks.pop(target_session_id, None)
1276
  self._session_info.pop(target_session_id, None)
1277
+ self._session_modes.pop(target_session_id, None)
1278
  elif not attached:
1279
  executor = None
1280
  stack = None
 
1328
  elif requested_session_id:
1329
  async with self._session_lock:
1330
  _env = self._sessions.get(requested_session_id, _MISSING)
1331
+ session_mode = self._session_modes.get(requested_session_id)
1332
 
1333
  if _env is _MISSING:
1334
  return JsonRpcResponse.error_response(
 
1337
  request_id=request_id,
1338
  )
1339
 
1340
+ if session_mode is not None and session_mode != mode.value:
1341
+ return JsonRpcResponse.error_response(
1342
+ JsonRpcErrorCode.INVALID_PARAMS,
1343
+ f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",
1344
+ request_id=request_id,
1345
+ )
1346
+
1347
  if _env is None:
1348
  return JsonRpcResponse.error_response(
1349
  JsonRpcErrorCode.INVALID_REQUEST,
 
1355
  managed_session_id = requested_session_id
1356
  else:
1357
  _env = self._env_factory()
1358
+ if hasattr(_env, "set_mode"):
1359
+ _env.set_mode(mode.value)
1360
  should_close = True
1361
  try:
1362
  mcp_client = getattr(_env, "mcp_client", None)
 
1381
  }
1382
 
1383
  if method == McpMethod.TOOLS_LIST:
1384
+ if hasattr(_env, "_async_handle_list_tools"):
1385
+ obs = await _env._async_handle_list_tools()
1386
+ if obs.metadata and "error" in obs.metadata:
1387
+ return JsonRpcResponse.error_response(
1388
+ JsonRpcErrorCode.INTERNAL_ERROR,
1389
+ obs.metadata["error"],
1390
+ request_id=request_id,
1391
+ )
1392
+ tools = [
1393
+ {
1394
+ "name": t.name,
1395
+ "description": t.description or "",
1396
+ "inputSchema": t.input_schema,
1397
+ }
1398
+ for t in obs.tools
1399
+ ]
1400
+ return JsonRpcResponse.success(
1401
+ result={"tools": tools},
1402
+ request_id=request_id,
1403
+ )
1404
+
1405
  # Check if environment is MCP-enabled
1406
  if mcp_client is None and mcp_server is None:
1407
  if supports_mcp_style_actions:
 
1424
  request_id=request_id,
1425
  )
1426
  return JsonRpcResponse.error_response(
1427
+ JsonRpcErrorCode.METHOD_NOT_FOUND,
1428
  "Environment does not support MCP",
1429
  request_id=request_id,
1430
  )
 
1440
  return JsonRpcResponse.success(
1441
  result={
1442
  "tools": [
1443
+ t.model_dump(by_alias=True)
1444
  if hasattr(t, "model_dump")
1445
  else dict(t)
1446
  for t in tools
 
1481
  request_id=request_id,
1482
  )
1483
 
1484
+ if hasattr(_env, "_mode_tools") and any(
1485
+ m is not None for m in _env._mode_tools.get(tool_name, {})
1486
+ ):
1487
+ obs = await _env._async_handle_call_tool(
1488
+ CallToolAction(tool_name=tool_name, arguments=arguments)
1489
+ )
1490
+ if obs.error:
1491
+ err_code = (
1492
+ JsonRpcErrorCode.INVALID_PARAMS
1493
+ if obs.error.error_type
1494
+ in (
1495
+ ToolErrorType.INVALID_ARGS,
1496
+ ToolErrorType.TOOL_NOT_FOUND,
1497
+ )
1498
+ else JsonRpcErrorCode.INTERNAL_ERROR
1499
+ )
1500
+ return JsonRpcResponse.error_response(
1501
+ err_code,
1502
+ obs.error.message,
1503
+ request_id=request_id,
1504
+ )
1505
+ return JsonRpcResponse.success(
1506
+ result=_make_json_serializable(obs.result),
1507
+ request_id=request_id,
1508
+ )
1509
+
1510
  if mcp_client is None and mcp_server is None:
1511
  if supports_mcp_style_actions:
1512
  observation = await call_mcp_style_step(
 
1528
  request_id=request_id,
1529
  )
1530
  return JsonRpcResponse.error_response(
1531
+ JsonRpcErrorCode.METHOD_NOT_FOUND,
1532
  "Environment does not support MCP",
1533
  request_id=request_id,
1534
  )
 
1700
 
1701
  try:
1702
  # Create session with dedicated environment
1703
+ session_id, session_env = await self._create_session(mode=mode)
1704
  if session_env is None:
1705
  raise RuntimeError(
1706
  "Session environment not initialized for MCP websocket"
 
1947
  tags=["Schema"],
1948
  summary="Get all JSON schemas",
1949
  description="""
1950
+ Get JSON schemas for actions, observations, state, and reset parameters in a single response.
1951
 
1952
  Returns a combined schema object containing:
1953
  - **action**: JSON schema for actions accepted by this environment
1954
  - **observation**: JSON schema for observations returned by step
1955
  - **reset_observation**: JSON schema for observations returned by reset
1956
  - **state**: JSON schema for environment state objects
1957
+ - **reset**: JSON schema for reset parameters accepted by this environment
1958
 
1959
  This is more efficient than calling individual schema endpoints and provides
1960
  all schema information needed to interact with the environment.
 
1977
  "type": "object",
1978
  "properties": {"step_count": {"type": "integer"}},
1979
  },
1980
+ "reset": {
1981
+ "type": "object",
1982
+ "properties": {"seed": {"type": "integer"}},
1983
+ },
1984
  }
1985
  }
1986
  },
 
1994
  observation=self.observation_cls.model_json_schema(),
1995
  reset_observation=self.reset_observation_cls.model_json_schema(),
1996
  state=self.state_cls.model_json_schema(),
1997
+ reset=self.reset_cls.model_json_schema(),
1998
  )
1999
 
2000
  # Register MCP endpoint for production mode (direct MCP access)
 
2045
  session_env = None
2046
  owns_session = False
2047
  attached_session = False
2048
+ telemetry = None
2049
+ operations_started = False
2050
 
2051
  try:
2052
  requested_session_id = websocket.query_params.get("session_id")
 
2055
  attached_env = self._sessions.get(
2056
  requested_session_id, _MISSING
2057
  )
2058
+ session_mode = self._session_modes.get(requested_session_id)
2059
  if attached_env is _MISSING:
2060
  raise RuntimeError(
2061
  f"Unknown session_id: {requested_session_id}"
2062
  )
2063
+ if session_mode is not None and session_mode != mode.value:
2064
+ raise RuntimeError(
2065
+ f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'"
2066
+ )
2067
  if attached_env is None:
2068
  raise RuntimeError(
2069
  f"Session {requested_session_id} is still initializing"
 
2079
  attached_session = True
2080
  self._update_session_activity(session_id)
2081
  else:
2082
+ session_id, session_env = await self._create_session(mode=mode)
2083
  owns_session = True
2084
 
2085
  if session_env is None:
 
2102
  # Receive message from client
2103
  raw_message = await websocket.receive_text()
2104
 
2105
+ # The reaper or shutdown may have destroyed this
2106
+ # session (closing its env and freeing its slot).
2107
+ if session_id not in self._sessions:
2108
+ error_resp = WSErrorResponse(
2109
+ data={
2110
+ "message": "Session expired or was closed; "
2111
+ "open a new connection",
2112
+ "code": WSErrorCode.SESSION_ERROR,
2113
+ }
2114
+ )
2115
+ await websocket.send_text(error_resp.model_dump_json())
2116
+ break
2117
+
2118
  try:
2119
  message_dict = json.loads(raw_message)
2120
  except json.JSONDecodeError as e:
 
2129
 
2130
  msg_type = message_dict.get("type", "")
2131
 
2132
+ if msg_type in {"validation_open", "validation_read"}:
2133
+ # Do not return Pydantic input/error details: these messages
2134
+ # contain credentials and must never echo or log them.
2135
+ try:
2136
+ if not validation_enabled or not owns_session:
2137
+ raise ValueError("Validation unavailable")
2138
+ if msg_type == "validation_open":
2139
+ auth = ValidationOpenMessage.model_validate(
2140
+ message_dict
2141
+ )
2142
+ if telemetry is not None or operations_started:
2143
+ raise ValueError("Validation already started")
2144
+ if not secrets.compare_digest(
2145
+ validation_token.encode(),
2146
+ auth.data.token.get_secret_value().encode(),
2147
+ ):
2148
+ raise ValueError("Unauthorized")
2149
+ telemetry = SessionTelemetry()
2150
+ response = ValidationOpenedResponse(
2151
+ data=ValidationOpenedData(
2152
+ capability=telemetry.capability
2153
+ )
2154
+ )
2155
+ else:
2156
+ auth = ValidationReadMessage.model_validate(
2157
+ message_dict
2158
+ )
2159
+ if telemetry is None or not telemetry.authorized(
2160
+ auth.data.capability.get_secret_value()
2161
+ ):
2162
+ raise ValueError("Unauthorized")
2163
+ response = ValidationResponse(
2164
+ data=telemetry.snapshot
2165
+ )
2166
+ except Exception:
2167
+ response = WSErrorResponse(
2168
+ data={
2169
+ "message": "Validation unavailable or unauthorized",
2170
+ "code": WSErrorCode.VALIDATION_ERROR,
2171
+ }
2172
+ )
2173
+ await websocket.send_text(response.model_dump_json())
2174
+ continue
2175
+
2176
+ seed_acceptance = None
2177
+ before_scores = None
2178
+ if msg_type in {"reset", "step", "state"}:
2179
+ operations_started = True
2180
+ if telemetry is not None and msg_type == "step":
2181
+ try:
2182
+ before_scores = rubric_counts(
2183
+ getattr(session_env, "rubric", None)
2184
+ )
2185
+ except Exception:
2186
+ telemetry.snapshot.rubric_error = (
2187
+ "Rubric introspection unavailable"
2188
+ )
2189
+
2190
+ in_flight = self._session_operations_in_flight
2191
+ in_flight[session_id] = in_flight.get(session_id, 0) + 1
2192
+ self._update_session_activity(session_id)
2193
  try:
2194
  match msg_type:
2195
  case "reset":
 
2221
  )
2222
  )
2223
 
2224
+ if telemetry is not None:
2225
+ seed_acceptance = SeedAcceptance(
2226
+ requested="seed" in msg.data,
2227
+ value=msg.data.get("seed"),
2228
+ accepted="seed" in valid_kwargs,
2229
+ )
2230
 
2231
  response = WSObservationResponse(
2232
  data=serialize_observation(observation),
 
2303
  }
2304
  )
2305
 
2306
+ if telemetry is not None and msg_type in {
2307
+ "reset",
2308
+ "step",
2309
+ "state",
2310
+ }:
2311
+ nodes = None
2312
+ try:
2313
+ if msg_type in {"reset", "step"}:
2314
+ nodes = rubric_snapshot(
2315
+ getattr(session_env, "rubric", None),
2316
+ before_scores,
2317
+ )
2318
+ except Exception:
2319
+ nodes = []
2320
+ telemetry.snapshot.rubric_error = (
2321
+ "Rubric introspection unavailable"
2322
+ )
2323
+ telemetry.append(
2324
+ msg_type,
2325
+ message_dict,
2326
+ response.model_dump(mode="json"),
2327
+ seed=seed_acceptance,
2328
+ rubric=nodes,
2329
+ )
2330
  await websocket.send_text(response.model_dump_json())
2331
 
2332
  except ValidationError as e:
2333
+ if telemetry is not None and msg_type in {
2334
+ "reset",
2335
+ "step",
2336
+ "state",
2337
+ }:
2338
+ telemetry.incomplete("Session operation failed")
2339
  error_resp = WSErrorResponse(
2340
  data={
2341
  "message": "Invalid message",
 
2345
  )
2346
  await websocket.send_text(error_resp.model_dump_json())
2347
  except Exception as e:
2348
+ if telemetry is not None and msg_type in {
2349
+ "reset",
2350
+ "step",
2351
+ "state",
2352
+ }:
2353
+ telemetry.incomplete("Session operation failed")
2354
  error_resp = WSErrorResponse(
2355
  data={
2356
  "message": str(e),
 
2358
  }
2359
  )
2360
  await websocket.send_text(error_resp.model_dump_json())
2361
+ finally:
2362
+ in_flight[session_id] -= 1
2363
+ if in_flight[session_id] == 0:
2364
+ del in_flight[session_id]
2365
+ self._update_session_activity(session_id)
2366
 
2367
  except WebSocketDisconnect:
2368
  pass
 
2422
  *,
2423
  mode: Optional[ServerMode | str] = None,
2424
  reset_observation_cls: Optional[Type[Observation]] = None,
2425
+ reset_cls: Type[ResetRequest] = ResetRequest,
2426
  ) -> FastAPI:
2427
  """
2428
  Create a FastAPI application with or without web interface.
 
2467
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2468
  The `State` subclass this environment reports, used for the `/state`
2469
  response model and the `state` entry of `/schema`.
2470
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
2471
+ The `ResetRequest` subclass describing this environment's reset parameters,
2472
+ published as the `reset` entry of `/schema`. Not used for validation.
2473
  mode (`ServerMode` or `str`, *optional*):
2474
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2475
  environment variable, defaulting to simulation.
 
2497
  max_concurrent_envs,
2498
  concurrency_config,
2499
  state_cls=state_cls,
2500
+ reset_cls=reset_cls,
2501
  reset_observation_cls=reset_observation_cls,
2502
  gradio_builder=gradio_builder,
2503
  custom_tab_name=custom_tab_name,
 
2516
  concurrency_config,
2517
  env_name=env_name,
2518
  state_cls=state_cls,
2519
+ reset_cls=reset_cls,
2520
  reset_observation_cls=reset_observation_cls,
2521
  mode=mode,
2522
  )
 
2533
  *,
2534
  mode: Optional[ServerMode | str] = None,
2535
  reset_observation_cls: Optional[Type[Observation]] = None,
2536
+ reset_cls: Type[ResetRequest] = ResetRequest,
2537
  ) -> FastAPI:
2538
  """
2539
  Create a FastAPI application with comprehensive documentation.
 
2559
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2560
  The `State` subclass this environment reports, used for the `/state`
2561
  response model and the `state` entry of `/schema`.
2562
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
2563
+ The `ResetRequest` subclass describing this environment's reset parameters,
2564
+ published as the `reset` entry of `/schema`. Not used for validation.
2565
  mode (`ServerMode` or `str`, *optional*):
2566
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2567
  environment variable, defaulting to simulation.
 
2589
  * **Environment Reset**: Initialize or restart episodes
2590
  * **Action Execution**: Send actions and receive observations
2591
  * **State Inspection**: Query current environment state
2592
+ * **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters
2593
 
2594
  ## Workflow
2595
 
 
2619
  },
2620
  {
2621
  "name": "Schema",
2622
+ "description": "JSON Schema endpoints for actions, observations, state, and reset parameters",
2623
  },
2624
  {"name": "Health", "description": "Service health and status checks"},
2625
  ],
 
2628
  openapi_url="/openapi.json",
2629
  contact={
2630
  "name": "OpenEnv Team",
2631
+ "url": "https://github.com/openenv/OpenEnv",
2632
  },
2633
  license_info={
2634
  "name": "BSD-3-Clause",
2635
+ "url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE",
2636
  },
2637
  )
2638
 
 
2644
  concurrency_config=concurrency_config,
2645
  env_name=env_name,
2646
  state_cls=state_cls,
2647
+ reset_cls=reset_cls,
2648
  reset_observation_cls=reset_observation_cls,
2649
  )
2650
  if mode is None:
2651
  mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value)
2652
  server.register_routes(app, mode=mode)
2653
+
2654
+ from .security import attach_guard
2655
+
2656
+ attach_guard(app)
2657
  return app
src/core/env_server/interfaces.py CHANGED
@@ -105,7 +105,7 @@ class TaskProvider(Protocol):
105
 
106
  Selecting a task is not part of this protocol — pass the chosen split and
107
  index to `reset()` instead. See the
108
- [Task API guide](https://huggingface.co/docs/openenv/guides/task-api).
109
 
110
  Examples:
111
 
@@ -223,7 +223,7 @@ class Transform(ABC, Generic[ObsT]):
223
  class Environment(ABC, Generic[ActT, ObsT, StateT]):
224
  """Base class for all environment servers following Gym/Gymnasium API.
225
 
226
- See [rfcs/004-rubrics.md](https://github.com/huggingface/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details.
227
 
228
  Args:
229
  transform (`Transform`, *optional*):
 
105
 
106
  Selecting a task is not part of this protocol — pass the chosen split and
107
  index to `reset()` instead. See the
108
+ [Task API guide](https://openenv.github.io/OpenEnv/main/guides/task-api).
109
 
110
  Examples:
111
 
 
223
  class Environment(ABC, Generic[ActT, ObsT, StateT]):
224
  """Base class for all environment servers following Gym/Gymnasium API.
225
 
226
+ See [rfcs/004-rubrics.md](https://github.com/openenv/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details.
227
 
228
  Args:
229
  transform (`Transform`, *optional*):
src/core/env_server/mcp_environment.py CHANGED
@@ -86,17 +86,17 @@ VALID_MODES = {"production", "simulation"}
86
 
87
  def get_server_tools(mcp_server: Any) -> Dict[str, Any]:
88
  """
89
- Get tools from a FastMCP server, compatible with both 2.x and 3.x.
90
 
91
  Returns:
92
  Dictionary mapping tool names to tool objects.
93
  """
94
- # FastMCP 2.x: get_tools() returns dict {name: Tool}
95
  if hasattr(mcp_server, "get_tools"):
96
  result = run_async_safely(mcp_server.get_tools())
97
  if isinstance(result, dict):
98
  return result
99
- # FastMCP 3.x: list_tools() returns list of Tool objects
100
  if hasattr(mcp_server, "list_tools"):
101
  tools_list = run_async_safely(mcp_server.list_tools())
102
  return {t.name: t for t in tools_list}
@@ -108,7 +108,7 @@ def _tool_from_server_tool(tool: Any) -> Tool:
108
  return Tool(
109
  name=tool.name,
110
  description=tool.description or "",
111
- input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {},
112
  )
113
 
114
 
@@ -187,7 +187,9 @@ class MCPEnvironment(Environment):
187
  self._validate_tool_names(mcp_server)
188
 
189
  self.mcp_server = mcp_server
190
- self.mcp_client = Client(mcp_server)
 
 
191
 
192
  # Track mode-specific tools: {tool_name: {mode: func}}
193
  # mode can be "production", "simulation", or None (available in all modes)
@@ -195,6 +197,11 @@ class MCPEnvironment(Environment):
195
 
196
  # Track tool schemas for list_tools: {tool_name: {mode: schema}}
197
  self._mode_tool_schemas = defaultdict(dict)
 
 
 
 
 
198
 
199
  def _require_mcp_client(self) -> Any:
200
  """Return MCP client or raise if environment has been closed."""
@@ -249,7 +256,7 @@ class MCPEnvironment(Environment):
249
 
250
  def _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]:
251
  """
252
- Get tools from a FastMCP server, compatible with both 2.x and 3.x.
253
 
254
  Returns:
255
  Dictionary mapping tool names to tool objects.
@@ -496,7 +503,8 @@ class MCPEnvironment(Environment):
496
  tools_result = await self._async_list_tools()
497
  tools = []
498
  for tool in tools_result:
499
- if tool.name not in self._mode_tool_schemas:
 
500
  tools.append(_tool_from_server_tool(tool))
501
  for mode_schemas in self._mode_tool_schemas.values():
502
  schema = _schema_for_mode(mode_schemas, current_mode)
@@ -519,21 +527,12 @@ class MCPEnvironment(Environment):
519
  tool_name = action.tool_name
520
  current_mode = getattr(self, "_mode", None)
521
 
522
- if tool_name in self._mode_tools:
523
- mode_info = self._mode_tools[tool_name]
524
  if None in mode_info:
525
  func = mode_info[None]
526
  elif current_mode in mode_info:
527
  func = mode_info[current_mode]
528
- else:
529
- return CallToolObservation(
530
- tool_name=tool_name,
531
- result=None,
532
- error=ToolError(
533
- error_type=ToolErrorType.TOOL_NOT_FOUND,
534
- message=f"Tool '{tool_name}' not available in {current_mode} mode",
535
- ),
536
- )
537
  try:
538
  if inspect.iscoroutinefunction(func):
539
  result = await func(**action.arguments)
 
86
 
87
  def get_server_tools(mcp_server: Any) -> Dict[str, Any]:
88
  """
89
+ Get tools from a FastMCP server.
90
 
91
  Returns:
92
  Dictionary mapping tool names to tool objects.
93
  """
94
+ # FastMCP server tools are exposed as a name-to-tool mapping.
95
  if hasattr(mcp_server, "get_tools"):
96
  result = run_async_safely(mcp_server.get_tools())
97
  if isinstance(result, dict):
98
  return result
99
+ # Some server adapters expose the tools as a list instead.
100
  if hasattr(mcp_server, "list_tools"):
101
  tools_list = run_async_safely(mcp_server.list_tools())
102
  return {t.name: t for t in tools_list}
 
108
  return Tool(
109
  name=tool.name,
110
  description=tool.description or "",
111
+ input_schema=tool.input_schema,
112
  )
113
 
114
 
 
187
  self._validate_tool_names(mcp_server)
188
 
189
  self.mcp_server = mcp_server
190
+ # OpenEnv sessions keep MCP state across tool calls. FastMCP 4's default
191
+ # modern protocol is sessionless, so use its supported legacy handshake.
192
+ self.mcp_client = Client(mcp_server, mode="legacy")
193
 
194
  # Track mode-specific tools: {tool_name: {mode: func}}
195
  # mode can be "production", "simulation", or None (available in all modes)
 
197
 
198
  # Track tool schemas for list_tools: {tool_name: {mode: schema}}
199
  self._mode_tool_schemas = defaultdict(dict)
200
+ self._mode: Optional[str] = None
201
+
202
+ def set_mode(self, mode: Optional[str]) -> None:
203
+ """Set the active mode ('production' or 'simulation') for mode-aware tools."""
204
+ self._mode = mode
205
 
206
  def _require_mcp_client(self) -> Any:
207
  """Return MCP client or raise if environment has been closed."""
 
256
 
257
  def _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]:
258
  """
259
+ Get tools from a FastMCP server.
260
 
261
  Returns:
262
  Dictionary mapping tool names to tool objects.
 
503
  tools_result = await self._async_list_tools()
504
  tools = []
505
  for tool in tools_result:
506
+ mode_schemas = self._mode_tool_schemas.get(tool.name, {})
507
+ if _schema_for_mode(mode_schemas, current_mode) is None:
508
  tools.append(_tool_from_server_tool(tool))
509
  for mode_schemas in self._mode_tool_schemas.values():
510
  schema = _schema_for_mode(mode_schemas, current_mode)
 
527
  tool_name = action.tool_name
528
  current_mode = getattr(self, "_mode", None)
529
 
530
+ mode_info = self._mode_tools.get(tool_name, {})
531
+ if None in mode_info or current_mode in mode_info:
532
  if None in mode_info:
533
  func = mode_info[None]
534
  elif current_mode in mode_info:
535
  func = mode_info[current_mode]
 
 
 
 
 
 
 
 
 
536
  try:
537
  if inspect.iscoroutinefunction(func):
538
  result = await func(**action.arguments)
src/core/env_server/security.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """Optional fastapi-guard security middleware for environment servers.
4
+
5
+ Opt-in via the `OPENENV_GUARD_*` environment variables. When disabled (the
6
+ default), `attach_guard` is a no-op and environment servers behave exactly as
7
+ before.
8
+
9
+ Install the extra with `pip install "openenv[security]"` and enable with
10
+ `OPENENV_GUARD_ENABLED=1` to get IP block/allow lists, rate limiting,
11
+ user-agent blocking, penetration-attempt detection with auto-ban, and optional
12
+ Redis-backed distributed state (fastapi-guard).
13
+
14
+ Health and schema endpoints are excluded from detection checks so
15
+ orchestrators can probe the server; global IP allow/block lists are still
16
+ enforced on those paths.
17
+
18
+ WebSocket connections (`/ws`, `/mcp`, `/harness`, `/ws/ui`) get the same
19
+ checks on the handshake: ban, IP lists, a separate rate-limit bucket and
20
+ penetration detection on the path, query and headers. A refused handshake is
21
+ closed before `accept()`, so the client gets HTTP 403 on the upgrade and no
22
+ socket. Messages on an accepted connection are not screened, for the same
23
+ reason request bodies are not. With Redis configured, the guard initializes at
24
+ startup; while Redis is unreachable a handshake is closed with 1013 and HTTP
25
+ requests are refused.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ from contextlib import asynccontextmanager
32
+ from typing import Any
33
+
34
+ from starlette import status
35
+ from starlette.exceptions import WebSocketException
36
+ from starlette.websockets import WebSocket
37
+
38
+ DEFAULT_EXCLUDED_PATHS = [
39
+ "/health",
40
+ "/schema",
41
+ "/metadata",
42
+ "/docs",
43
+ "/redoc",
44
+ "/openapi.json",
45
+ ]
46
+ # Empty by default on purpose: trusting private-range peers would let
47
+ # any of them spoof X-Forwarded-For past the blocklist and rate limits.
48
+ # Behind a reverse proxy, list the proxy's addresses in
49
+ # OPENENV_GUARD_TRUSTED_PROXIES.
50
+ DEFAULT_TRUSTED_PROXIES = ""
51
+
52
+
53
+ def _env_list(name: str, default: str = "") -> list[str]:
54
+ raw = os.environ.get(name, default)
55
+ return [item.strip() for item in raw.split(",") if item.strip()]
56
+
57
+
58
+ def _env_bool(name: str) -> bool:
59
+ raw = os.environ.get(name)
60
+ if raw is None or not raw.strip():
61
+ return False
62
+ normalized = raw.strip().lower()
63
+ if normalized in ("1", "true", "yes", "on"):
64
+ return True
65
+ if normalized in ("0", "false", "no", "off"):
66
+ return False
67
+ msg = f"{name} must be a boolean (1/true/yes/on or 0/false/no/off), got {raw!r}"
68
+ raise ValueError(msg)
69
+
70
+
71
+ def _build_security_config() -> Any:
72
+ from guard import SecurityConfig
73
+
74
+ kwargs: dict[str, Any] = {
75
+ "enable_rate_limiting": True,
76
+ "rate_limit": int(os.environ.get("OPENENV_GUARD_RATE_LIMIT", "100")),
77
+ "rate_limit_window": int(
78
+ os.environ.get("OPENENV_GUARD_RATE_LIMIT_WINDOW", "60")
79
+ ),
80
+ "enable_ip_banning": True,
81
+ "auto_ban_threshold": int(
82
+ os.environ.get("OPENENV_GUARD_AUTO_BAN_THRESHOLD", "10")
83
+ ),
84
+ "auto_ban_duration": int(
85
+ os.environ.get("OPENENV_GUARD_AUTO_BAN_DURATION", "300")
86
+ ),
87
+ # Environment/request bodies are model input (observations, prompts,
88
+ # completions), not commands this server executes: signature-scanning
89
+ # them false-positives on ordinary content. URL, query, and header
90
+ # screening stay on.
91
+ "detection_scan_body": False,
92
+ "enable_penetration_detection": True,
93
+ # In-memory state unless a Redis URL is configured: never implicitly
94
+ # depend on a Redis server being reachable at localhost.
95
+ "enable_redis": False,
96
+ "blacklist": tuple(_env_list("OPENENV_GUARD_BLOCKED_IPS")),
97
+ "blocked_user_agents": _env_list("OPENENV_GUARD_BLOCKED_USER_AGENTS"),
98
+ "trusted_proxies": tuple(
99
+ _env_list("OPENENV_GUARD_TRUSTED_PROXIES", DEFAULT_TRUSTED_PROXIES)
100
+ ),
101
+ "trusted_proxy_depth": int(
102
+ os.environ.get("OPENENV_GUARD_TRUSTED_PROXY_DEPTH", "1")
103
+ ),
104
+ "exclude_paths": DEFAULT_EXCLUDED_PATHS,
105
+ # fastapi-guard sends security headers unless this is None, and its
106
+ # X-Frame-Options: SAMEORIGIN stops a Space page from framing the app.
107
+ "security_headers": None,
108
+ }
109
+
110
+ allowed_ips = _env_list("OPENENV_GUARD_ALLOWED_IPS")
111
+ if allowed_ips:
112
+ kwargs["whitelist"] = tuple(allowed_ips)
113
+
114
+ redis_url = os.environ.get("OPENENV_GUARD_REDIS_URL")
115
+ if redis_url:
116
+ kwargs["enable_redis"] = True
117
+ kwargs["redis_url"] = redis_url
118
+
119
+ return SecurityConfig(**kwargs)
120
+
121
+
122
+ class _WebSocketGuardMiddleware:
123
+ # SecurityMiddleware is a BaseHTTPMiddleware, which never sees websocket
124
+ # scopes, so every handshake goes through fastapi-guard's guard_websocket.
125
+ def __init__(self, app: Any, config: Any) -> None:
126
+ from guard import guard_websocket
127
+ from guard.lifespan import _find_security_redis_handler, guard_startup
128
+
129
+ self.app = app
130
+ self.config = config
131
+ self.guard_websocket = guard_websocket
132
+ # guard_websocket reads Redis through this; None means not connected.
133
+ self.find_redis = _find_security_redis_handler
134
+ self.guard_startup = guard_startup
135
+
136
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
137
+ if scope["type"] == "websocket":
138
+ websocket = WebSocket(scope, receive, send)
139
+ try:
140
+ if not await self._redis_ready(scope["app"]):
141
+ # The HTTP side refuses too until Redis is reachable.
142
+ raise WebSocketException(
143
+ code=status.WS_1013_TRY_AGAIN_LATER,
144
+ reason="Service temporarily unavailable",
145
+ )
146
+ await self.guard_websocket(websocket)
147
+ except WebSocketException as exc:
148
+ await websocket.close(code=exc.code, reason=exc.reason)
149
+ return
150
+ await self.app(scope, receive, send)
151
+
152
+ async def _redis_ready(self, app: Any) -> bool:
153
+ if not self.config.enable_redis or self.find_redis(app) is not None:
154
+ return True
155
+ # Retry on each handshake, like the HTTP side's first request.
156
+ await self.guard_startup(app)
157
+ return self.find_redis(app) is not None
158
+
159
+
160
+ def attach_guard(app: Any) -> None:
161
+ """Add the fastapi-guard middleware to `app` when enabled via env.
162
+
163
+ No-op unless OPENENV_GUARD_ENABLED is set to 1/true/yes/on.
164
+ """
165
+ if not _env_bool("OPENENV_GUARD_ENABLED"):
166
+ return
167
+ if getattr(app.state, "guard_attached", False):
168
+ return
169
+ try:
170
+ from guard import SecurityMiddleware
171
+ from guard.lifespan import guard_lifespan
172
+ except ImportError as exc:
173
+ raise ImportError(
174
+ "OPENENV_GUARD_ENABLED requires fastapi-guard. "
175
+ 'Install it with: pip install "openenv[security]"'
176
+ ) from exc
177
+
178
+ config = _build_security_config()
179
+ app.add_middleware(SecurityMiddleware, config=config)
180
+ app.add_middleware(_WebSocketGuardMiddleware, config=config)
181
+ # Initialize the guard (Redis included) at startup, so a WebSocket-only
182
+ # worker never runs on in-memory state.
183
+ existing_lifespan = app.router.lifespan_context
184
+
185
+ @asynccontextmanager
186
+ async def lifespan(app: Any):
187
+ async with guard_lifespan(app):
188
+ async with existing_lifespan(app) as state:
189
+ yield state
190
+
191
+ app.router.lifespan_context = lifespan
192
+ app.state.guard_attached = True
src/core/env_server/session_telemetry.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """Bounded, opt-in evidence emitted by the subject's replay session."""
4
+
5
+ import json
6
+ import secrets
7
+ from typing import Any, Literal
8
+
9
+ from openenv.core.rubrics.base import Rubric
10
+ from openenv.core.rubrics.containers import Gate, Sequential, WeightedSum
11
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr
12
+
13
+ MAX_TELEMETRY_BYTES = 8 * 1024 * 1024
14
+ MAX_TRAJECTORY_ACTIONS = 100
15
+ MAX_TRAJECTORY_RECORDS = 202
16
+ MAX_RUBRIC_NODES = 128
17
+
18
+
19
+ class _WireModel(BaseModel):
20
+ model_config = ConfigDict(extra="forbid", strict=True)
21
+
22
+
23
+ class ValidationOpenData(_WireModel):
24
+ schema_version: Literal[1]
25
+ token: SecretStr = Field(min_length=32, max_length=256)
26
+
27
+
28
+ class ValidationOpenMessage(_WireModel):
29
+ type: Literal["validation_open"]
30
+ data: ValidationOpenData
31
+
32
+
33
+ class ValidationReadData(_WireModel):
34
+ schema_version: Literal[1]
35
+ capability: SecretStr = Field(min_length=32, max_length=256)
36
+
37
+
38
+ class ValidationReadMessage(_WireModel):
39
+ type: Literal["validation_read"]
40
+ data: ValidationReadData
41
+
42
+
43
+ class ValidationOpenedData(_WireModel):
44
+ schema_version: Literal[1] = 1
45
+ capability: str
46
+
47
+
48
+ class ValidationOpenedResponse(_WireModel):
49
+ type: Literal["validation_open"] = "validation_open"
50
+ data: ValidationOpenedData
51
+
52
+
53
+ class SeedAcceptance(_WireModel):
54
+ requested: bool
55
+ value: Any = None
56
+ accepted: bool
57
+
58
+
59
+ class RubricNode(_WireModel):
60
+ name: str
61
+ class_name: str
62
+ children: list[str]
63
+ aggregation: Literal["weighted_sum", "sequential", "gate", "leaf", "unknown"]
64
+ config: dict[str, Any]
65
+ config_available: bool
66
+ score: Any = None
67
+ evaluated: bool = False
68
+
69
+
70
+ class StepAttribution(_WireModel):
71
+ step_index: int
72
+ rubric: list[RubricNode]
73
+
74
+
75
+ class TrajectoryRecord(_WireModel):
76
+ operation: Literal["reset", "step", "state"]
77
+ request: dict[str, Any]
78
+ response: dict[str, Any]
79
+
80
+
81
+ class SubjectTrajectory(_WireModel):
82
+ schema_version: Literal[1] = 1
83
+ source: Literal["openenv-server"] = "openenv-server"
84
+ records: list[TrajectoryRecord] = Field(default_factory=list)
85
+ complete: bool = True
86
+ reason: str | None = None
87
+
88
+
89
+ class ValidationSnapshot(_WireModel):
90
+ schema_version: Literal[1] = 1
91
+ seed: SeedAcceptance | None = None
92
+ rubric: list[RubricNode] = Field(default_factory=list)
93
+ rubric_error: str | None = None
94
+ attribution: list[StepAttribution] = Field(default_factory=list)
95
+ trajectory: SubjectTrajectory = Field(default_factory=SubjectTrajectory)
96
+
97
+
98
+ class ValidationResponse(_WireModel):
99
+ type: Literal["validation"] = "validation"
100
+ data: ValidationSnapshot
101
+
102
+
103
+ def _rubrics(root: Rubric | None) -> list[tuple[str, Rubric]]:
104
+ """Visit the named tree with finite size, rejecting cycles and aliases."""
105
+ if root is None:
106
+ return []
107
+ result, pending, seen = [], [("root", root)], set()
108
+ while pending:
109
+ name, rubric = pending.pop()
110
+ if id(rubric) in seen or len(result) >= MAX_RUBRIC_NODES:
111
+ raise ValueError("Rubric tree is cyclic, shared, or exceeds 128 nodes")
112
+ seen.add(id(rubric))
113
+ result.append((name, rubric))
114
+ children = list(rubric.named_children())
115
+ if any(not key or "." in key for key, _ in children):
116
+ raise ValueError("Rubric child names must be nonempty path segments")
117
+ pending.extend((f"{name}.{key}", child) for key, child in reversed(children))
118
+ return result
119
+
120
+
121
+ def rubric_counts(root: Rubric | None) -> dict[int, int]:
122
+ return {id(r): r._evaluation_count for _, r in _rubrics(root)}
123
+
124
+
125
+ def rubric_snapshot(
126
+ root: Rubric | None, before: dict[int, int] | None = None
127
+ ) -> list[RubricNode]:
128
+ nodes = []
129
+ for name, rubric in _rubrics(root):
130
+ children = [f"{name}.{key}" for key, _ in rubric.named_children()]
131
+ aggregation = "unknown" if children else "leaf"
132
+ config = None
133
+ # Exact types: a subclass can override scoring, so its semantics are unknown.
134
+ if type(rubric) is WeightedSum:
135
+ aggregation, config = "weighted_sum", {"weights": list(rubric._weights)}
136
+ elif type(rubric) is Sequential:
137
+ aggregation, config = "sequential", {}
138
+ elif type(rubric) is Gate:
139
+ aggregation, config = "gate", {"threshold": rubric.threshold}
140
+ else:
141
+ config = rubric.validation_config()
142
+ evaluated = before is not None and rubric._evaluation_count > before.get(
143
+ id(rubric), 0
144
+ )
145
+ nodes.append(
146
+ RubricNode(
147
+ name=name,
148
+ class_name=f"{type(rubric).__module__}.{type(rubric).__qualname__}",
149
+ children=children,
150
+ aggregation=aggregation,
151
+ config={} if config is None else config,
152
+ config_available=config is not None,
153
+ score=rubric.last_score if evaluated else None,
154
+ evaluated=evaluated,
155
+ )
156
+ )
157
+ json.dumps([node.model_dump() for node in nodes], allow_nan=False)
158
+ return nodes
159
+
160
+
161
+ class SessionTelemetry:
162
+ """Own one socket's capability and a detached record of completed operations."""
163
+
164
+ def __init__(self):
165
+ self.capability = secrets.token_urlsafe(32)
166
+ self.snapshot = ValidationSnapshot()
167
+ self._bytes = 0
168
+ self._steps = 0
169
+
170
+ def authorized(self, capability: str) -> bool:
171
+ return secrets.compare_digest(self.capability.encode(), capability.encode())
172
+
173
+ def append(
174
+ self,
175
+ operation: Literal["reset", "step", "state"],
176
+ request: dict[str, Any],
177
+ response: dict[str, Any],
178
+ *,
179
+ seed: SeedAcceptance | None = None,
180
+ rubric: list[RubricNode] | None = None,
181
+ ) -> None:
182
+ if not self.snapshot.trajectory.complete:
183
+ return
184
+ try:
185
+ # JSON round-trip detaches mutable observations/actions from the record.
186
+ record = TrajectoryRecord.model_validate(
187
+ json.loads(
188
+ json.dumps(
189
+ {
190
+ "operation": operation,
191
+ "request": request,
192
+ "response": response,
193
+ },
194
+ allow_nan=False,
195
+ )
196
+ )
197
+ )
198
+ attribution = (
199
+ StepAttribution(step_index=self._steps, rubric=rubric or [])
200
+ if operation == "step"
201
+ else None
202
+ )
203
+ byte_count = len(record.model_dump_json().encode())
204
+ if attribution is not None:
205
+ byte_count += len(attribution.model_dump_json().encode())
206
+ byte_count += (
207
+ len(seed.model_dump_json().encode()) if seed is not None else 0
208
+ )
209
+ # Reserve room for the current rubric, envelope, and seed metadata.
210
+ current_bytes = len(
211
+ json.dumps(
212
+ [
213
+ node.model_dump()
214
+ for node in (self.snapshot.rubric if rubric is None else rubric)
215
+ ],
216
+ allow_nan=False,
217
+ ).encode()
218
+ )
219
+ if (
220
+ len(self.snapshot.trajectory.records) >= MAX_TRAJECTORY_RECORDS
221
+ or operation == "step"
222
+ and self._steps >= MAX_TRAJECTORY_ACTIONS
223
+ or self._bytes + byte_count + current_bytes + 4096 > MAX_TELEMETRY_BYTES
224
+ ):
225
+ self.incomplete("Session telemetry budget exceeded")
226
+ return
227
+ self._bytes += byte_count
228
+ self.snapshot.trajectory.records.append(record)
229
+ if seed is not None:
230
+ self.snapshot.seed = seed.model_copy(deep=True)
231
+ if rubric is not None:
232
+ self.snapshot.rubric = [node.model_copy(deep=True) for node in rubric]
233
+ if attribution is not None:
234
+ self.snapshot.attribution.append(attribution.model_copy(deep=True))
235
+ self._steps += 1
236
+ except (TypeError, ValueError):
237
+ self.incomplete("Session telemetry contains non-JSON data")
238
+
239
+ def incomplete(self, reason: str) -> None:
240
+ self.snapshot.trajectory.complete = False
241
+ self.snapshot.trajectory.reason = reason
src/core/env_server/types.py CHANGED
@@ -236,6 +236,10 @@ class SchemaResponse(BaseMessage):
236
  state: Dict[str, Any] = Field(
237
  description="JSON schema for environment state objects"
238
  )
 
 
 
 
239
  reset_observation: Optional[Dict[str, Any]] = Field(
240
  default=None, description="JSON schema for observations returned by reset"
241
  )
@@ -243,6 +247,8 @@ class SchemaResponse(BaseMessage):
243
  @model_serializer(mode="wrap")
244
  def _omit_undeclared_reset_schema(self, handler):
245
  data = handler(self)
 
 
246
  if self.reset_observation is None:
247
  data.pop("reset_observation", None)
248
  return data
 
236
  state: Dict[str, Any] = Field(
237
  description="JSON schema for environment state objects"
238
  )
239
+ reset: Optional[Dict[str, Any]] = Field(
240
+ default=None,
241
+ description="JSON schema for reset parameters accepted by this environment",
242
+ )
243
  reset_observation: Optional[Dict[str, Any]] = Field(
244
  default=None, description="JSON schema for observations returned by reset"
245
  )
 
247
  @model_serializer(mode="wrap")
248
  def _omit_undeclared_reset_schema(self, handler):
249
  data = handler(self)
250
+ if self.reset is None:
251
+ data.pop("reset", None)
252
  if self.reset_observation is None:
253
  data.pop("reset_observation", None)
254
  return data
src/core/env_server/web_interface.py CHANGED
@@ -28,7 +28,7 @@ from .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME
28
  from .gradio_ui import build_gradio_app, get_gradio_display_title
29
  from .interfaces import Environment
30
  from .serialization import deserialize_action_with_preprocessing, serialize_observation
31
- from .types import Action, EnvironmentMetadata, Observation, State
32
 
33
 
34
  _CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"}
@@ -169,7 +169,7 @@ def get_quick_start_markdown(
169
  lines += ["", after]
170
  lines += [
171
  "",
172
- "More in the [OpenEnv documentation](https://huggingface.co/docs/openenv).",
173
  ]
174
  return "\n".join(lines)
175
 
@@ -485,6 +485,7 @@ def create_web_interface_app(
485
  *,
486
  mode: Optional[Any] = None,
487
  reset_observation_cls: Optional[Type[Observation]] = None,
 
488
  ) -> FastAPI:
489
  """
490
  Create a FastAPI application with web interface for the given environment.
@@ -519,6 +520,9 @@ def create_web_interface_app(
519
  title instead of the default ``"OpenEnv Agentic Environment: {name}"``.
520
  state_cls: The State subclass this environment reports. Used for the /state
521
  response model and the state entry of /schema. Defaults to State.
 
 
 
522
  mode: Server mode (``ServerMode`` or string). When ``None``, resolved
523
  from the ``OPENENV_MODE`` environment variable, defaulting to
524
  simulation.
@@ -537,6 +541,7 @@ def create_web_interface_app(
537
  concurrency_config,
538
  env_name=env_name,
539
  state_cls=state_cls,
 
540
  reset_observation_cls=reset_observation_cls,
541
  mode=mode,
542
  )
@@ -638,6 +643,8 @@ def create_web_interface_app(
638
  css=OPENENV_GRADIO_CSS,
639
  )
640
 
 
 
641
  return app
642
 
643
 
 
28
  from .gradio_ui import build_gradio_app, get_gradio_display_title
29
  from .interfaces import Environment
30
  from .serialization import deserialize_action_with_preprocessing, serialize_observation
31
+ from .types import Action, EnvironmentMetadata, Observation, ResetRequest, State
32
 
33
 
34
  _CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"}
 
169
  lines += ["", after]
170
  lines += [
171
  "",
172
+ "More in the [OpenEnv documentation](https://openenv.github.io/OpenEnv/).",
173
  ]
174
  return "\n".join(lines)
175
 
 
485
  *,
486
  mode: Optional[Any] = None,
487
  reset_observation_cls: Optional[Type[Observation]] = None,
488
+ reset_cls: Type[ResetRequest] = ResetRequest,
489
  ) -> FastAPI:
490
  """
491
  Create a FastAPI application with web interface for the given environment.
 
520
  title instead of the default ``"OpenEnv Agentic Environment: {name}"``.
521
  state_cls: The State subclass this environment reports. Used for the /state
522
  response model and the state entry of /schema. Defaults to State.
523
+ reset_cls: The ResetRequest subclass describing reset parameters. Published
524
+ as the reset entry of /schema; not used for validation. Defaults to
525
+ ResetRequest.
526
  mode: Server mode (``ServerMode`` or string). When ``None``, resolved
527
  from the ``OPENENV_MODE`` environment variable, defaulting to
528
  simulation.
 
541
  concurrency_config,
542
  env_name=env_name,
543
  state_cls=state_cls,
544
+ reset_cls=reset_cls,
545
  reset_observation_cls=reset_observation_cls,
546
  mode=mode,
547
  )
 
643
  css=OPENENV_GRADIO_CSS,
644
  )
645
 
646
+ # Security middleware is attached inside create_fastapi_app, before the
647
+ # gradio mount at /web; it is app-level middleware, so it covers the mount.
648
  return app
649
 
650
 
src/core/harness/bridge.py CHANGED
@@ -14,7 +14,7 @@ from .adapter import HarnessError
14
 
15
 
16
  async def _source_tools(mcp_server: Any) -> dict[str, Any]:
17
- """Return {name: FastMCP tool}, compatible with FastMCP 2.x and 3.x.
18
 
19
  Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`],
20
  which wraps the same calls in `run_async_safely`; awaiting directly avoids
@@ -52,9 +52,11 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any:
52
  return mcp_server
53
 
54
  from fastmcp import Client
 
55
  from fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClient
56
  from fastmcp.server.transforms import ToolTransform
57
  from fastmcp.tools.tool_transform import ToolTransformConfig
 
58
 
59
  source_tools = await _source_tools(mcp_server)
60
  missing = sorted(set(renames.values()) - set(source_tools))
@@ -71,12 +73,20 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any:
71
  async with Client(mcp_server):
72
  yield {}
73
 
74
- # Forward callbacks in the current request context. Each harness MCP
75
- # connection gets its own source session, closed on disconnect.
76
  client = StatefulProxyClient(mcp_server)
 
 
 
 
 
 
 
 
77
  view = FastMCPProxy(
78
  name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view",
79
- client_factory=client.new_stateful,
80
  lifespan=lifespan,
81
  )
82
  view.add_transform(
 
14
 
15
 
16
  async def _source_tools(mcp_server: Any) -> dict[str, Any]:
17
+ """Return {name: FastMCP tool}.
18
 
19
  Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`],
20
  which wraps the same calls in `run_async_safely`; awaiting directly avoids
 
52
  return mcp_server
53
 
54
  from fastmcp import Client
55
+ from fastmcp.server.dependencies import get_context
56
  from fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClient
57
  from fastmcp.server.transforms import ToolTransform
58
  from fastmcp.tools.tool_transform import ToolTransformConfig
59
+ from mcp_types.version import MODERN_PROTOCOL_VERSIONS
60
 
61
  source_tools = await _source_tools(mcp_server)
62
  missing = sorted(set(renames.values()) - set(source_tools))
 
73
  async with Client(mcp_server):
74
  yield {}
75
 
76
+ # Keep one backend client per front connection, and mirror its protocol era.
77
+ # StatefulProxyClient defaults to legacy, which cannot carry sampling guards.
78
  client = StatefulProxyClient(mcp_server)
79
+
80
+ def client_factory():
81
+ backend = client.new_stateful()
82
+ if not backend.is_connected():
83
+ version = get_context().request_context.protocol_version
84
+ backend.mode = version if version in MODERN_PROTOCOL_VERSIONS else "legacy"
85
+ return backend
86
+
87
  view = FastMCPProxy(
88
  name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view",
89
+ client_factory=client_factory,
90
  lifespan=lifespan,
91
  )
92
  view.add_transform(
src/core/harness/capture/forwarding.py CHANGED
@@ -33,6 +33,7 @@ why `SessionRegistry.require_registered` defaults to True.
33
 
34
  from __future__ import annotations
35
 
 
36
  import logging
37
  import re
38
  import secrets
@@ -42,6 +43,12 @@ import subprocess
42
  import threading
43
  import time
44
  from abc import ABC, abstractmethod
 
 
 
 
 
 
45
 
46
  logger = logging.getLogger(__name__)
47
 
@@ -147,6 +154,25 @@ class GradioForwarder(PortForwarder):
147
  f"gradio is required for GradioForwarder: {exc}"
148
  ) from exc
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  def start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str:
151
  from gradio.networking import setup_tunnel
152
  from gradio.tunneling import CURRENT_TUNNELS
@@ -154,6 +180,7 @@ class GradioForwarder(PortForwarder):
154
  self.stop()
155
  share_token = secrets.token_hex(16)
156
  try:
 
157
  url = setup_tunnel(
158
  local_host=local_host,
159
  local_port=local_port,
 
33
 
34
  from __future__ import annotations
35
 
36
+ import importlib
37
  import logging
38
  import re
39
  import secrets
 
43
  import threading
44
  import time
45
  from abc import ABC, abstractmethod
46
+ from pathlib import Path
47
+
48
+ try:
49
+ import fcntl
50
+ except ImportError: # Windows: no advisory locks, keep gradio's unlocked download.
51
+ fcntl = None
52
 
53
  logger = logging.getLogger(__name__)
54
 
 
154
  f"gradio is required for GradioForwarder: {exc}"
155
  ) from exc
156
 
157
+ @staticmethod
158
+ def _ensure_frpc_binary() -> None:
159
+ """
160
+ Download gradio's frpc binary once, under a cross-process lock.
161
+
162
+ Gradio checks `Path(BINARY_PATH).exists()` and then writes the binary in place. A second
163
+ process that starts while the first is still writing sees the file, skips the download and
164
+ executes a half-written binary, which fails with `Text file busy` (ETXTBSY) or a corrupt
165
+ executable. Holding an exclusive lock next to the binary makes every other process wait
166
+ until the first download has finished, after which gradio's own check skips the download.
167
+ """
168
+ tunneling = importlib.import_module("gradio.tunneling")
169
+ binary = Path(tunneling.BINARY_PATH)
170
+ binary.parent.mkdir(parents=True, exist_ok=True)
171
+ with open(binary.with_name(binary.name + ".lock"), "a") as lock_file:
172
+ if fcntl is not None:
173
+ fcntl.flock(lock_file, fcntl.LOCK_EX)
174
+ tunneling.Tunnel.download_binary()
175
+
176
  def start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str:
177
  from gradio.networking import setup_tunnel
178
  from gradio.tunneling import CURRENT_TUNNELS
 
180
  self.stop()
181
  share_token = secrets.token_hex(16)
182
  try:
183
+ self._ensure_frpc_binary()
184
  url = setup_tunnel(
185
  local_host=local_host,
186
  local_port=local_port,
src/core/harness/capture/graph.py CHANGED
@@ -248,9 +248,25 @@ class RolloutGraph:
248
  self._nodes: dict[str, TurnNode] = {}
249
  self._order: list[str] = []
250
  self._children: dict[str, list[str]] = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
  # --- construction --------------------------------------------------
253
  def add_turn(self, node: TurnNode) -> TurnNode:
 
 
 
254
  node.index = len(self._order)
255
  node.parent_id = self._find_parent(node)
256
  self._nodes[node.node_id] = node
 
248
  self._nodes: dict[str, TurnNode] = {}
249
  self._order: list[str] = []
250
  self._children: dict[str, list[str]] = {}
251
+ # Every request re-sends the whole history, so each turn decodes a fresh copy of every
252
+ # earlier image and long text. Keep one copy per graph. Only immutable strings are shared;
253
+ # message dicts and lists stay per turn.
254
+ self._shared_text: dict[str, str] = {}
255
+
256
+ def _share_text(self, value: Any) -> Any:
257
+ if isinstance(value, str) and len(value) >= 1024:
258
+ return self._shared_text.setdefault(value, value)
259
+ if isinstance(value, list):
260
+ return [self._share_text(item) for item in value]
261
+ if isinstance(value, dict):
262
+ return {key: self._share_text(item) for key, item in value.items()}
263
+ return value
264
 
265
  # --- construction --------------------------------------------------
266
  def add_turn(self, node: TurnNode) -> TurnNode:
267
+ node.request_messages = self._share_text(node.request_messages)
268
+ node.request_tools = self._share_text(node.request_tools)
269
+ node.response_message = self._share_text(node.response_message)
270
  node.index = len(self._order)
271
  node.parent_id = self._find_parent(node)
272
  self._nodes[node.node_id] = node
src/core/harness/capture/server.py CHANGED
@@ -266,6 +266,41 @@ def clamp_output_tokens(chat_request: dict[str, Any], cap: int | None) -> int |
266
  return replaced
267
 
268
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  def normalise_for_capture(chat_request: dict[str, Any]) -> None:
270
  """Force the upstream call into the one shape that yields complete, capturable responses.
271
 
@@ -1199,6 +1234,23 @@ def create_app(
1199
  for key in SAMPLING_KEYS:
1200
  chat_request.pop(key, None)
1201
  chat_request.update(effective_sampling)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1202
  normalise_response(response)
1203
  _ingest(
1204
  session,
 
266
  return replaced
267
 
268
 
269
+ def context_window_ran_out(
270
+ chat_request: dict[str, Any], response: dict[str, Any]
271
+ ) -> bool:
272
+ """Whether the engine cut the completion short because the context window was full.
273
+
274
+ Older vLLM rejects a request whose prompt plus `max_tokens` exceeds the context window with a 400
275
+ ("maximum context length"), which the proxy turns into a budget stop. Newer vLLM (seen with 0.34)
276
+ serves it and stops generating when the window is full instead: the completion ends with
277
+ `finish_reason="length"` before reaching `max_tokens`. Forwarded as is, that truncated turn reaches
278
+ the harness, and pi answers it by compacting its context, in a summarisation call capture cannot
279
+ tie to the rest of the rollout: every such rollout fails validation with `turn_mismatch`. It is the
280
+ same event as the 400, so it ends the rollout the same way.
281
+ """
282
+ # The limit the engine applies, in its order: vLLM (like OpenAI) takes `max_completion_tokens` and
283
+ # falls back to `max_tokens`. A harness that sends both with different values would otherwise turn
284
+ # an output-cap stop into a context stop, or hide a real one.
285
+ requested = next(
286
+ (
287
+ chat_request[key]
288
+ for key in ("max_completion_tokens", "max_tokens")
289
+ if isinstance(chat_request.get(key), int)
290
+ ),
291
+ None,
292
+ )
293
+ choices = response.get("choices") or []
294
+ completion_tokens = (response.get("usage") or {}).get("completion_tokens")
295
+ return (
296
+ requested is not None
297
+ and isinstance(completion_tokens, int)
298
+ and bool(choices)
299
+ and choices[0].get("finish_reason") == "length"
300
+ and completion_tokens < requested
301
+ )
302
+
303
+
304
  def normalise_for_capture(chat_request: dict[str, Any]) -> None:
305
  """Force the upstream call into the one shape that yields complete, capturable responses.
306
 
 
1234
  for key in SAMPLING_KEYS:
1235
  chat_request.pop(key, None)
1236
  chat_request.update(effective_sampling)
1237
+ if context_window_ran_out(chat_request, response):
1238
+ # Like the 400 above: a stop the harness ends on, and the truncated turn is never ingested
1239
+ session.findings.append(
1240
+ "[WARN] context_budget_exhausted: the engine stopped at the context window, "
1241
+ "before max_tokens"
1242
+ )
1243
+ session.budget_stop_count += 1
1244
+ stop = _budget_stop_response(_model_of(session) or app.state.model)
1245
+ if client_wants_stream:
1246
+ return StreamingResponse(
1247
+ sse.replay(api_type, transformer, stop, original_request),
1248
+ media_type="text/event-stream",
1249
+ headers=sse.SSE_HEADERS,
1250
+ )
1251
+ payload = transformer.transform_response(stop, original_request)
1252
+ normalise_client_payload(payload, api_type)
1253
+ return JSONResponse(payload)
1254
  normalise_response(response)
1255
  _ingest(
1256
  session,
src/core/harness/capture/validate_llm.py CHANGED
@@ -44,11 +44,13 @@ from __future__ import annotations
44
 
45
  import json
46
  import os
 
47
  import urllib.error
48
  import urllib.request
49
  from dataclasses import dataclass, field
 
50
 
51
- from .compat import behaviour_warnings, diagnose, MAX_FIXES
52
  from .upstream import (
53
  auth_headers,
54
  normalise_engine_base,
@@ -70,6 +72,25 @@ ENGINE_HINT = (
70
  )
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  @dataclass
74
  class LLMReport:
75
  """Outcome of the probe. `ok` means trainable; `reachable` means usable at all."""
@@ -574,7 +595,10 @@ def validate_llm(
574
  # or gate it behind different scopes than inference, and refusing there would reject an endpoint
575
  # that serves completions perfectly well. The completion probe below is the real test; a missing
576
  # list only costs us the model-name check.
577
- listed_model = model.rsplit(":", 1)[0] if provider == "hf" else model
 
 
 
578
  if served and model not in served and listed_model not in served:
579
  # Worth failing on rather than warning: a mismatched name is silently accepted by some
580
  # servers and then every request 404s at rollout time instead of at startup.
@@ -603,6 +627,7 @@ def validate_llm(
603
  applied: list = []
604
  payload: dict | None = None
605
  failure = ""
 
606
 
607
  # Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the
608
  # capture params are the ones most likely to go, and losing them is what decides the level.
@@ -630,13 +655,40 @@ def validate_llm(
630
  fix = diagnose(json.loads(detail))
631
  except json.JSONDecodeError:
632
  fix = diagnose(detail)
633
- if fix is None or not fix.apply(body):
634
- failure = f"probe failed: HTTP {exc.code}: {detail[:300]}"
 
 
 
 
635
  break
636
- fixes.append(str(fix))
637
- applied.append(fix)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  except Exception as exc: # noqa: BLE001
639
  failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}"
 
 
 
 
 
640
  break
641
 
642
  if payload is None:
 
44
 
45
  import json
46
  import os
47
+ import time
48
  import urllib.error
49
  import urllib.request
50
  from dataclasses import dataclass, field
51
+ from urllib.parse import urlsplit
52
 
53
+ from .compat import behaviour_warnings, diagnose, MAX_FIXES, ParamFix
54
  from .upstream import (
55
  auth_headers,
56
  normalise_engine_base,
 
72
  )
73
 
74
 
75
+ # How many times the probe repeats the SAME request after an error that names nothing it can fix.
76
+ # Hosted routers occasionally answer a valid request with a 400 or 5xx that a resend clears: observed
77
+ # as one task in ~150 aborting before it ran, against an endpoint that served the other 149.
78
+ PROBE_RETRIES = 2
79
+ PROBE_RETRY_DELAY = 1.0
80
+ # Errors no resend or rewrite can fix: bad credentials, no access, no such route or model. Retrying
81
+ # these only delays a message the user needs now.
82
+ _FATAL_HTTP = frozenset({401, 403, 404})
83
+ # Statuses with which a provider rejects a request it doesn't accept, e.g. unsupported capture params.
84
+ _PARAM_REJECTION_HTTP = frozenset({400, 422})
85
+ # What the eval fallback drops. `logprobs` also takes `top_logprobs` with it (see `ParamFix.apply`).
86
+ _CAPTURE_PARAMS = ("return_token_ids", "logprobs")
87
+
88
+
89
+ def _is_timeout(exc: BaseException) -> bool:
90
+ reason = getattr(exc, "reason", None)
91
+ return isinstance(exc, TimeoutError) or isinstance(reason, TimeoutError)
92
+
93
+
94
  @dataclass
95
  class LLMReport:
96
  """Outcome of the probe. `ok` means trainable; `reachable` means usable at all."""
 
595
  # or gate it behind different scopes than inference, and refusing there would reject an endpoint
596
  # that serves completions perfectly well. The completion probe below is the real test; a missing
597
  # list only costs us the model-name check.
598
+ # The HF router lists bare ids but routes `<id>:<provider>` (also `:fastest`, `:cheapest`). The
599
+ # CLI reaches it with the default provider, so recognise the router by its host as well.
600
+ hf_router = urlsplit(base).hostname == "router.huggingface.co"
601
+ listed_model = model.rsplit(":", 1)[0] if provider == "hf" or hf_router else model
602
  if served and model not in served and listed_model not in served:
603
  # Worth failing on rather than warning: a mismatched name is silently accepted by some
604
  # servers and then every request 404s at rollout time instead of at startup.
 
627
  applied: list = []
628
  payload: dict | None = None
629
  failure = ""
630
+ retries_left = PROBE_RETRIES
631
 
632
  # Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the
633
  # capture params are the ones most likely to go, and losing them is what decides the level.
 
655
  fix = diagnose(json.loads(detail))
656
  except json.JSONDecodeError:
657
  fix = diagnose(detail)
658
+ if fix is not None and fix.apply(body):
659
+ fixes.append(str(fix))
660
+ applied.append(fix)
661
+ continue
662
+ failure = f"probe failed: HTTP {exc.code}: {detail[:300]}"
663
+ if exc.code in _FATAL_HTTP:
664
  break
665
+ # An error that names no parameter is first treated as transient: the same request again.
666
+ if retries_left:
667
+ retries_left -= 1
668
+ time.sleep(PROBE_RETRY_DELAY)
669
+ continue
670
+ # Still failing. Some providers reject the capture params with a bare 400 that names
671
+ # nothing, so ask once more without them. If that answers, the endpoint is an eval
672
+ # backend (the level is graded from what comes back), which is what `ENGINE_HINT`
673
+ # promises. A `purpose="train"` rollout still refuses it, since the level is not `tokens`.
674
+ # Only a request error can be about the params: a 5xx or a 429 that outlasts the retries
675
+ # is reported, rather than grading a busy token-capable engine as `text`.
676
+ if exc.code not in _PARAM_REJECTION_HTTP:
677
+ break
678
+ dropped = [ParamFix(param=p) for p in _CAPTURE_PARAMS]
679
+ dropped = [f for f in dropped if f.apply(body)]
680
+ if not dropped:
681
+ break
682
+ for f in dropped:
683
+ fixes.append(f"{f} (eval fallback after HTTP {exc.code})")
684
+ applied.append(f)
685
  except Exception as exc: # noqa: BLE001
686
  failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}"
687
+ # A timeout is worth repeating. Anything else here (connection refused, DNS) is not.
688
+ if _is_timeout(exc) and retries_left:
689
+ retries_left -= 1
690
+ time.sleep(PROBE_RETRY_DELAY)
691
+ continue
692
  break
693
 
694
  if payload is None:
src/core/harness/collect.py CHANGED
@@ -23,10 +23,11 @@ import warnings
23
  from dataclasses import asdict, dataclass, field
24
  from datetime import datetime, timezone
25
  from pathlib import Path
26
- from typing import Any, BinaryIO, Callable, Iterable, Iterator
27
 
28
  from ..env_server.mcp_types import Tool
29
  from ..llm_client import LLMClient
 
30
  from .rollout import (
31
  _resolve_env_reward,
32
  HarnessAdapter,
@@ -237,9 +238,10 @@ class CollectResult:
237
  class CollectRunner:
238
  """Drive repeated rollouts into an append-only JSONL dataset.
239
 
240
- The runner is stateless across ``run()`` calls — resume state lives on
241
- disk via the ``RolloutSerializer``. A single runner instance can be
242
- reused across runs targeting different output dirs.
 
243
  """
244
 
245
  def __init__(
@@ -254,17 +256,10 @@ class CollectRunner:
254
  self._session_factory = session_factory
255
  self._harness_adapter = harness_adapter
256
  self._serializer = serializer
257
- self._tasks: Iterator[Any] | None = iter(tasks) if tasks is not None else None
 
258
  self._limits = limits
259
 
260
- def _next_task(self) -> Any:
261
- if self._tasks is None:
262
- return None
263
- try:
264
- return next(self._tasks)
265
- except StopIteration:
266
- return None
267
-
268
  def run(
269
  self,
270
  *,
@@ -274,6 +269,16 @@ class CollectRunner:
274
  resume: bool = True,
275
  should_keep: Callable[[EpisodeRecord], bool] | None = None,
276
  ) -> CollectResult:
 
 
 
 
 
 
 
 
 
 
277
  planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)]
278
 
279
  if resume:
@@ -312,7 +317,8 @@ class CollectRunner:
312
  with progress:
313
  for episode_id in planned_ids:
314
  # Preserve task-to-episode alignment even when resume skips ids.
315
- task = self._next_task()
 
316
  if episode_id in already:
317
  num_skipped += 1
318
  progress.advance(task_id)
@@ -513,7 +519,7 @@ def build_dataset_readme(output_dir: Path) -> str:
513
  "",
514
  "# OpenEnv rollouts",
515
  "",
516
- "Collected with [OpenEnv](https://github.com/huggingface/OpenEnv) "
517
  "(`openenv collect`).",
518
  "",
519
  f"- **Episodes:** {_count_episodes(results_path)}",
@@ -594,6 +600,19 @@ def push_to_hf_hub(
594
  readme_path = output_dir / README_FILENAME
595
  readme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8")
596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  num_episodes = _count_episodes(results_path)
598
  message = commit_message or f"Add {num_episodes} collected episode(s)"
599
 
 
23
  from dataclasses import asdict, dataclass, field
24
  from datetime import datetime, timezone
25
  from pathlib import Path
26
+ from typing import Any, BinaryIO, Callable, Iterable
27
 
28
  from ..env_server.mcp_types import Tool
29
  from ..llm_client import LLMClient
30
+ from ..utils import redact_secrets
31
  from .rollout import (
32
  _resolve_env_reward,
33
  HarnessAdapter,
 
238
  class CollectRunner:
239
  """Drive repeated rollouts into an append-only JSONL dataset.
240
 
241
+ Resume state lives on disk via the ``RolloutSerializer``. Repeatable task
242
+ iterables, such as lists and tuples, restart at the first task on each
243
+ ``run()`` so tasks stay aligned with episode ids. One-shot iterators work
244
+ for one run; reusing them raises ``ValueError`` before accessing results.
245
  """
246
 
247
  def __init__(
 
256
  self._session_factory = session_factory
257
  self._harness_adapter = harness_adapter
258
  self._serializer = serializer
259
+ self._tasks = tasks
260
+ self._tasks_used = False
261
  self._limits = limits
262
 
 
 
 
 
 
 
 
 
263
  def run(
264
  self,
265
  *,
 
269
  resume: bool = True,
270
  should_keep: Callable[[EpisodeRecord], bool] | None = None,
271
  ) -> CollectResult:
272
+ task_iterator = iter(self._tasks) if self._tasks is not None else None
273
+ if (
274
+ task_iterator is not None
275
+ and task_iterator is self._tasks
276
+ and self._tasks_used
277
+ ):
278
+ raise ValueError(
279
+ "Cannot reuse a one-shot task iterator; pass a repeatable iterable "
280
+ "or create a new CollectRunner with a fresh iterator."
281
+ )
282
  planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)]
283
 
284
  if resume:
 
317
  with progress:
318
  for episode_id in planned_ids:
319
  # Preserve task-to-episode alignment even when resume skips ids.
320
+ self._tasks_used = True
321
+ task = next(task_iterator, None) if task_iterator is not None else None
322
  if episode_id in already:
323
  num_skipped += 1
324
  progress.advance(task_id)
 
519
  "",
520
  "# OpenEnv rollouts",
521
  "",
522
+ "Collected with [OpenEnv](https://github.com/openenv/OpenEnv) "
523
  "(`openenv collect`).",
524
  "",
525
  f"- **Episodes:** {_count_episodes(results_path)}",
 
600
  readme_path = output_dir / README_FILENAME
601
  readme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8")
602
 
603
+ # Episodes hold what the agent saw and printed, which can include credentials.
604
+ redacted = 0
605
+ for path in output_dir.iterdir():
606
+ if path.suffix in {".jsonl", ".json", ".md"}:
607
+ text, count = redact_secrets(path.read_text(encoding="utf-8"))
608
+ if count:
609
+ path.write_text(text, encoding="utf-8")
610
+ redacted += count
611
+ if redacted:
612
+ warnings.warn(
613
+ f"Redacted {redacted} secret(s) from {output_dir} before the upload"
614
+ )
615
+
616
  num_episodes = _count_episodes(results_path)
617
  message = commit_message or f"Add {num_episodes} collected episode(s)"
618
 
src/core/mcp_client.py CHANGED
@@ -255,6 +255,12 @@ class MCPClientBase(EnvClient[Any, Observation, State]):
255
 
256
  return await super()._connect_async()
257
 
 
 
 
 
 
 
258
  async def _ensure_production_session(self) -> str:
259
  """Create and cache a persistent HTTP MCP session id if needed."""
260
  async with self._production_session_lock:
 
255
 
256
  return await super()._connect_async()
257
 
258
+ def _raise_if_session_lost(self) -> None:
259
+ # In production mode a reconnect attaches to the same HTTP MCP session,
260
+ # which outlives the WebSocket, so the episode carries over.
261
+ if not getattr(self, "use_production_mode", False):
262
+ super()._raise_if_session_lost()
263
+
264
  async def _ensure_production_session(self) -> str:
265
  """Create and cache a persistent HTTP MCP session id if needed."""
266
  async with self._production_session_lock:
src/core/openenv/auto/auto_action.py CHANGED
@@ -89,9 +89,9 @@ class AutoAction:
89
  Args:
90
  name: Environment name or HuggingFace Hub repo ID
91
  Examples:
92
- - "coding" / "coding-env" / "coding_env"
93
- - "openenv/coding_env" (Hub repo ID)
94
- - "https://huggingface.co/openenv/coding_env" (Hub URL)
95
  skip_install: If True, skip package installation and return
96
  GenericAction class instead. Use this when working with
97
  GenericEnvClient to avoid installing remote packages.
 
89
  Args:
90
  name: Environment name or HuggingFace Hub repo ID
91
  Examples:
92
+ - `"coding"` / `"coding-env"` / `"coding_env"`
93
+ - `"openenv/coding_env"` (Hub repo ID)
94
+ - `"https://huggingface.co/openenv/coding_env"` (Hub URL)
95
  skip_install: If True, skip package installation and return
96
  GenericAction class instead. Use this when working with
97
  GenericEnvClient to avoid installing remote packages.
src/core/openenv/auto/auto_env.py CHANGED
@@ -518,9 +518,9 @@ class AutoEnv:
518
  Args:
519
  name: Environment name or HuggingFace Hub repo ID
520
  Examples:
521
- - "coding" / "coding-env" / "coding_env"
522
- - "openenv/coding_env" (Hub repo ID)
523
- - "https://huggingface.co/openenv/coding_env" (Hub URL)
524
  base_url: Optional base URL for HTTP connection
525
  docker_image: Optional Docker image name (overrides default)
526
  container_provider: Optional container provider
 
518
  Args:
519
  name: Environment name or HuggingFace Hub repo ID
520
  Examples:
521
+ - `"coding"` / `"coding-env"` / `"coding_env"`
522
+ - `"openenv/coding_env"` (Hub repo ID)
523
+ - `"https://huggingface.co/openenv/coding_env"` (Hub URL)
524
  base_url: Optional base URL for HTTP connection
525
  docker_image: Optional Docker image name (overrides default)
526
  container_provider: Optional container provider
src/core/openenv/cli/__main__.py CHANGED
@@ -51,9 +51,10 @@ app.command(
51
  name="push",
52
  help="Push an OpenEnv environment to Hugging Face Spaces or custom registry",
53
  )(push.push)
54
- app.command(name="serve", help="Serve environments locally (TODO: Phase 4)")(
55
- serve.serve
56
- )
 
57
  app.command(
58
  name="fork",
59
  help="Fork (duplicate) a Hugging Face Space to your account",
 
51
  name="push",
52
  help="Push an OpenEnv environment to Hugging Face Spaces or custom registry",
53
  )(push.push)
54
+ app.command(
55
+ name="serve",
56
+ help="Run an environment on the host for local development (no container isolation)",
57
+ )(serve.serve)
58
  app.command(
59
  name="fork",
60
  help="Fork (duplicate) a Hugging Face Space to your account",
src/core/openenv/cli/commands/build.py CHANGED
@@ -14,6 +14,11 @@ from typing import Annotated
14
 
15
  import typer
16
 
 
 
 
 
 
17
  from .._cli_utils import console
18
 
19
  app = typer.Typer(help="Build Docker images for OpenEnv environments")
@@ -96,26 +101,13 @@ def _prepare_standalone_build(env_path: Path, temp_dir: Path) -> Path:
96
  pyproject_path = build_dir / "pyproject.toml"
97
  if pyproject_path.exists():
98
  with open(pyproject_path, "rb") as f:
99
- try:
100
- import tomli
101
-
102
- pyproject = tomli.load(f)
103
- deps = pyproject.get("project", {}).get("dependencies", [])
104
-
105
- # Check if openenv dependency is declared
106
- has_openenv = any(dep.startswith("openenv") for dep in deps)
107
-
108
- if not has_openenv:
109
- console.print(
110
- "[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency",
111
- )
112
- console.print(
113
- "[yellow]You may need to add:[/yellow] openenv>=0.2.0",
114
- )
115
- except ImportError:
116
- console.print(
117
- "[yellow]Warning:[/yellow] tomli not available, skipping dependency check",
118
- )
119
 
120
  return build_dir
121
 
@@ -156,45 +148,27 @@ def _prepare_inrepo_build(env_path: Path, repo_root: Path, temp_dir: Path) -> Pa
156
  pyproject_path = build_dir / "pyproject.toml"
157
  if pyproject_path.exists():
158
  with open(pyproject_path, "rb") as f:
159
- try:
160
- import tomli
161
-
162
- pyproject = tomli.load(f)
163
- deps = pyproject.get("project", {}).get("dependencies", [])
164
-
165
- # Replace OpenEnv package references with local source.
166
- new_deps = []
167
- for dep in deps:
168
- if _is_openenv_runtime_dependency(dep):
169
- # Skip - we'll use local core
170
- continue
171
- new_deps.append(dep)
172
-
173
- # Write back with local OpenEnv reference
174
- pyproject["project"]["dependencies"] = new_deps + [
175
- "openenv @ file:///app/env/openenv"
176
- ]
177
-
178
- # Write updated pyproject.toml
179
- with open(pyproject_path, "wb") as out_f:
180
- import tomli_w
181
-
182
- tomli_w.dump(pyproject, out_f)
183
-
184
- console.print(
185
- "[cyan]Updated pyproject.toml to use local core[/cyan]"
186
- )
187
-
188
- # Remove old lockfile since dependencies changed
189
- lockfile = build_dir / "uv.lock"
190
- if lockfile.exists():
191
- lockfile.unlink()
192
- console.print("[cyan]Removed outdated uv.lock[/cyan]")
193
-
194
- except ImportError:
195
- console.print(
196
- "[yellow]Warning:[/yellow] tomli/tomli_w not available, using pyproject.toml as-is",
197
- )
198
  else:
199
  console.print(
200
  "[yellow]Warning:[/yellow] OpenEnv package not found, building without it"
 
14
 
15
  import typer
16
 
17
+ try:
18
+ import tomllib
19
+ except ModuleNotFoundError:
20
+ import tomli as tomllib
21
+
22
  from .._cli_utils import console
23
 
24
  app = typer.Typer(help="Build Docker images for OpenEnv environments")
 
101
  pyproject_path = build_dir / "pyproject.toml"
102
  if pyproject_path.exists():
103
  with open(pyproject_path, "rb") as f:
104
+ pyproject = tomllib.load(f)
105
+ deps = pyproject.get("project", {}).get("dependencies", [])
106
+ if not any(dep.startswith("openenv") for dep in deps):
107
+ console.print(
108
+ "[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency",
109
+ )
110
+ console.print("[yellow]You may need to add:[/yellow] openenv>=0.2.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  return build_dir
113
 
 
148
  pyproject_path = build_dir / "pyproject.toml"
149
  if pyproject_path.exists():
150
  with open(pyproject_path, "rb") as f:
151
+ pyproject = tomllib.load(f)
152
+ deps = pyproject.get("project", {}).get("dependencies", [])
153
+ pyproject["project"]["dependencies"] = [
154
+ dep for dep in deps if not _is_openenv_runtime_dependency(dep)
155
+ ] + ["openenv @ file:///app/env/openenv"]
156
+
157
+ try:
158
+ import tomli_w
159
+ except ImportError:
160
+ console.print(
161
+ "[yellow]Warning:[/yellow] tomli_w not available, using pyproject.toml as-is",
162
+ )
163
+ else:
164
+ with open(pyproject_path, "wb") as out_f:
165
+ tomli_w.dump(pyproject, out_f)
166
+ console.print("[cyan]Updated pyproject.toml to use local core[/cyan]")
167
+ lockfile = build_dir / "uv.lock"
168
+ if lockfile.exists():
169
+ lockfile.unlink()
170
+ console.print("[cyan]Removed outdated uv.lock[/cyan]")
171
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  else:
173
  console.print(
174
  "[yellow]Warning:[/yellow] OpenEnv package not found, building without it"
src/core/openenv/cli/commands/harbor.py CHANGED
@@ -1,9 +1,10 @@
1
  """`openenv harbor` — run Harbor tasks with token-level capture.
2
 
3
- Four commands, in the order you would use them:
4
 
5
  openenv harbor info what can this machine run right now?
6
  openenv harbor rollout --task-index 0 one rollout, end to end, no server
 
7
  openenv harbor serve the env server, for trainers and clients
8
  openenv harbor push the same server, deployed to a Space
9
 
@@ -187,6 +188,52 @@ def _hub_not_found(exc: Exception) -> bool:
187
  return getattr(response, "status_code", None) == 404
188
 
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  @app.command("info")
191
  def info(
192
  llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP_OPTIONAL)] = "",
@@ -207,6 +254,14 @@ def info(
207
  env_file: Annotated[
208
  str, typer.Option("--env-file", help="dotenv file with provider credentials.")
209
  ] = "",
 
 
 
 
 
 
 
 
210
  verbose: Annotated[
211
  bool,
212
  typer.Option("--verbose", help="List every harness, not only validated ones."),
@@ -228,11 +283,23 @@ def info(
228
  api_key=api_key or None,
229
  auth_header=auth_header,
230
  )
231
- print(
232
- json.dumps(caps.to_dict(), indent=2)
233
- if json_output
234
- else caps.render(verbose=verbose)
235
  )
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
 
238
  @app.command("rollout")
@@ -272,7 +339,11 @@ def rollout(
272
  ] = "",
273
  reward_key: Annotated[
274
  str,
275
- typer.Option("--reward-key", help="Which reward key is the training signal."),
 
 
 
 
276
  ] = "",
277
  keep_sandbox: Annotated[
278
  bool,
@@ -327,6 +398,111 @@ def rollout(
327
  raise typer.Exit(0 if all(r.ok for r in results) else 1)
328
 
329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  @app.command("serve")
331
  def serve(
332
  llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)] = "",
@@ -395,6 +571,16 @@ def serve(
395
  reward_key: Annotated[
396
  str, typer.Option("--reward-key", help=_REWARD_KEY_HELP)
397
  ] = "",
 
 
 
 
 
 
 
 
 
 
398
  ) -> None:
399
  """Serve Harbor tasks over the OpenEnv Task API and MCP.
400
 
@@ -418,6 +604,8 @@ def serve(
418
  )
419
  # The UI's laptop defaults (this machine's token, private URLs) are for a loopback-only server.
420
  os.environ["OPENENV_HARBOR_UI_HOST"] = host
 
 
421
  serve_harbor(
422
  llm_url=llm_url,
423
  model=model or None,
 
1
  """`openenv harbor` — run Harbor tasks with token-level capture.
2
 
3
+ Five commands, in the order you would use them:
4
 
5
  openenv harbor info what can this machine run right now?
6
  openenv harbor rollout --task-index 0 one rollout, end to end, no server
7
+ openenv harbor export-sft results/ rollouts as SFT rows (messages + tools)
8
  openenv harbor serve the env server, for trainers and clients
9
  openenv harbor push the same server, deployed to a Space
10
 
 
188
  return getattr(response, "status_code", None) == 404
189
 
190
 
191
+ def _check_harness(harness: str, model: str) -> dict[str, Any]:
192
+ """Construct the rollout's agent with dummy capture credentials, without setup or run."""
193
+ import io
194
+
195
+ result: dict[str, Any] = {"name": harness, "ok": False}
196
+ try:
197
+ # Imports, constructors and the process-env warning may print. Keep --json readable.
198
+ with (
199
+ contextlib.redirect_stdout(io.StringIO()),
200
+ tempfile.TemporaryDirectory() as tmp,
201
+ ):
202
+ from harbor.agents.factory import AgentFactory
203
+ from openenv.harbor import seams
204
+ from openenv.harbor.rollout import build_trial_config, process_env
205
+
206
+ seam = seams.get(harness)
207
+ url, session = "http://127.0.0.1:9", "openenv-harness-preflight"
208
+ *_, proc_env = seam.resolve(base_url=url, session=session, model=model)
209
+ config = build_trial_config(
210
+ task_dir=tmp,
211
+ harness=harness,
212
+ sandbox="docker",
213
+ intercept_url=url,
214
+ session_id=session,
215
+ model=model,
216
+ trial_name="preflight",
217
+ trials_dir=tmp,
218
+ )
219
+ with process_env(harness, proc_env):
220
+ AgentFactory.create_agent_from_config(config.agent, logs_dir=Path(tmp))
221
+ result.update(
222
+ ok=True,
223
+ import_path=seam.import_path,
224
+ dialect=seam.dialect,
225
+ host_side=seam.host_side,
226
+ status=seam.status,
227
+ model=config.agent.model_name,
228
+ kwargs=config.agent.kwargs,
229
+ agent_env=config.agent.env,
230
+ process_env=proc_env,
231
+ )
232
+ except (Exception, SystemExit) as exc: # noqa: BLE001 - a failed check is report data
233
+ result["detail"] = f"{type(exc).__name__}: {exc}"
234
+ return result
235
+
236
+
237
  @app.command("info")
238
  def info(
239
  llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP_OPTIONAL)] = "",
 
254
  env_file: Annotated[
255
  str, typer.Option("--env-file", help="dotenv file with provider credentials.")
256
  ] = "",
257
+ harness: Annotated[
258
+ str,
259
+ typer.Option(
260
+ "--harness",
261
+ help="Check a seam name or trusted `module:Class` by constructing it with dummy "
262
+ "capture credentials. Runs no agent or sandbox.",
263
+ ),
264
+ ] = "",
265
  verbose: Annotated[
266
  bool,
267
  typer.Option("--verbose", help="List every harness, not only validated ones."),
 
283
  api_key=api_key or None,
284
  auth_header=auth_header,
285
  )
286
+ checked = (
287
+ _check_harness(harness, model or caps.llm.get("model") or "preflight-model")
288
+ if harness
289
+ else None
290
  )
291
+ if json_output:
292
+ data = caps.to_dict()
293
+ if checked is not None:
294
+ data["harness"] = checked
295
+ print(json.dumps(data, indent=2))
296
+ else:
297
+ print(caps.render(verbose=verbose))
298
+ if checked is not None:
299
+ print("\nharness preflight (construction only; capture is untested)")
300
+ print(json.dumps(checked, indent=2))
301
+ if checked is not None and not checked["ok"]:
302
+ raise typer.Exit(1)
303
 
304
 
305
  @app.command("rollout")
 
339
  ] = "",
340
  reward_key: Annotated[
341
  str,
342
+ typer.Option(
343
+ "--reward-key",
344
+ help="Which reward key is the headline one, or a comma-separated preference "
345
+ "order (e.g. `correctness,reward`) for a dataset whose tasks write different keys.",
346
+ ),
347
  ] = "",
348
  keep_sandbox: Annotated[
349
  bool,
 
398
  raise typer.Exit(0 if all(r.ok for r in results) else 1)
399
 
400
 
401
+ def _read_results(paths: list[str]) -> list[dict[str, Any]]:
402
+ """Rollouts from `rollout --out` files, or from every `*.json` in a directory."""
403
+ files: list[Path] = []
404
+ for spec in paths:
405
+ path = Path(spec)
406
+ if not path.exists():
407
+ raise typer.BadParameter(f"{spec} does not exist")
408
+ files.extend(sorted(path.glob("*.json")) if path.is_dir() else [path])
409
+ results: list[dict[str, Any]] = []
410
+ for file in files:
411
+ data = json.loads(file.read_text())
412
+ items = data if isinstance(data, list) else [data]
413
+ # a directory can hold other JSON (a run summary): keep what looks like a rollout
414
+ results.extend(i for i in items if isinstance(i, dict) and "turns" in i)
415
+ return results
416
+
417
+
418
+ @app.command("export-sft")
419
+ def export_sft_command(
420
+ results: Annotated[
421
+ list[str],
422
+ typer.Argument(
423
+ help="Result JSONs written by `rollout --out`, or directories of them."
424
+ ),
425
+ ],
426
+ out: Annotated[
427
+ str, typer.Option("--out", help="JSON Lines file for the SFT rows.")
428
+ ] = "sft_rows.jsonl",
429
+ min_reward: Annotated[
430
+ Optional[float],
431
+ typer.Option(
432
+ "--min-reward",
433
+ help="Keep only rollouts graded at least this, e.g. 1.0 for solved tasks. Unset, every rollout is kept with its reward.",
434
+ ),
435
+ ] = None,
436
+ reward_key: Annotated[
437
+ str,
438
+ typer.Option(
439
+ "--reward-key",
440
+ 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.",
441
+ ),
442
+ ] = "",
443
+ push_to: Annotated[
444
+ str,
445
+ typer.Option("--push-to", help="Hub dataset repo to upload the rows to."),
446
+ ] = "",
447
+ private: Annotated[
448
+ Optional[bool],
449
+ typer.Option(
450
+ "--private",
451
+ help="Create --push-to as a private dataset. Unset, the namespace's default visibility applies.",
452
+ ),
453
+ ] = None,
454
+ ) -> None:
455
+ """Turn rollouts into conversational SFT rows (`messages` + `tools`), one per rollout.
456
+
457
+ Works on evaluation rollouts against a hosted model: SFT needs the conversation, not token ids. To train on the
458
+ rows, type `messages` and `tools` with the `Json` feature of `datasets`: a schema inferred from the rows gives
459
+ every tool call the argument names of every other tool, as `None`.
460
+ """
461
+ from openenv.core.utils import redact_secrets
462
+ from openenv.harbor.sft import export_sft
463
+
464
+ rows, stats = export_sft(
465
+ _read_results(results), min_reward=min_reward, reward_key=reward_key
466
+ )
467
+ # Rows hold what the agent saw and printed, which can include credentials.
468
+ text, redacted = redact_secrets("".join(json.dumps(row) + "\n" for row in rows))
469
+ path = Path(out)
470
+ path.write_text(text)
471
+ print(f"{stats.rows} rows from {stats.rollouts} rollouts -> {path}")
472
+ if redacted:
473
+ print(f" redacted {redacted} secret(s)")
474
+ if stats.below_min_reward or stats.ungraded:
475
+ print(
476
+ f" dropped: {stats.below_min_reward} below --min-reward, {stats.ungraded} ungraded"
477
+ )
478
+ skipped = {
479
+ "had no agent turn": stats.no_agent_turn,
480
+ "had an unusable capture": stats.capture_failed,
481
+ "ended on an empty reply": stats.empty_reply,
482
+ "held a tool call whose arguments aren't a JSON object": stats.malformed_tool_call,
483
+ }
484
+ for reason, count in skipped.items():
485
+ if count:
486
+ print(f" {count} rollouts {reason}, skipped")
487
+ if stats.ended_on_tool_call:
488
+ print(
489
+ f" {len(stats.ended_on_tool_call)} rollouts ended right after a tool call, usually a failed model call"
490
+ f" worth rerunning: {', '.join(stats.ended_on_tool_call)}"
491
+ )
492
+ if push_to:
493
+ from huggingface_hub import HfApi
494
+
495
+ api = HfApi()
496
+ api.create_repo(push_to, repo_type="dataset", private=private, exist_ok=True)
497
+ api.upload_file(
498
+ path_or_fileobj=path,
499
+ path_in_repo=f"data/{path.name}",
500
+ repo_id=push_to,
501
+ repo_type="dataset",
502
+ )
503
+ print(f"pushed to https://huggingface.co/datasets/{push_to}")
504
+
505
+
506
  @app.command("serve")
507
  def serve(
508
  llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)] = "",
 
571
  reward_key: Annotated[
572
  str, typer.Option("--reward-key", help=_REWARD_KEY_HELP)
573
  ] = "",
574
+ allow_harness: Annotated[
575
+ Optional[list[str]],
576
+ typer.Option(
577
+ "--allow-harness",
578
+ help=(
579
+ "Accept this `module:Class` harness in clients' rollouts. Naming a class imports "
580
+ "its module on this server, so other import paths are refused. Repeatable."
581
+ ),
582
+ ),
583
+ ] = None,
584
  ) -> None:
585
  """Serve Harbor tasks over the OpenEnv Task API and MCP.
586
 
 
604
  )
605
  # The UI's laptop defaults (this machine's token, private URLs) are for a loopback-only server.
606
  os.environ["OPENENV_HARBOR_UI_HOST"] = host
607
+ if allow_harness:
608
+ os.environ["OPENENV_HARBOR_ALLOW_HARNESS"] = ",".join(allow_harness)
609
  serve_harbor(
610
  llm_url=llm_url,
611
  model=model or None,
src/core/openenv/cli/commands/push.py CHANGED
@@ -5,7 +5,6 @@
5
  from __future__ import annotations
6
 
7
  import shutil
8
- import sys
9
  import tempfile
10
  from fnmatch import fnmatch
11
  from pathlib import Path
@@ -407,14 +406,14 @@ def _prepare_staging_directory(
407
  # Add base_path to existing frontmatter
408
  lines = readme_content.split("\n")
409
  new_lines = []
410
- _in_frontmatter = True
411
  for i, line in enumerate(lines):
412
  new_lines.append(line)
413
  if line.strip() == "---" and i > 0:
414
  # End of frontmatter, add base_path before this line
415
  if "base_path:" not in "\n".join(new_lines):
416
  new_lines.insert(-1, "base_path: /web")
417
- _in_frontmatter = False
 
418
  readme_path.write_text("\n".join(new_lines))
419
  else:
420
  # No frontmatter, add it
@@ -682,7 +681,6 @@ def push(
682
  if no_interface and interface:
683
  console.print(
684
  "[bold red]Error:[/bold red] Cannot specify both --interface and --no-interface",
685
- file=sys.stderr,
686
  )
687
  raise typer.Exit(1)
688
 
 
5
  from __future__ import annotations
6
 
7
  import shutil
 
8
  import tempfile
9
  from fnmatch import fnmatch
10
  from pathlib import Path
 
406
  # Add base_path to existing frontmatter
407
  lines = readme_content.split("\n")
408
  new_lines = []
 
409
  for i, line in enumerate(lines):
410
  new_lines.append(line)
411
  if line.strip() == "---" and i > 0:
412
  # End of frontmatter, add base_path before this line
413
  if "base_path:" not in "\n".join(new_lines):
414
  new_lines.insert(-1, "base_path: /web")
415
+ new_lines.extend(lines[i + 1 :])
416
+ break
417
  readme_path.write_text("\n".join(new_lines))
418
  else:
419
  # No frontmatter, add it
 
681
  if no_interface and interface:
682
  console.print(
683
  "[bold red]Error:[/bold red] Cannot specify both --interface and --no-interface",
 
684
  )
685
  raise typer.Exit(1)
686
 
src/core/openenv/cli/commands/serve.py CHANGED
@@ -1,20 +1,20 @@
1
  # SPDX-License-Identifier: BSD-3-Clause
2
 
3
- """Serve OpenEnv environments locally (TO BE IMPLEMENTED)."""
4
 
5
  from __future__ import annotations
6
 
 
 
7
  from pathlib import Path
8
  from typing import Annotated
9
 
10
  import typer
 
11
 
12
- from .._cli_utils import console
13
 
14
- app = typer.Typer(help="Serve OpenEnv environments locally")
15
 
16
-
17
- @app.command()
18
  def serve(
19
  env_path: Annotated[
20
  str | None,
@@ -23,68 +23,133 @@ def serve(
23
  ),
24
  ] = None,
25
  port: Annotated[
26
- int,
27
- typer.Option("--port", "-p", help="Port to serve on"),
28
- ] = 8000,
 
 
 
 
29
  host: Annotated[
30
  str,
31
- typer.Option("--host", help="Host to bind to"),
32
- ] = "0.0.0.0",
33
  reload: Annotated[
34
  bool,
35
- typer.Option("--reload", help="Enable auto-reload on code changes"),
36
  ] = False,
37
  ) -> None:
38
  """
39
- Serve an OpenEnv environment locally.
40
-
41
- TODO: This command is currently not implemented and has been deferred for later.
42
 
43
- Planned functionality:
44
- - Run environment server locally without Docker
45
- - Support multiple deployment modes (local, notebook, cluster)
46
- - Auto-reload for development
47
- - Integration with environment's [project.scripts] entry point
48
 
49
- For now, use Docker-based serving:
50
- 1. Build the environment: openenv build
51
- 2. Run the container: docker run -p 8000:8000 <image-name>
52
-
53
- Or use uv directly:
54
- uv run --project . server --port 8000
55
  """
56
- console.print("[bold yellow]⚠ This command is not yet implemented[/bold yellow]\n")
57
-
58
- console.print(
59
- "The [bold cyan]openenv serve[/bold cyan] command has been deferred for later."
60
- )
61
-
62
- console.print("[bold]Alternative approaches:[/bold]\n")
63
 
64
- console.print("[cyan]Option 1: Docker-based serving (recommended)[/cyan]")
65
- console.print(" 1. Build the environment:")
66
- console.print(" [dim]$ openenv build[/dim]")
67
- console.print(" 2. Run the Docker container:")
68
- console.print(
69
- f" [dim]$ docker run -p {port}:{port} openenv-<env-name>:latest[/dim]\n"
70
  )
71
 
72
- console.print("[cyan]Option 2: Direct execution with uv[/cyan]")
73
-
74
- # Determine environment path
75
- if env_path is None:
76
- env_path_obj = Path.cwd()
77
- else:
78
- env_path_obj = Path(env_path)
79
-
80
- # Check for openenv.yaml
81
- openenv_yaml = env_path_obj / "openenv.yaml"
82
- if openenv_yaml.exists():
83
- console.print(" From your environment directory:")
84
- console.print(f" [dim]$ cd {env_path_obj}[/dim]")
85
- console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n")
86
- else:
87
- console.print(" From an environment directory with pyproject.toml:")
88
- console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n")
89
-
90
- raise typer.Exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # SPDX-License-Identifier: BSD-3-Clause
2
 
3
+ """Serve an OpenEnv environment locally (uvicorn, from ``openenv.yaml``)."""
4
 
5
  from __future__ import annotations
6
 
7
+ import os
8
+ import sys
9
  from pathlib import Path
10
  from typing import Annotated
11
 
12
  import typer
13
+ import yaml
14
 
15
+ from .._cli_utils import console, validate_env_structure
16
 
 
17
 
 
 
18
  def serve(
19
  env_path: Annotated[
20
  str | None,
 
23
  ),
24
  ] = None,
25
  port: Annotated[
26
+ int | None,
27
+ typer.Option(
28
+ "--port",
29
+ "-p",
30
+ help="Port to bind (default: ``port`` in openenv.yaml, else 8000)",
31
+ ),
32
+ ] = None,
33
  host: Annotated[
34
  str,
35
+ typer.Option("--host", help="Host interface to bind (local development only)"),
36
+ ] = "127.0.0.1",
37
  reload: Annotated[
38
  bool,
39
+ typer.Option("--reload", help="Enable autoreload (development)"),
40
  ] = False,
41
  ) -> None:
42
  """
43
+ Run the environment FastAPI app on the host for local development.
 
 
44
 
45
+ Uses ``openenv.yaml`` fields ``app`` (e.g. ``server.app:app``), ``port``, and
46
+ ``runtime`` (must be ``fastapi``). Matches ``uv run --project . server`` layout:
47
+ the environment directory is the working directory. Package-qualified app
48
+ paths also support the environment package and the repo's ``envs`` package.
 
49
 
50
+ For production or training, use Docker (``openenv build``) — this command runs
51
+ on the host for local development only.
 
 
 
 
52
  """
53
+ import uvicorn
 
 
 
 
 
 
54
 
55
+ env_path_obj = (
56
+ Path.cwd().resolve() if env_path is None else Path(env_path).resolve()
 
 
 
 
57
  )
58
 
59
+ if not env_path_obj.exists():
60
+ typer.echo(f"Error: Path does not exist: {env_path_obj}", err=True)
61
+ raise typer.Exit(1)
62
+
63
+ if not env_path_obj.is_dir():
64
+ typer.echo(f"Error: Path is not a directory: {env_path_obj}", err=True)
65
+ raise typer.Exit(1)
66
+
67
+ try:
68
+ validate_env_structure(env_path_obj)
69
+ except FileNotFoundError as exc:
70
+ raise typer.BadParameter(f"Not a valid OpenEnv environment: {exc}") from exc
71
+
72
+ manifest_path = env_path_obj / "openenv.yaml"
73
+ try:
74
+ with manifest_path.open("r", encoding="utf-8") as handle:
75
+ manifest = yaml.safe_load(handle)
76
+ except OSError as exc:
77
+ raise typer.BadParameter(f"Failed to read openenv.yaml: {exc}") from exc
78
+ except yaml.YAMLError as exc:
79
+ raise typer.BadParameter(f"Invalid YAML in openenv.yaml: {exc}") from exc
80
+
81
+ if not isinstance(manifest, dict):
82
+ raise typer.BadParameter("openenv.yaml must be a YAML dictionary")
83
+
84
+ app_spec = manifest.get("app")
85
+ if not app_spec or not isinstance(app_spec, str):
86
+ raise typer.BadParameter(
87
+ "openenv.yaml must contain a string 'app' field (e.g. server.app:app)"
88
+ )
89
+ if ":" not in app_spec:
90
+ raise typer.BadParameter(
91
+ f"openenv.yaml 'app' must look like 'module.path:attribute', got {app_spec!r}"
92
+ )
93
+
94
+ runtime = str(manifest.get("runtime", "fastapi")).lower()
95
+ if runtime != "fastapi":
96
+ raise typer.BadParameter(
97
+ f"openenv serve only supports runtime 'fastapi' (got {runtime!r})"
98
+ )
99
+
100
+ raw_port = port if port is not None else manifest.get("port", 8000)
101
+ try:
102
+ listen_port = int(raw_port)
103
+ except (TypeError, ValueError) as exc:
104
+ raise typer.BadParameter(
105
+ f"Invalid port {raw_port!r}; expected an integer"
106
+ ) from exc
107
+ if not (1 <= listen_port <= 65535):
108
+ raise typer.BadParameter(
109
+ f"Invalid port {listen_port}; expected a value between 1 and 65535"
110
+ )
111
+
112
+ original_path = list(sys.path)
113
+ prev_cwd = os.getcwd()
114
+ env_root = str(env_path_obj)
115
+ app_dir = env_path_obj
116
+ module_name = app_spec.split(":", 1)[0]
117
+ # Prefer a module inside the environment, even when its package name matches
118
+ # the environment directory (for example, /work/server/server/app.py).
119
+ local_module = env_path_obj.joinpath(*module_name.split("."))
120
+ if not (
121
+ local_module.with_suffix(".py").is_file()
122
+ or (local_module / "__init__.py").is_file()
123
+ ):
124
+ if env_path_obj.parent.name == "envs" and module_name.startswith(
125
+ f"envs.{env_path_obj.name}."
126
+ ):
127
+ app_dir = env_path_obj.parent.parent
128
+ elif module_name.startswith(f"{env_path_obj.name}."):
129
+ app_dir = env_path_obj.parent
130
+
131
+ try:
132
+ os.chdir(env_root)
133
+
134
+ console.print(
135
+ f"[bold green]Serving[/bold green] [cyan]{app_spec}[/cyan] on "
136
+ f"[bold]http://{host}:{listen_port}/[/bold] (cwd: {env_root})"
137
+ )
138
+
139
+ try:
140
+ uvicorn.run(
141
+ app_spec,
142
+ host=host,
143
+ port=listen_port,
144
+ reload=reload,
145
+ app_dir=str(app_dir),
146
+ )
147
+ except OSError as exc:
148
+ typer.echo(f"Error: {exc}", err=True)
149
+ raise typer.Exit(1) from exc
150
+ finally:
151
+ try:
152
+ os.chdir(prev_cwd)
153
+ except OSError:
154
+ pass
155
+ sys.path[:] = original_path
src/core/openenv/cli/commands/skills.py CHANGED
@@ -38,7 +38,7 @@ _SKILL_TIPS = """
38
 
39
  Use `openenv <command> --help` for full flag reference.
40
 
41
- Full CLI reference: https://huggingface.co/docs/openenv/reference/cli
42
  """
43
 
44
  CENTRAL_LOCAL = Path(".agents/skills")
 
38
 
39
  Use `openenv <command> --help` for full flag reference.
40
 
41
+ Full CLI reference: https://openenv.github.io/OpenEnv/main/reference/cli
42
  """
43
 
44
  CENTRAL_LOCAL = Path(".agents/skills")
src/core/openenv/cli/commands/validate.py CHANGED
@@ -3,9 +3,13 @@
3
  """OpenEnv validate command."""
4
 
5
  import json
 
6
  import signal
 
7
  import threading
8
- from contextlib import contextmanager
 
 
9
  from pathlib import Path
10
  from typing import Annotated, Any
11
 
@@ -30,6 +34,39 @@ EXIT_UNSUPPORTED = 2
30
  EXIT_INTERNAL = 3
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  @contextmanager
34
  def _sigterm_as_interrupt():
35
  """Treat SIGTERM like Ctrl-C so the runner cleans up its subject."""
@@ -168,15 +205,63 @@ def validate(
168
  min=0.1,
169
  ),
170
  ] = 5.0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  ) -> None:
172
  """
173
  Validate a local package or a running OpenEnv server.
174
 
175
  Local validation detects the package format by its well-known file (the
176
- formats this build can parse; currently `openenv.yaml`), parses it into the
177
  normalized manifest, runs the applicable graders up to the requested level,
178
  applies the severity policy, and emits a report.
179
 
 
 
 
 
 
 
 
180
  Exit codes: 0 pass/warn · 1 fail · 2 unrecognized/unsupported package · 3
181
  internal or policy error.
182
 
@@ -194,8 +279,43 @@ def validate(
194
 
195
  # Probe a running server (legacy runtime probe)
196
  openenv validate --url http://localhost:8000
 
 
 
 
 
 
197
  ```
198
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  runtime_target = url
200
  if (
201
  runtime_target is not None
@@ -249,22 +369,52 @@ def validate(
249
  raise typer.Exit(EXIT_INTERNAL)
250
 
251
  package_root = Path(target) if target is not None else Path.cwd()
252
- if not package_root.is_dir():
253
  typer.echo(f"Error: not a package directory: {package_root}", err=True)
254
  raise typer.Exit(EXIT_UNSUPPORTED)
255
 
256
  try:
257
  if output is not None and not output.parent.is_dir():
258
  raise OSError("report output directory does not exist")
259
- with _sigterm_as_interrupt():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  validation_report = run_validation(
261
  package_root,
262
  max_level=_LEVELS[level],
263
  skip_build=skip_build,
264
  policy=load_policy(policy_version) if policy_version else None,
 
265
  artifacts_dir=(
266
  output.parent / (output.stem + ".artifacts") if output else None
267
  ),
 
 
 
 
 
 
268
  )
269
  report_json = write_report(validation_report, output)
270
  except (SignatureError, UnsupportedPackageError) as exc:
 
3
  """OpenEnv validate command."""
4
 
5
  import json
6
+ import shutil
7
  import signal
8
+ import tempfile
9
  import threading
10
+ from contextlib import contextmanager, ExitStack
11
+ from dataclasses import dataclass
12
+ from functools import cached_property
13
  from pathlib import Path
14
  from typing import Annotated, Any
15
 
 
34
  EXIT_INTERNAL = 3
35
 
36
 
37
+ @dataclass
38
+ class _LazyHFSandboxProvider:
39
+ """Defer Jobs hardware preflight until the runner needs runtime capabilities."""
40
+
41
+ name = "hf-sandbox"
42
+
43
+ space_id: str
44
+ revision: str
45
+ flavor: str
46
+
47
+ @cached_property
48
+ def _provider(self):
49
+ from openenv.validation.providers.hf_sandbox import HFSandboxValidationProvider
50
+
51
+ return HFSandboxValidationProvider(
52
+ self.space_id, self.revision, flavor=self.flavor
53
+ )
54
+
55
+ @property
56
+ def supported_network_modes(self):
57
+ return self._provider.supported_network_modes
58
+
59
+ @property
60
+ def capabilities(self):
61
+ return self._provider.capabilities
62
+
63
+ def build(self, root, execution):
64
+ return self._provider.build(root, execution)
65
+
66
+ def start(self, spec):
67
+ return self._provider.start(spec)
68
+
69
+
70
  @contextmanager
71
  def _sigterm_as_interrupt():
72
  """Treat SIGTERM like Ctrl-C so the runner cleans up its subject."""
 
205
  min=0.1,
206
  ),
207
  ] = 5.0,
208
+ space: Annotated[
209
+ str | None,
210
+ typer.Option(
211
+ "--space",
212
+ help="Validate a Hugging Face Space (e.g. openenv/echo_env) on HF Jobs",
213
+ ),
214
+ ] = None,
215
+ revision: Annotated[
216
+ str | None,
217
+ typer.Option(
218
+ "--revision",
219
+ help="Space branch, tag or commit hash to validate (default: main)",
220
+ ),
221
+ ] = None,
222
+ flavor: Annotated[
223
+ str,
224
+ typer.Option(
225
+ "--flavor",
226
+ help=(
227
+ "HF Jobs hardware flavor for --space or --sandbox hf-sandbox, "
228
+ "e.g. cpu-basic or t4-small"
229
+ ),
230
+ ),
231
+ ] = "cpu-basic",
232
+ sandbox: Annotated[
233
+ str,
234
+ typer.Option(
235
+ "--sandbox",
236
+ help=(
237
+ "Where Harbor task trials run: docker (local daemon) or "
238
+ "hf-sandbox (one HF Job per trial)"
239
+ ),
240
+ ),
241
+ ] = "docker",
242
+ namespace: Annotated[
243
+ str | None,
244
+ typer.Option(
245
+ "--namespace",
246
+ help="User or organization that owns the --sandbox hf-sandbox jobs",
247
+ ),
248
+ ] = None,
249
  ) -> None:
250
  """
251
  Validate a local package or a running OpenEnv server.
252
 
253
  Local validation detects the package format by its well-known file (the
254
+ formats this build can parse: `openenv.yaml` or Harbor `task.toml`), parses it into the
255
  normalized manifest, runs the applicable graders up to the requested level,
256
  applies the severity policy, and emits a report.
257
 
258
+ Native Harbor tasks require the optional Harbor dependency and an explicit
259
+ `validation/openenv.json` contract. Fresh trials grade the oracle, the
260
+ do-nothing floor and any declared canaries under the semantic check ids. They
261
+ run on the local Docker daemon, or with `--sandbox hf-sandbox` as one Hugging
262
+ Face Job per trial from the task's digest-pinned image. Checks without an
263
+ implementation are named SKIPs, so the report is WARN at best.
264
+
265
  Exit codes: 0 pass/warn · 1 fail · 2 unrecognized/unsupported package · 3
266
  internal or policy error.
267
 
 
279
 
280
  # Probe a running server (legacy runtime probe)
281
  openenv validate --url http://localhost:8000
282
+
283
+ # Validate a Hub Space on HF Jobs GPU hardware
284
+ openenv validate --space openenv/echo_env --level runtime --flavor t4-small
285
+
286
+ # Run a Harbor task's trials as HF Jobs instead of local Docker
287
+ openenv validate path/to/task --sandbox hf-sandbox --flavor cpu-upgrade
288
  ```
289
  """
290
+ if space is not None and (target is not None or url is not None or local):
291
+ typer.echo(
292
+ "Error: --space cannot be combined with a path, --url or --local", err=True
293
+ )
294
+ raise typer.Exit(EXIT_FAIL)
295
+ if sandbox not in ("docker", "hf-sandbox"):
296
+ typer.echo(
297
+ f"Error: unknown sandbox {sandbox!r}; expected docker or hf-sandbox",
298
+ err=True,
299
+ )
300
+ raise typer.Exit(EXIT_FAIL)
301
+ hf_sandbox = sandbox == "hf-sandbox"
302
+ running_url = url is not None or (target is not None and _looks_like_url(target))
303
+ if hf_sandbox and (space is not None or running_url):
304
+ typer.echo(
305
+ "Error: --sandbox cannot be combined with --space or a running URL",
306
+ err=True,
307
+ )
308
+ raise typer.Exit(EXIT_FAIL)
309
+ if space is None and revision is not None:
310
+ typer.echo("Error: --revision requires --space", err=True)
311
+ raise typer.Exit(EXIT_FAIL)
312
+ if space is None and not hf_sandbox and flavor != "cpu-basic":
313
+ typer.echo("Error: --flavor requires --space or --sandbox hf-sandbox", err=True)
314
+ raise typer.Exit(EXIT_FAIL)
315
+ if namespace is not None and not hf_sandbox:
316
+ typer.echo("Error: --namespace requires --sandbox hf-sandbox", err=True)
317
+ raise typer.Exit(EXIT_FAIL)
318
+
319
  runtime_target = url
320
  if (
321
  runtime_target is not None
 
369
  raise typer.Exit(EXIT_INTERNAL)
370
 
371
  package_root = Path(target) if target is not None else Path.cwd()
372
+ if space is None and not package_root.is_dir():
373
  typer.echo(f"Error: not a package directory: {package_root}", err=True)
374
  raise typer.Exit(EXIT_UNSUPPORTED)
375
 
376
  try:
377
  if output is not None and not output.parent.is_dir():
378
  raise OSError("report output directory does not exist")
379
+ with ExitStack() as stack:
380
+ provider = None
381
+ if space is not None:
382
+ from huggingface_hub import HfApi, snapshot_download
383
+
384
+ # Download and report one commit, even if a branch moves.
385
+ revision = (
386
+ HfApi()
387
+ .space_info(
388
+ space, revision="main" if revision is None else revision
389
+ )
390
+ .sha
391
+ )
392
+ package_root = (
393
+ Path(stack.enter_context(tempfile.TemporaryDirectory())) / "source"
394
+ )
395
+ # Copy the repository snapshot out of the SDK cache, dereferencing
396
+ # its blob links without adding local_dir download metadata.
397
+ shutil.copytree(
398
+ snapshot_download(space, repo_type="space", revision=revision),
399
+ package_root,
400
+ )
401
+ provider = _LazyHFSandboxProvider(space, revision, flavor)
402
+ stack.enter_context(_sigterm_as_interrupt())
403
  validation_report = run_validation(
404
  package_root,
405
  max_level=_LEVELS[level],
406
  skip_build=skip_build,
407
  policy=load_policy(policy_version) if policy_version else None,
408
+ provider=provider,
409
  artifacts_dir=(
410
  output.parent / (output.stem + ".artifacts") if output else None
411
  ),
412
+ report_target=f"spaces/{space}@{revision}"
413
+ if space is not None
414
+ else None,
415
+ sandbox=sandbox,
416
+ flavor=flavor,
417
+ namespace=namespace,
418
  )
419
  report_json = write_report(validation_report, output)
420
  except (SignatureError, UnsupportedPackageError) as exc:
src/core/openenv/cli/importers/__init__.py CHANGED
@@ -1,12 +1,14 @@
1
  """Deterministic source importers for OpenEnv environments."""
2
 
 
3
  from .base import DetectedEnvironment, EnvironmentImporter, ImporterRegistry
4
  from .ors import ORSImporter
5
  from .verifiers import VerifiersImporter
6
 
7
- DEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter()]
8
 
9
  __all__ = [
 
10
  "DEFAULT_IMPORTERS",
11
  "DetectedEnvironment",
12
  "EnvironmentImporter",
 
1
  """Deterministic source importers for OpenEnv environments."""
2
 
3
+ from .agentenv import AgentEnvImporter
4
  from .base import DetectedEnvironment, EnvironmentImporter, ImporterRegistry
5
  from .ors import ORSImporter
6
  from .verifiers import VerifiersImporter
7
 
8
+ DEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter(), AgentEnvImporter()]
9
 
10
  __all__ = [
11
+ "AgentEnvImporter",
12
  "DEFAULT_IMPORTERS",
13
  "DetectedEnvironment",
14
  "EnvironmentImporter",
src/core/openenv/cli/importers/agentenv.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AgentEnv bundle source importer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from packaging.requirements import InvalidRequirement, Requirement
9
+ from packaging.specifiers import SpecifierSet
10
+ from packaging.utils import canonicalize_name
11
+
12
+ from .._cli_utils import console
13
+ from .base import (
14
+ append_dependency_files,
15
+ collect_source_dependencies,
16
+ DetectedEnvironment,
17
+ iter_directories,
18
+ prepare_import_package,
19
+ render_importer_template,
20
+ write_text,
21
+ )
22
+
23
+
24
+ _FRAMEWORK = "agentenv-framework"
25
+ _FRAMEWORK_EXTRA = "openenv"
26
+ _FRAMEWORK_VERSION = "0.9.1366"
27
+ _FRAMEWORK_FLOOR = f">={_FRAMEWORK_VERSION}"
28
+ _ADAPTER_SOURCE = (
29
+ "https://github.com/scaleapi/agentenv-framework/blob/"
30
+ f"v{_FRAMEWORK_VERSION}/src/agent_env/openenv"
31
+ )
32
+ _REQUIRES_PYTHON = ">=3.11.4"
33
+
34
+
35
+ def _is_task_file(path: Path) -> bool:
36
+ try:
37
+ steps = json.loads(path.read_text(encoding="utf-8"))
38
+ except (OSError, UnicodeDecodeError, ValueError):
39
+ return False
40
+ return (
41
+ isinstance(steps, list)
42
+ and bool(steps)
43
+ and all(
44
+ isinstance(step, dict)
45
+ and isinstance(step.get("id"), str)
46
+ and isinstance(step.get("type"), str)
47
+ for step in steps
48
+ )
49
+ )
50
+
51
+
52
+ def detect_agentenv_bundles(source: Path) -> list[DetectedEnvironment]:
53
+ """Detect AgentEnv bundles, folders whose tasks/ holds task files, without importing source."""
54
+ source = source.resolve()
55
+ matches: list[DetectedEnvironment] = []
56
+
57
+ for tasks_dir in iter_directories(source, "tasks"):
58
+ if not any(_is_task_file(path) for path in sorted(tasks_dir.glob("*.json"))):
59
+ continue
60
+ bundle = tasks_dir.parent
61
+ matches.append(
62
+ DetectedEnvironment(
63
+ source_type="agentenv",
64
+ class_name=bundle.name,
65
+ module_path=""
66
+ if bundle == source
67
+ else bundle.relative_to(source).as_posix(),
68
+ file_path=bundle,
69
+ )
70
+ )
71
+
72
+ return matches
73
+
74
+
75
+ def _with_framework_floor(dependencies: list[str]) -> list[str]:
76
+ """The bundle's dependencies, with agentenv-framework's openenv extra at least the version that serves bundles."""
77
+ for index, dependency in enumerate(dependencies):
78
+ try:
79
+ requirement = Requirement(dependency)
80
+ except InvalidRequirement:
81
+ continue
82
+ if canonicalize_name(requirement.name) == _FRAMEWORK:
83
+ if requirement.url is not None:
84
+ raise ValueError(
85
+ f"Cannot verify {_FRAMEWORK}{_FRAMEWORK_FLOOR} from a direct "
86
+ "reference. In the bundle's pyproject.toml or requirements.txt, "
87
+ "replace the framework direct reference with a version constraint "
88
+ f"such as {_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}, "
89
+ "preserving any additional extras and environment marker."
90
+ )
91
+ requirement.extras.add(_FRAMEWORK_EXTRA)
92
+ requirement.specifier &= SpecifierSet(_FRAMEWORK_FLOOR)
93
+ dependencies[index] = str(requirement)
94
+ return dependencies
95
+ return [*dependencies, f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}"]
96
+
97
+
98
+ class AgentEnvImporter:
99
+ """Importer for AgentEnv bundles, served by agentenv-framework's OpenEnv server."""
100
+
101
+ source_type = "agentenv"
102
+
103
+ def detect(self, source: Path) -> list[DetectedEnvironment]:
104
+ return detect_agentenv_bundles(source)
105
+
106
+ def generate(
107
+ self,
108
+ *,
109
+ source: Path,
110
+ destination: Path,
111
+ env_name: str,
112
+ detected: DetectedEnvironment,
113
+ ) -> None:
114
+ bundle = detected.file_path
115
+ dependencies = _with_framework_floor(collect_source_dependencies(bundle))
116
+ package = prepare_import_package(
117
+ bundle, destination, env_name, vendor_dir=bundle.name
118
+ )
119
+ client = f"{package.class_name_prefix}Env"
120
+ (destination / "server" / f"{env_name}_environment.py").unlink()
121
+ (destination / "models.py").unlink()
122
+ for name, template in (
123
+ ("client.py", "agentenv_client.py.tpl"),
124
+ ("__init__.py", "agentenv_init.py.tpl"),
125
+ ):
126
+ write_text(
127
+ destination / name,
128
+ render_importer_template(template, env_name=env_name, client=client),
129
+ )
130
+ write_text(
131
+ destination / "server" / "__init__.py",
132
+ f'"""{env_name} environment server: an AgentEnv bundle."""\n',
133
+ )
134
+ write_text(
135
+ destination / "server" / "app.py",
136
+ render_importer_template(
137
+ "agentenv_app.py.tpl", bundle=json.dumps(bundle.name)
138
+ ),
139
+ )
140
+ write_text(
141
+ destination / "README.md",
142
+ render_importer_template(
143
+ "agentenv_README.md.tpl",
144
+ env_name=env_name,
145
+ bundle=bundle.name,
146
+ framework=f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}",
147
+ adapter=_ADAPTER_SOURCE,
148
+ client=client,
149
+ ),
150
+ )
151
+ console.print(
152
+ "[yellow]Warning:[/yellow] AgentEnv requires local Docker: a Docker CLI "
153
+ "and a running daemon accessible to the server for image builds and episode "
154
+ "containers. The generated server/Dockerfile does not provide this "
155
+ "runtime; openenv build / openenv push alone do not produce a working "
156
+ "deployment. See README.md for prerequisites."
157
+ )
158
+ append_dependency_files(
159
+ destination,
160
+ env_name,
161
+ dependencies,
162
+ requires_python=_REQUIRES_PYTHON,
163
+ )
src/core/openenv/cli/importers/base.py CHANGED
@@ -133,6 +133,14 @@ def iter_python_files(source: Path) -> list[Path]:
133
  ]
134
 
135
 
 
 
 
 
 
 
 
 
136
  def module_path(source: Path, file_path: Path) -> str:
137
  rel = file_path.relative_to(source).with_suffix("")
138
  parts = list(rel.parts)
@@ -196,6 +204,7 @@ def append_dependency_files(
196
  env_dir: Path,
197
  env_name: str,
198
  dependencies: list[str],
 
199
  ) -> None:
200
  requirements = env_dir / "server" / "requirements.txt"
201
  if requirements.exists():
@@ -231,6 +240,8 @@ def append_dependency_files(
231
  project_dependencies.append(dependency)
232
  existing.add(_dependency_name(dependency))
233
  project["dependencies"] = project_dependencies
 
 
234
 
235
  tool = data.setdefault("tool", {})
236
  setuptools = tool.setdefault("setuptools", {})
@@ -266,7 +277,7 @@ class ImportPackageContext:
266
 
267
 
268
  def prepare_import_package(
269
- source: Path, destination: Path, env_name: str
270
  ) -> ImportPackageContext:
271
  from openenv.cli.commands.init import (
272
  _copy_template_directory,
@@ -282,7 +293,7 @@ def prepare_import_package(
282
  env_name,
283
  )
284
 
285
- vendor_dir = safe_vendor_dir_name(source)
286
  vendor_path = destination / "vendor" / vendor_dir
287
  copy_source_tree(source, vendor_path)
288
  ensure_vendor_package(vendor_path)
 
133
  ]
134
 
135
 
136
+ def iter_directories(source: Path, name: str) -> list[Path]:
137
+ return [
138
+ path
139
+ for path in sorted(source.rglob(name))
140
+ if path.is_dir() and not _is_excluded(path.relative_to(source))
141
+ ]
142
+
143
+
144
  def module_path(source: Path, file_path: Path) -> str:
145
  rel = file_path.relative_to(source).with_suffix("")
146
  parts = list(rel.parts)
 
204
  env_dir: Path,
205
  env_name: str,
206
  dependencies: list[str],
207
+ requires_python: str | None = None,
208
  ) -> None:
209
  requirements = env_dir / "server" / "requirements.txt"
210
  if requirements.exists():
 
240
  project_dependencies.append(dependency)
241
  existing.add(_dependency_name(dependency))
242
  project["dependencies"] = project_dependencies
243
+ if requires_python:
244
+ project["requires-python"] = requires_python
245
 
246
  tool = data.setdefault("tool", {})
247
  setuptools = tool.setdefault("setuptools", {})
 
277
 
278
 
279
  def prepare_import_package(
280
+ source: Path, destination: Path, env_name: str, vendor_dir: str | None = None
281
  ) -> ImportPackageContext:
282
  from openenv.cli.commands.init import (
283
  _copy_template_directory,
 
293
  env_name,
294
  )
295
 
296
+ vendor_dir = vendor_dir or safe_vendor_dir_name(source)
297
  vendor_path = destination / "vendor" / vendor_dir
298
  copy_source_tree(source, vendor_path)
299
  ensure_vendor_package(vendor_path)
src/core/openenv/cli/importers/templates/agentenv_README.md.tpl ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ${env_name}: AgentEnv bundle
2
+
3
+ This package serves the vendored `${bundle}` bundle through
4
+ `agent_env.openenv.build_app`. The bundle keeps its original folder name at
5
+ `vendor/${bundle}`; the generated package name is `${env_name}`.
6
+
7
+ ## Prerequisites
8
+
9
+ - Python >=3.11.4 and `${framework}` (declared in
10
+ `pyproject.toml` and `server/requirements.txt`).
11
+ - Local Docker: a Docker CLI and a running daemon accessible to the server.
12
+ The delegated server builds the bundle's environment images at startup and
13
+ deploys episode containers using local Docker by default.
14
+ - A self-contained bundle: tasks, environment definitions, verifiers, data and
15
+ dependencies must be included in the bundle or provided by agentenv-framework.
16
+ Only the selected bundle is vendored; external plugin registrations and files
17
+ elsewhere in the source repository are not included.
18
+
19
+ ## Run locally
20
+
21
+ From this generated package directory, after setting up Docker:
22
+
23
+ ```bash
24
+ uv sync
25
+ MAX_CONCURRENT_ENVS=8 uv run server --host 127.0.0.1 --port 8000
26
+ ```
27
+
28
+ `MAX_CONCURRENT_ENVS` (default 8) caps the concurrent sessions. Each session
29
+ plays its own episode on its own deployment.
30
+
31
+ The `server` entry point runs `server/app.py`, which passes
32
+ `vendor/${bundle}` to `build_app`. Task selection, splits, tools and rewards
33
+ are defined by the bundle and agentenv-framework. The served environment is
34
+ `agent_env.openenv`'s `AgentEnvEnvironment`; read it, and `build_app`, at the
35
+ minimum supported version: [environment.py](${adapter}/environment.py) and
36
+ [app.py](${adapter}/app.py). Follow
37
+ [AgentEnv's OpenEnv documentation](https://www.agentenvframework.com/docs/openenv)
38
+ for its API and client usage.
39
+
40
+ ## Client
41
+
42
+ `client.py` defines `${client}`, an `MCPToolClient`: the served environment
43
+ takes OpenEnv's MCP actions (`ListToolsAction`, `CallToolAction`), which
44
+ `__init__.py` also exports.
45
+
46
+ ```python
47
+ from ${env_name} import ${client}
48
+
49
+ async with ${client}(base_url="http://127.0.0.1:8000") as env:
50
+ await env.reset(split="all", index=0)
51
+ tools = await env.list_tools()
52
+ ended = await env.call_tool("end_turn", response="Done.")
53
+ print(ended["done"], ended["reward"])
54
+ ```
55
+
56
+ The tools are the bundle environment's MCP tools plus `end_turn`, which ends
57
+ the turn with its `response`. Its result carries the next turn's prompt, or,
58
+ once `done`, the task's reward. A step before `reset` raises.
59
+
60
+ `list_tools()` discovers fresh tools by default because tools can change after
61
+ reset, `end_turn`, or a bundle tool call. `get_tool()` and `has_tool()` also use
62
+ fresh discovery. Pass `list_tools(use_cache=True)` explicitly to reuse the last
63
+ discovery result.
64
+
65
+ ## Deployment limitations
66
+
67
+ **Warning:** `server/Dockerfile` does not provide the Docker runtime required
68
+ by the delegated server. `openenv build` / `openenv push` alone do not produce
69
+ a working deployment, including on Hugging Face Spaces. Deployment requires
70
+ separately provisioning the server's image-build and episode-container runtime;
71
+ this importer does not configure it. Review AgentEnv's runtime requirements
72
+ before choosing a deployment host.
73
+
74
+ ## Generated files
75
+
76
+ - `server/app.py`: delegated application and local server entry point.
77
+ - `vendor/${bundle}`: the selected bundle and its data.
78
+ - `pyproject.toml`: package dependencies and the `server` entry point.
79
+ - `server/requirements.txt`: server dependencies.
80
+ - `openenv.yaml`: generated OpenEnv manifest.
81
+ - `server/Dockerfile`: shared image template with the limitation described above.
82
+ - `client.py`, `__init__.py`: the client and the MCP action types it sends.
src/core/openenv/cli/importers/templates/agentenv_app.py.tpl ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ from agent_env.openenv import build_app
7
+
8
+
9
+ BUNDLE = Path(__file__).resolve().parents[1] / "vendor" / ${bundle}
10
+
11
+ app = build_app(
12
+ BUNDLE, max_concurrent_envs=int(os.getenv("MAX_CONCURRENT_ENVS", "8"))
13
+ )
14
+
15
+
16
+ def main():
17
+ import argparse
18
+
19
+ import uvicorn
20
+
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument("--host", default="0.0.0.0")
23
+ parser.add_argument("--port", type=int, default=8000)
24
+ args = parser.parse_args()
25
+ uvicorn.run(app, host=args.host, port=args.port)
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()
src/core/openenv/cli/importers/templates/agentenv_client.py.tpl ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """${env_name} client.
2
+
3
+ The served AgentEnv bundle takes OpenEnv's MCP actions, so this client is an
4
+ ``MCPToolClient``. Reset to a task, call the bundle's tools, and end each turn
5
+ with ``end_turn``. Its result carries the next turn's prompt, or once ``done``
6
+ the task's reward:
7
+
8
+ >>> async with ${client}(base_url="http://localhost:8000") as env:
9
+ ... await env.reset(split="all", index=0)
10
+ ... tools = await env.list_tools()
11
+ ... ended = await env.call_tool("end_turn", response="Done.")
12
+ ... print(ended["done"], ended["reward"])
13
+ """
14
+
15
+ from openenv.core.env_server.mcp_types import Tool
16
+ from openenv.core.mcp_client import MCPToolClient
17
+
18
+
19
+ class ${client}(MCPToolClient):
20
+ """Client for the ${env_name} environment."""
21
+
22
+ async def list_tools(self, use_cache: bool = False) -> list[Tool]:
23
+ """Discover the current task and turn's tools.
24
+
25
+ Args:
26
+ use_cache (`bool`, *optional*, defaults to `False`):
27
+ Set to `True` to reuse the last discovery result.
28
+ """
29
+ return await super().list_tools(use_cache=use_cache)