sergiopaniego HF Staff commited on
Commit
ee062a0
·
verified ·
1 Parent(s): e991348

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. README.md +4 -3
  2. envs/textarena_env/README.md +2 -1
  3. envs/textarena_env/pyproject.toml +1 -1
  4. envs/textarena_env/server/app.py +13 -4
  5. envs/textarena_env/server/environment.py +58 -5
  6. pyproject.toml +1 -1
  7. server/app.py +13 -4
  8. server/environment.py +58 -5
  9. src/core/README.md +6 -6
  10. src/core/containers/runtime/__init__.py +0 -2
  11. src/core/containers/runtime/kubernetes_provider.py +985 -0
  12. src/core/containers/runtime/providers.py +24 -17
  13. src/core/env_server/http_server.py +147 -17
  14. src/core/env_server/interfaces.py +1 -1
  15. src/core/env_server/mcp_environment.py +9 -12
  16. src/core/env_server/types.py +6 -0
  17. src/core/env_server/web_interface.py +6 -1
  18. src/core/harness/collect.py +20 -15
  19. src/core/openenv/cli/__main__.py +4 -3
  20. src/core/openenv/cli/commands/build.py +33 -59
  21. src/core/openenv/cli/commands/push.py +2 -4
  22. src/core/openenv/cli/commands/serve.py +122 -57
  23. src/core/openenv/cli/templates/openenv_env/pyproject.toml +1 -1
  24. src/core/openenv/cli/templates/openenv_env/server/app.py +1 -1
  25. src/core/openenv/core/README.md +6 -6
  26. src/core/openenv/core/containers/runtime/__init__.py +0 -2
  27. src/core/openenv/core/containers/runtime/kubernetes_provider.py +985 -0
  28. src/core/openenv/core/containers/runtime/providers.py +24 -17
  29. src/core/openenv/core/env_server/http_server.py +147 -17
  30. src/core/openenv/core/env_server/interfaces.py +1 -1
  31. src/core/openenv/core/env_server/mcp_environment.py +9 -12
  32. src/core/openenv/core/env_server/types.py +6 -0
  33. src/core/openenv/core/env_server/web_interface.py +6 -1
  34. src/core/openenv/core/harness/collect.py +20 -15
  35. src/core/openenv/core/rubrics/containers.py +14 -10
  36. src/core/openenv/core/sync_client.py +9 -2
  37. src/core/openenv/core/tools/git_server_client.py +8 -5
  38. src/core/openenv/discovery/schemas/0.1-draft/catalog.schema.json +1 -1
  39. src/core/openenv/discovery/schemas/0.1-draft/declaration.schema.json +1 -1
  40. src/core/openenv/discovery/schemas/0.1-draft/environment-card.schema.json +1 -1
  41. src/core/openenv/harbor/atif.py +20 -19
  42. src/core/rubrics/containers.py +14 -10
  43. src/core/sync_client.py +9 -2
  44. src/core/tools/git_server_client.py +8 -5
  45. src/openenv/cli/__main__.py +4 -3
  46. src/openenv/cli/commands/build.py +33 -59
  47. src/openenv/cli/commands/push.py +2 -4
  48. src/openenv/cli/commands/serve.py +122 -57
  49. src/openenv/cli/templates/openenv_env/pyproject.toml +1 -1
  50. src/openenv/cli/templates/openenv_env/server/app.py +1 -1
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
  ---
14
 
@@ -24,6 +24,7 @@ An OpenEnv wrapper for [TextArena](https://github.com/textarena/textarena) game
24
  > Generic wrapper for any [TextArena](https://www.textarena.ai/docs/overview) game inside OpenEnv. This module exposes the TextArena `Env` interface through the standard HTTP server/client APIs used by other OpenEnv environments, enabling quick experimentation with the full suite of word, reasoning, and multi-agent games.
25
 
26
  Try Wordle on the [`openenv/wordle`](https://huggingface.co/spaces/openenv/wordle) Space, or connect a client to `https://openenv-wordle.hf.space`.
 
27
 
28
  ## Quick Start
29
 
@@ -192,7 +193,7 @@ The server supports configuration via environment variables:
192
  - `TEXTARENA_NUM_PLAYERS` - Number of players (default: 1)
193
  - `TEXTARENA_MAX_TURNS` - Maximum turns per episode
194
  - `TEXTARENA_DOWNLOAD_NLTK` - Download NLTK data (default: "1")
195
- - `TEXTARENA_KW_*` - Pass additional kwargs to TextArena (e.g., `TEXTARENA_KW_difficulty=hard`)
196
 
197
  ## Development & Testing
198
 
@@ -259,7 +260,7 @@ textarena_env/
259
  This Space is built from OpenEnv environment `textarena_env`.
260
 
261
  - Space URL: `https://huggingface.co/spaces/openenv/sudoku`
262
- - OpenEnv pinned ref: `0.10.0`
263
  - Hub tag: `openenv`
264
 
265
  ### Connecting from Code
 
8
  app_port: 8000
9
  base_path: /web
10
  tags:
11
+ - openenv-0.11.0
12
  - openenv
13
  ---
14
 
 
24
  > Generic wrapper for any [TextArena](https://www.textarena.ai/docs/overview) game inside OpenEnv. This module exposes the TextArena `Env` interface through the standard HTTP server/client APIs used by other OpenEnv environments, enabling quick experimentation with the full suite of word, reasoning, and multi-agent games.
25
 
26
  Try Wordle on the [`openenv/wordle`](https://huggingface.co/spaces/openenv/wordle) Space, or connect a client to `https://openenv-wordle.hf.space`.
27
+ To train a model on it, follow the [Wordle tutorial](https://huggingface.co/docs/openenv/tutorials/wordle-grpo): an SFT warmup, then GRPO with TRL.
28
 
29
  ## Quick Start
30
 
 
193
  - `TEXTARENA_NUM_PLAYERS` - Number of players (default: 1)
194
  - `TEXTARENA_MAX_TURNS` - Maximum turns per episode
195
  - `TEXTARENA_DOWNLOAD_NLTK` - Download NLTK data (default: "1")
196
+ - `TEXTARENA_KW_*` - Pass additional kwargs to TextArena. Values are read as JSON, so numbers and booleans keep their type (e.g., `TEXTARENA_KW_CLUES=65` for Sudoku, `TEXTARENA_KW_difficulty=hard`)
197
 
198
  ## Development & Testing
199
 
 
260
  This Space is built from OpenEnv environment `textarena_env`.
261
 
262
  - Space URL: `https://huggingface.co/spaces/openenv/sudoku`
263
+ - OpenEnv pinned ref: `0.11.0`
264
  - Hub tag: `openenv`
265
 
266
  ### Connecting from Code
envs/textarena_env/README.md CHANGED
@@ -23,6 +23,7 @@ An OpenEnv wrapper for [TextArena](https://github.com/textarena/textarena) game
23
  > Generic wrapper for any [TextArena](https://www.textarena.ai/docs/overview) game inside OpenEnv. This module exposes the TextArena `Env` interface through the standard HTTP server/client APIs used by other OpenEnv environments, enabling quick experimentation with the full suite of word, reasoning, and multi-agent games.
24
 
25
  Try Wordle on the [`openenv/wordle`](https://huggingface.co/spaces/openenv/wordle) Space, or connect a client to `https://openenv-wordle.hf.space`.
 
26
 
27
  ## Quick Start
28
 
@@ -191,7 +192,7 @@ The server supports configuration via environment variables:
191
  - `TEXTARENA_NUM_PLAYERS` - Number of players (default: 1)
192
  - `TEXTARENA_MAX_TURNS` - Maximum turns per episode
193
  - `TEXTARENA_DOWNLOAD_NLTK` - Download NLTK data (default: "1")
194
- - `TEXTARENA_KW_*` - Pass additional kwargs to TextArena (e.g., `TEXTARENA_KW_difficulty=hard`)
195
 
196
  ## Development & Testing
197
 
 
23
  > Generic wrapper for any [TextArena](https://www.textarena.ai/docs/overview) game inside OpenEnv. This module exposes the TextArena `Env` interface through the standard HTTP server/client APIs used by other OpenEnv environments, enabling quick experimentation with the full suite of word, reasoning, and multi-agent games.
24
 
25
  Try Wordle on the [`openenv/wordle`](https://huggingface.co/spaces/openenv/wordle) Space, or connect a client to `https://openenv-wordle.hf.space`.
26
+ To train a model on it, follow the [Wordle tutorial](https://huggingface.co/docs/openenv/tutorials/wordle-grpo): an SFT warmup, then GRPO with TRL.
27
 
28
  ## Quick Start
29
 
 
192
  - `TEXTARENA_NUM_PLAYERS` - Number of players (default: 1)
193
  - `TEXTARENA_MAX_TURNS` - Maximum turns per episode
194
  - `TEXTARENA_DOWNLOAD_NLTK` - Download NLTK data (default: "1")
195
+ - `TEXTARENA_KW_*` - Pass additional kwargs to TextArena. Values are read as JSON, so numbers and booleans keep their type (e.g., `TEXTARENA_KW_CLUES=65` for Sudoku, `TEXTARENA_KW_difficulty=hard`)
196
 
197
  ## Development & Testing
198
 
envs/textarena_env/pyproject.toml CHANGED
@@ -15,7 +15,7 @@ description = "TextArena environment for OpenEnv"
15
  requires-python = ">=3.10"
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.10"
16
  dependencies = [
17
  # Core OpenEnv dependencies (required for server functionality)
18
+ "openenv @ git+https://github.com/openenv/OpenEnv.git@v0.11.0",
19
  "fastapi>=0.115.0",
20
  "pydantic>=2.0.0",
21
  "uvicorn>=0.24.0",
envs/textarena_env/server/app.py CHANGED
@@ -9,8 +9,10 @@
9
  from __future__ import annotations
10
 
11
  import inspect
 
12
  import logging
13
  import os
 
14
 
15
  from openenv.core.env_server.http_server import create_app
16
 
@@ -31,14 +33,21 @@ except ImportError:
31
  from .gradio_ui import build_textarena_gradio_app
32
 
33
 
34
- def _parse_env_kwargs(prefix: str = "TEXTARENA_KW_") -> dict[str, str]:
35
- """Collect arbitrary environment kwargs from the process environment."""
36
 
37
- env_kwargs: dict[str, str] = {}
 
 
 
 
38
  for key, value in os.environ.items():
39
  if key.startswith(prefix):
40
  env_key = key[len(prefix) :].lower()
41
- env_kwargs[env_key] = value
 
 
 
42
  return env_kwargs
43
 
44
 
 
9
  from __future__ import annotations
10
 
11
  import inspect
12
+ import json
13
  import logging
14
  import os
15
+ from typing import Any
16
 
17
  from openenv.core.env_server.http_server import create_app
18
 
 
33
  from .gradio_ui import build_textarena_gradio_app
34
 
35
 
36
+ def _parse_env_kwargs(prefix: str = "TEXTARENA_KW_") -> dict[str, Any]:
37
+ """Collect arbitrary environment kwargs from the process environment.
38
 
39
+ Values are read as JSON, so `TEXTARENA_KW_CLUES=65` passes the integer 65. Values that are not JSON, like
40
+ `TEXTARENA_KW_DIFFICULTY=hard`, are passed as strings.
41
+ """
42
+
43
+ env_kwargs: dict[str, Any] = {}
44
  for key, value in os.environ.items():
45
  if key.startswith(prefix):
46
  env_key = key[len(prefix) :].lower()
47
+ try:
48
+ env_kwargs[env_key] = json.loads(value)
49
+ except json.JSONDecodeError:
50
+ env_kwargs[env_key] = value
51
  return env_kwargs
52
 
53
 
envs/textarena_env/server/environment.py CHANGED
@@ -9,11 +9,14 @@
9
  from __future__ import annotations
10
 
11
  import os
 
12
  import re
13
  import subprocess
14
  import sys
 
15
  import urllib.request
16
- from typing import Any, Dict, Iterable, List, Optional
 
17
  from uuid import uuid4
18
 
19
  from openenv.core.env_server.interfaces import Environment
@@ -42,6 +45,9 @@ _TEXTARENA_MODULE: Any | None = None
42
  _TEXTARENA_IMPORT_ERROR: Exception | None = None
43
  _NLTK_DOWNLOADED: bool = False
44
 
 
 
 
45
  # TextArena's Wordle feedback, e.g. "You submitted [crane].\nFeedback:\nC R A N E\nG X Y X G".
46
  _WORDLE_FEEDBACK = re.compile(
47
  r"You submitted \[(\w+)\]\.\nFeedback:\n[^\n]*\n([GYX ]+)"
@@ -167,7 +173,8 @@ class TextArenaEnvironment(Environment):
167
  self.max_turns = max_turns
168
  self._env_kwargs = env_kwargs or {}
169
 
170
- self._ta_env = ta.make(env_id=env_id, **self._env_kwargs)
 
171
 
172
  self._state = TextArenaState(
173
  env_id=env_id,
@@ -181,7 +188,8 @@ class TextArenaEnvironment(Environment):
181
  # Initialize environment state - TextArena envs require reset() to be called
182
  # before step() can be used, as the internal state object isn't created until reset.
183
  # This ensures the environment is always in a valid state after construction.
184
- self._ta_env.reset(num_players=self.num_players)
 
185
 
186
  # ------------------------------------------------------------------
187
  # Environment interface
@@ -204,7 +212,7 @@ class TextArenaEnvironment(Environment):
204
  if hasattr(env, "full_observations"):
205
  env.full_observations = {}
206
 
207
- self._ta_env.reset(num_players=self.num_players)
208
 
209
  for provider in self._reward_providers:
210
  provider.reset()
@@ -227,7 +235,8 @@ class TextArenaEnvironment(Environment):
227
  if not isinstance(action, TextArenaAction):
228
  raise TypeError(f"Expected TextArenaAction, received {type(action)!r}")
229
 
230
- done, info = self._ta_env.step(action.message)
 
231
 
232
  self._state.step_count += 1
233
  self._state.turn = getattr(self._ta_env.state, "turn", self._state.turn + 1)
@@ -297,6 +306,50 @@ class TextArenaEnvironment(Environment):
297
  # ------------------------------------------------------------------
298
  # Helpers
299
  # ------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  def _build_observation(self) -> TextArenaObservation:
301
  player_id, messages = self._ta_env.get_observation()
302
 
 
9
  from __future__ import annotations
10
 
11
  import os
12
+ import random
13
  import re
14
  import subprocess
15
  import sys
16
+ import threading
17
  import urllib.request
18
+ from contextlib import contextmanager
19
+ from typing import Any, Dict, Iterable, Iterator, List, Optional
20
  from uuid import uuid4
21
 
22
  from openenv.core.env_server.interfaces import Environment
 
45
  _TEXTARENA_IMPORT_ERROR: Exception | None = None
46
  _NLTK_DOWNLOADED: bool = False
47
 
48
+ # Serialize TextArena RNG access; seeded sessions retain their own stream.
49
+ _RNG_LOCK = threading.Lock()
50
+
51
  # TextArena's Wordle feedback, e.g. "You submitted [crane].\nFeedback:\nC R A N E\nG X Y X G".
52
  _WORDLE_FEEDBACK = re.compile(
53
  r"You submitted \[(\w+)\]\.\nFeedback:\n[^\n]*\n([GYX ]+)"
 
173
  self.max_turns = max_turns
174
  self._env_kwargs = env_kwargs or {}
175
 
176
+ with _RNG_LOCK:
177
+ self._ta_env = ta.make(env_id=env_id, **self._env_kwargs)
178
 
179
  self._state = TextArenaState(
180
  env_id=env_id,
 
188
  # Initialize environment state - TextArena envs require reset() to be called
189
  # before step() can be used, as the internal state object isn't created until reset.
190
  # This ensures the environment is always in a valid state after construction.
191
+ self._rng_state: Optional[tuple] = None
192
+ self._reset_ta_env()
193
 
194
  # ------------------------------------------------------------------
195
  # Environment interface
 
212
  if hasattr(env, "full_observations"):
213
  env.full_observations = {}
214
 
215
+ self._reset_ta_env(seed)
216
 
217
  for provider in self._reward_providers:
218
  provider.reset()
 
235
  if not isinstance(action, TextArenaAction):
236
  raise TypeError(f"Expected TextArenaAction, received {type(action)!r}")
237
 
238
+ with self._session_rng():
239
+ done, info = self._ta_env.step(action.message)
240
 
241
  self._state.step_count += 1
242
  self._state.turn = getattr(self._ta_env.state, "turn", self._state.turn + 1)
 
306
  # ------------------------------------------------------------------
307
  # Helpers
308
  # ------------------------------------------------------------------
309
+ def _reset_ta_env(self, seed: Optional[int] = None) -> None:
310
+ """Reset the wrapped game without disturbing other sessions.
311
+
312
+ TextArena implements ``reset(seed=...)`` by calling ``random.seed`` on the
313
+ process-global RNG and then drawing the episode from it. The lock keeps
314
+ seed and draw atomic across concurrent sessions. A seeded reset keeps the
315
+ RNG state it produced on the session, so later ``step`` calls continue the
316
+ same stream, and restores the prior process state so a seeded reset does
317
+ not make unseeded sessions predictable.
318
+ """
319
+ with _RNG_LOCK:
320
+ self._rng_state = None
321
+ if seed is None:
322
+ self._ta_env.reset(num_players=self.num_players)
323
+ return
324
+ process_state = random.getstate()
325
+ try:
326
+ self._ta_env.reset(num_players=self.num_players, seed=seed)
327
+ self._rng_state = random.getstate()
328
+ finally:
329
+ random.setstate(process_state)
330
+
331
+ @contextmanager
332
+ def _session_rng(self) -> Iterator[None]:
333
+ """Run a wrapped call under this session's RNG stream.
334
+
335
+ Unseeded sessions draw from the process-global RNG as before. A seeded
336
+ session swaps its saved state in, runs the call, saves the advanced
337
+ state back, and restores the process state on exit, including when the
338
+ call raises, so equal seeds and equal actions give equal trajectories
339
+ regardless of what other sessions do in between.
340
+ """
341
+ with _RNG_LOCK:
342
+ if self._rng_state is None:
343
+ yield
344
+ return
345
+ process_state = random.getstate()
346
+ random.setstate(self._rng_state)
347
+ try:
348
+ yield
349
+ finally:
350
+ self._rng_state = random.getstate()
351
+ random.setstate(process_state)
352
+
353
  def _build_observation(self) -> TextArenaObservation:
354
  player_id, messages = self._ta_env.get_observation()
355
 
pyproject.toml CHANGED
@@ -15,7 +15,7 @@ description = "TextArena environment for OpenEnv"
15
  requires-python = ">=3.10"
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.10"
16
  dependencies = [
17
  # Core OpenEnv dependencies (required for server functionality)
18
+ "openenv @ git+https://github.com/openenv/OpenEnv.git@v0.11.0",
19
  "fastapi>=0.115.0",
20
  "pydantic>=2.0.0",
21
  "uvicorn>=0.24.0",
server/app.py CHANGED
@@ -9,8 +9,10 @@
9
  from __future__ import annotations
10
 
11
  import inspect
 
12
  import logging
13
  import os
 
14
 
15
  from openenv.core.env_server.http_server import create_app
16
 
@@ -31,14 +33,21 @@ except ImportError:
31
  from .gradio_ui import build_textarena_gradio_app
32
 
33
 
34
- def _parse_env_kwargs(prefix: str = "TEXTARENA_KW_") -> dict[str, str]:
35
- """Collect arbitrary environment kwargs from the process environment."""
36
 
37
- env_kwargs: dict[str, str] = {}
 
 
 
 
38
  for key, value in os.environ.items():
39
  if key.startswith(prefix):
40
  env_key = key[len(prefix) :].lower()
41
- env_kwargs[env_key] = value
 
 
 
42
  return env_kwargs
43
 
44
 
 
9
  from __future__ import annotations
10
 
11
  import inspect
12
+ import json
13
  import logging
14
  import os
15
+ from typing import Any
16
 
17
  from openenv.core.env_server.http_server import create_app
18
 
 
33
  from .gradio_ui import build_textarena_gradio_app
34
 
35
 
36
+ def _parse_env_kwargs(prefix: str = "TEXTARENA_KW_") -> dict[str, Any]:
37
+ """Collect arbitrary environment kwargs from the process environment.
38
 
39
+ Values are read as JSON, so `TEXTARENA_KW_CLUES=65` passes the integer 65. Values that are not JSON, like
40
+ `TEXTARENA_KW_DIFFICULTY=hard`, are passed as strings.
41
+ """
42
+
43
+ env_kwargs: dict[str, Any] = {}
44
  for key, value in os.environ.items():
45
  if key.startswith(prefix):
46
  env_key = key[len(prefix) :].lower()
47
+ try:
48
+ env_kwargs[env_key] = json.loads(value)
49
+ except json.JSONDecodeError:
50
+ env_kwargs[env_key] = value
51
  return env_kwargs
52
 
53
 
server/environment.py CHANGED
@@ -9,11 +9,14 @@
9
  from __future__ import annotations
10
 
11
  import os
 
12
  import re
13
  import subprocess
14
  import sys
 
15
  import urllib.request
16
- from typing import Any, Dict, Iterable, List, Optional
 
17
  from uuid import uuid4
18
 
19
  from openenv.core.env_server.interfaces import Environment
@@ -42,6 +45,9 @@ _TEXTARENA_MODULE: Any | None = None
42
  _TEXTARENA_IMPORT_ERROR: Exception | None = None
43
  _NLTK_DOWNLOADED: bool = False
44
 
 
 
 
45
  # TextArena's Wordle feedback, e.g. "You submitted [crane].\nFeedback:\nC R A N E\nG X Y X G".
46
  _WORDLE_FEEDBACK = re.compile(
47
  r"You submitted \[(\w+)\]\.\nFeedback:\n[^\n]*\n([GYX ]+)"
@@ -167,7 +173,8 @@ class TextArenaEnvironment(Environment):
167
  self.max_turns = max_turns
168
  self._env_kwargs = env_kwargs or {}
169
 
170
- self._ta_env = ta.make(env_id=env_id, **self._env_kwargs)
 
171
 
172
  self._state = TextArenaState(
173
  env_id=env_id,
@@ -181,7 +188,8 @@ class TextArenaEnvironment(Environment):
181
  # Initialize environment state - TextArena envs require reset() to be called
182
  # before step() can be used, as the internal state object isn't created until reset.
183
  # This ensures the environment is always in a valid state after construction.
184
- self._ta_env.reset(num_players=self.num_players)
 
185
 
186
  # ------------------------------------------------------------------
187
  # Environment interface
@@ -204,7 +212,7 @@ class TextArenaEnvironment(Environment):
204
  if hasattr(env, "full_observations"):
205
  env.full_observations = {}
206
 
207
- self._ta_env.reset(num_players=self.num_players)
208
 
209
  for provider in self._reward_providers:
210
  provider.reset()
@@ -227,7 +235,8 @@ class TextArenaEnvironment(Environment):
227
  if not isinstance(action, TextArenaAction):
228
  raise TypeError(f"Expected TextArenaAction, received {type(action)!r}")
229
 
230
- done, info = self._ta_env.step(action.message)
 
231
 
232
  self._state.step_count += 1
233
  self._state.turn = getattr(self._ta_env.state, "turn", self._state.turn + 1)
@@ -297,6 +306,50 @@ class TextArenaEnvironment(Environment):
297
  # ------------------------------------------------------------------
298
  # Helpers
299
  # ------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  def _build_observation(self) -> TextArenaObservation:
301
  player_id, messages = self._ta_env.get_observation()
302
 
 
9
  from __future__ import annotations
10
 
11
  import os
12
+ import random
13
  import re
14
  import subprocess
15
  import sys
16
+ import threading
17
  import urllib.request
18
+ from contextlib import contextmanager
19
+ from typing import Any, Dict, Iterable, Iterator, List, Optional
20
  from uuid import uuid4
21
 
22
  from openenv.core.env_server.interfaces import Environment
 
45
  _TEXTARENA_IMPORT_ERROR: Exception | None = None
46
  _NLTK_DOWNLOADED: bool = False
47
 
48
+ # Serialize TextArena RNG access; seeded sessions retain their own stream.
49
+ _RNG_LOCK = threading.Lock()
50
+
51
  # TextArena's Wordle feedback, e.g. "You submitted [crane].\nFeedback:\nC R A N E\nG X Y X G".
52
  _WORDLE_FEEDBACK = re.compile(
53
  r"You submitted \[(\w+)\]\.\nFeedback:\n[^\n]*\n([GYX ]+)"
 
173
  self.max_turns = max_turns
174
  self._env_kwargs = env_kwargs or {}
175
 
176
+ with _RNG_LOCK:
177
+ self._ta_env = ta.make(env_id=env_id, **self._env_kwargs)
178
 
179
  self._state = TextArenaState(
180
  env_id=env_id,
 
188
  # Initialize environment state - TextArena envs require reset() to be called
189
  # before step() can be used, as the internal state object isn't created until reset.
190
  # This ensures the environment is always in a valid state after construction.
191
+ self._rng_state: Optional[tuple] = None
192
+ self._reset_ta_env()
193
 
194
  # ------------------------------------------------------------------
195
  # Environment interface
 
212
  if hasattr(env, "full_observations"):
213
  env.full_observations = {}
214
 
215
+ self._reset_ta_env(seed)
216
 
217
  for provider in self._reward_providers:
218
  provider.reset()
 
235
  if not isinstance(action, TextArenaAction):
236
  raise TypeError(f"Expected TextArenaAction, received {type(action)!r}")
237
 
238
+ with self._session_rng():
239
+ done, info = self._ta_env.step(action.message)
240
 
241
  self._state.step_count += 1
242
  self._state.turn = getattr(self._ta_env.state, "turn", self._state.turn + 1)
 
306
  # ------------------------------------------------------------------
307
  # Helpers
308
  # ------------------------------------------------------------------
309
+ def _reset_ta_env(self, seed: Optional[int] = None) -> None:
310
+ """Reset the wrapped game without disturbing other sessions.
311
+
312
+ TextArena implements ``reset(seed=...)`` by calling ``random.seed`` on the
313
+ process-global RNG and then drawing the episode from it. The lock keeps
314
+ seed and draw atomic across concurrent sessions. A seeded reset keeps the
315
+ RNG state it produced on the session, so later ``step`` calls continue the
316
+ same stream, and restores the prior process state so a seeded reset does
317
+ not make unseeded sessions predictable.
318
+ """
319
+ with _RNG_LOCK:
320
+ self._rng_state = None
321
+ if seed is None:
322
+ self._ta_env.reset(num_players=self.num_players)
323
+ return
324
+ process_state = random.getstate()
325
+ try:
326
+ self._ta_env.reset(num_players=self.num_players, seed=seed)
327
+ self._rng_state = random.getstate()
328
+ finally:
329
+ random.setstate(process_state)
330
+
331
+ @contextmanager
332
+ def _session_rng(self) -> Iterator[None]:
333
+ """Run a wrapped call under this session's RNG stream.
334
+
335
+ Unseeded sessions draw from the process-global RNG as before. A seeded
336
+ session swaps its saved state in, runs the call, saves the advanced
337
+ state back, and restores the process state on exit, including when the
338
+ call raises, so equal seeds and equal actions give equal trajectories
339
+ regardless of what other sessions do in between.
340
+ """
341
+ with _RNG_LOCK:
342
+ if self._rng_state is None:
343
+ yield
344
+ return
345
+ process_state = random.getstate()
346
+ random.setstate(self._rng_state)
347
+ try:
348
+ yield
349
+ finally:
350
+ self._rng_state = random.getstate()
351
+ random.setstate(process_state)
352
+
353
  def _build_observation(self) -> TextArenaObservation:
354
  player_id, messages = self._ta_env.get_observation()
355
 
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/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/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/providers.py CHANGED
@@ -10,7 +10,7 @@ This module provides a pluggable architecture for different container providers
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
 
@@ -21,7 +21,9 @@ class ContainerProvider(ABC):
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 +177,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 +188,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()
@@ -207,6 +213,20 @@ class LocalDockerProvider(ContainerProvider):
207
  for key, value in env_vars.items():
208
  cmd.extend(["-e", f"{key}={value}"])
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  # Add image
211
  cmd.append(image)
212
 
@@ -644,19 +664,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.
 
10
  from __future__ import annotations
11
 
12
  from abc import ABC, abstractmethod
13
+ from typing import Any, Dict, Mapping, Optional, Sequence, TypeVar
14
 
15
  _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider")
16
 
 
21
 
22
  Providers implement this interface to support different container platforms:
23
  - LocalDockerProvider: Runs containers on local Docker daemon
24
+ - DockerSwarmProvider: Runs containers as a Docker Swarm service
25
+ - KubernetesProvider: optional ``openenv[kubernetes]`` extra
26
+ (``kubernetes_provider.py``)
27
  - FargateProvider: Runs containers on AWS Fargate
28
  - CloudRunProvider: Runs containers on Google Cloud Run
29
 
 
177
  Port to expose. If `None`, finds an available port.
178
  env_vars (`dict`, *optional*):
179
  Environment variables for the container.
180
+ volumes (`dict`, *optional*):
181
+ Mapping of host paths or volume names to mount configuration.
182
+ Each configuration must contain a `bind` container path and may
183
+ contain a `mode` such as `"ro"` or `"rw"`.
184
 
185
  Returns:
186
  `str`: Base URL to connect to the container.
 
188
  import subprocess
189
  import time
190
 
191
+ volumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes")
192
+
193
  # Find available port if not specified
194
  if port is None:
195
  port = self._find_available_port()
 
213
  for key, value in env_vars.items():
214
  cmd.extend(["-e", f"{key}={value}"])
215
 
216
+ # Add volume mounts before the image name.
217
+ if volumes:
218
+ for source, config in volumes.items():
219
+ bind = config.get("bind")
220
+ if not bind:
221
+ raise ValueError(
222
+ f"Volume config for {source!r} must include a non-empty 'bind'"
223
+ )
224
+ mode = config.get("mode")
225
+ volume_spec = f"{source}:{bind}"
226
+ if mode:
227
+ volume_spec = f"{volume_spec}:{mode}"
228
+ cmd.extend(["--volume", volume_spec])
229
+
230
  # Add image
231
  cmd.append(image)
232
 
 
664
  return f"{clean_image}-swarm-{timestamp}"
665
 
666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667
  class RuntimeProvider(ABC):
668
  """
669
  Abstract base class for runtime providers that are not container providers.
src/core/env_server/http_server.py CHANGED
@@ -56,6 +56,7 @@ from .mcp_types import (
56
  ListToolsAction,
57
  ListToolsObservation,
58
  McpMethod,
 
59
  WSMCPMessage,
60
  WSMCPResponse,
61
  )
@@ -181,6 +182,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 +210,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 +259,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,6 +267,7 @@ 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()
@@ -280,6 +288,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 +379,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
 
@@ -404,6 +415,13 @@ class HTTPEnvServer:
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:
@@ -441,6 +459,8 @@ class HTTPEnvServer:
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,
@@ -465,6 +485,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,7 +554,13 @@ 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:
@@ -544,6 +571,8 @@ class HTTPEnvServer:
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
@@ -569,12 +598,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 +910,24 @@ 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 +1028,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 +1068,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 +1096,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 +1150,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 +1159,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 +1177,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 +1203,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:
@@ -1221,6 +1303,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(
@@ -1414,7 +1522,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 +1769,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 +1799,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 +1816,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)
@@ -1761,10 +1875,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 +1899,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:
@@ -2003,6 +2122,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 +2167,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 +2197,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 +2216,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 +2233,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 +2259,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 +2289,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 +2319,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 +2328,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,6 +2344,7 @@ 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:
 
56
  ListToolsAction,
57
  ListToolsObservation,
58
  McpMethod,
59
+ ToolErrorType,
60
  WSMCPMessage,
61
  WSMCPResponse,
62
  )
 
182
  state_cls: Type[State] = State,
183
  *,
184
  reset_observation_cls: Optional[Type[Observation]] = None,
185
+ reset_cls: Type[ResetRequest] = ResetRequest,
186
  ):
187
  """
188
  Initialize HTTP server wrapper.
 
210
  The `State` subclass this environment reports. Used for the `/state`
211
  response model and the `state` entry of `/schema`, so that fields
212
  declared by the subclass are published and serialized.
213
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
214
+ The `ResetRequest` subclass describing this environment's reset parameters.
215
+ Published as the `reset` entry of `/schema`. It is not used to validate
216
+ reset requests.
217
 
218
  Raises:
219
  `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided.
 
259
  self.observation_cls = observation_cls
260
  self.reset_observation_cls = reset_observation_cls or observation_cls
261
  self.state_cls = state_cls
262
+ self.reset_cls = reset_cls
263
  self.env_name = env_name or self._default_env_name()
264
 
265
  # Session management for WebSocket connections
 
267
  self._session_executors: Dict[str, ThreadPoolExecutor] = {}
268
  self._session_stacks: Dict[str, AsyncExitStack] = {}
269
  self._session_info: Dict[str, SessionInfo] = {}
270
+ self._session_modes: Dict[str, Optional[str]] = {}
271
  self._session_websocket_attachments: set[str] = set()
272
  self._session_pending_closes: set[str] = set()
273
  self._session_lock = asyncio.Lock()
 
288
  self._concurrency_config.session_timeout
289
  )
290
  self._reaper_task: Optional[asyncio.Task[None]] = None
291
+ self._reaper_stop_event = asyncio.Event()
292
 
293
  def _default_env_name(self) -> str:
294
  factory = self._env_factory
 
379
 
380
  return valid_kwargs
381
 
382
+ async def _create_session(
383
+ self, mode: Optional[str | ServerMode] = None
384
+ ) -> tuple[str, Environment]:
385
  """
386
  Create a new WebSocket session with its own environment instance.
387
 
 
415
  # Create environment in the executor thread (outside lock)
416
  loop = asyncio.get_event_loop()
417
  env = await loop.run_in_executor(executor, self._env_factory)
418
+ mode_val = (
419
+ mode.value
420
+ if isinstance(mode, ServerMode)
421
+ else (str(mode) if mode is not None else None)
422
+ )
423
+ if mode_val is not None and hasattr(env, "set_mode"):
424
+ env.set_mode(mode_val)
425
  except Exception as e:
426
  async with self._session_lock:
427
  if executor is not self._shared_session_executor:
 
459
  async with self._session_lock:
460
  self._sessions[session_id] = env
461
  self._session_stacks[session_id] = stack
462
+ if mode is not None:
463
+ self._session_modes[session_id] = mode_val
464
  now = time.time()
465
  self._session_info[session_id] = SessionInfo(
466
  session_id=session_id,
 
485
  executor = self._session_executors.pop(session_id, None)
486
  stack = self._session_stacks.pop(session_id, None)
487
  self._session_info.pop(session_id, None)
488
+ self._session_modes.pop(session_id, None)
489
  self._session_websocket_attachments.discard(session_id)
490
  self._session_pending_closes.discard(session_id)
491
 
 
554
  interval = max(timeout / 4, 5.0) # check frequently enough
555
  while True:
556
  try:
557
+ try:
558
+ await asyncio.wait_for(
559
+ self._reaper_stop_event.wait(), timeout=interval
560
+ )
561
+ return
562
+ except asyncio.TimeoutError:
563
+ pass
564
  now = time.time()
565
  stale_ids: list[str] = []
566
  async with self._session_lock:
 
571
  ):
572
  stale_ids.append(sid)
573
  for sid in stale_ids:
574
+ if self._reaper_stop_event.is_set():
575
+ return
576
  # Re-check under lock: activity may have arrived since
577
  # the snapshot was taken, making this session active again.
578
  # Refresh `now` so slow _destroy_session calls don't cause
 
598
  def _start_reaper(self) -> None:
599
  """Start the idle-session reaper if a timeout is configured."""
600
  if self._session_idle_timeout_s is not None and self._reaper_task is None:
601
+ self._reaper_stop_event.clear()
602
  self._reaper_task = asyncio.create_task(self._reap_idle_sessions())
603
 
604
+ async def _stop_reaper(self) -> None:
605
+ """Stop the reaper after any in-progress session cleanup finishes."""
606
  if self._reaper_task is not None:
607
+ self._reaper_stop_event.set()
608
+ await self._reaper_task
609
  self._reaper_task = None
610
 
611
  def get_session_info(self, session_id: str) -> Optional[SessionInfo]:
 
910
  f"Invalid mode: '{mode}'. Must be one of: {valid_modes}"
911
  )
912
 
913
+ # Wire up session lifecycle via app events
914
  server_ref = self
915
 
916
  async def _start_session_reaper() -> None:
917
  server_ref._start_reaper()
918
 
919
+ async def _shutdown_sessions() -> None:
920
+ await server_ref._stop_reaper()
921
+ async with server_ref._session_lock:
922
+ session_ids = list(server_ref._sessions)
923
+ for session_id in session_ids:
924
+ await server_ref._destroy_session(session_id)
925
  if server_ref._shared_session_executor is not None:
926
  server_ref._shared_session_executor.shutdown(wait=True)
927
 
928
  if not getattr(app.router, "_openenv_reaper_registered", False):
929
  app.router.on_startup.append(_start_session_reaper)
930
+ app.router.on_shutdown.append(_shutdown_sessions)
931
  app.router._openenv_reaper_registered = True # type: ignore[attr-defined]
932
 
933
  # Helper function to handle reset endpoint
 
1028
  request_id=request_id,
1029
  )
1030
  try:
1031
+ created_session_id, _ = await self._create_session(mode=mode)
1032
  except SessionCapacityError as e:
1033
  return JsonRpcResponse.error_response(
1034
  JsonRpcErrorCode.SERVER_ERROR,
 
1068
  )
1069
 
1070
  async with self._session_lock:
1071
+ session_mode = self._session_modes.get(target_session_id)
1072
+ if (
1073
+ (
1074
+ target_session_id in self._sessions
1075
+ or target_session_id in self._session_websocket_attachments
1076
+ )
1077
+ and session_mode is not None
1078
+ and session_mode != mode.value
1079
+ ):
1080
+ return JsonRpcResponse.error_response(
1081
+ JsonRpcErrorCode.INVALID_PARAMS,
1082
+ f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",
1083
+ request_id=request_id,
1084
+ )
1085
+
1086
  if target_session_id in self._session_websocket_attachments:
1087
  env = _MISSING
1088
  attached = True
 
1096
  executor = self._session_executors.pop(target_session_id, None)
1097
  stack = self._session_stacks.pop(target_session_id, None)
1098
  self._session_info.pop(target_session_id, None)
1099
+ self._session_modes.pop(target_session_id, None)
1100
  elif not attached:
1101
  executor = None
1102
  stack = None
 
1150
  elif requested_session_id:
1151
  async with self._session_lock:
1152
  _env = self._sessions.get(requested_session_id, _MISSING)
1153
+ session_mode = self._session_modes.get(requested_session_id)
1154
 
1155
  if _env is _MISSING:
1156
  return JsonRpcResponse.error_response(
 
1159
  request_id=request_id,
1160
  )
1161
 
1162
+ if session_mode is not None and session_mode != mode.value:
1163
+ return JsonRpcResponse.error_response(
1164
+ JsonRpcErrorCode.INVALID_PARAMS,
1165
+ f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",
1166
+ request_id=request_id,
1167
+ )
1168
+
1169
  if _env is None:
1170
  return JsonRpcResponse.error_response(
1171
  JsonRpcErrorCode.INVALID_REQUEST,
 
1177
  managed_session_id = requested_session_id
1178
  else:
1179
  _env = self._env_factory()
1180
+ if hasattr(_env, "set_mode"):
1181
+ _env.set_mode(mode.value)
1182
  should_close = True
1183
  try:
1184
  mcp_client = getattr(_env, "mcp_client", None)
 
1203
  }
1204
 
1205
  if method == McpMethod.TOOLS_LIST:
1206
+ if hasattr(_env, "_async_handle_list_tools"):
1207
+ obs = await _env._async_handle_list_tools()
1208
+ if obs.metadata and "error" in obs.metadata:
1209
+ return JsonRpcResponse.error_response(
1210
+ JsonRpcErrorCode.INTERNAL_ERROR,
1211
+ obs.metadata["error"],
1212
+ request_id=request_id,
1213
+ )
1214
+ tools = [
1215
+ {
1216
+ "name": t.name,
1217
+ "description": t.description or "",
1218
+ "inputSchema": t.input_schema,
1219
+ }
1220
+ for t in obs.tools
1221
+ ]
1222
+ return JsonRpcResponse.success(
1223
+ result={"tools": tools},
1224
+ request_id=request_id,
1225
+ )
1226
+
1227
  # Check if environment is MCP-enabled
1228
  if mcp_client is None and mcp_server is None:
1229
  if supports_mcp_style_actions:
 
1303
  request_id=request_id,
1304
  )
1305
 
1306
+ if hasattr(_env, "_mode_tools") and any(
1307
+ m is not None for m in _env._mode_tools.get(tool_name, {})
1308
+ ):
1309
+ obs = await _env._async_handle_call_tool(
1310
+ CallToolAction(tool_name=tool_name, arguments=arguments)
1311
+ )
1312
+ if obs.error:
1313
+ err_code = (
1314
+ JsonRpcErrorCode.INVALID_PARAMS
1315
+ if obs.error.error_type
1316
+ in (
1317
+ ToolErrorType.INVALID_ARGS,
1318
+ ToolErrorType.TOOL_NOT_FOUND,
1319
+ )
1320
+ else JsonRpcErrorCode.INTERNAL_ERROR
1321
+ )
1322
+ return JsonRpcResponse.error_response(
1323
+ err_code,
1324
+ obs.error.message,
1325
+ request_id=request_id,
1326
+ )
1327
+ return JsonRpcResponse.success(
1328
+ result=_make_json_serializable(obs.result),
1329
+ request_id=request_id,
1330
+ )
1331
+
1332
  if mcp_client is None and mcp_server is None:
1333
  if supports_mcp_style_actions:
1334
  observation = await call_mcp_style_step(
 
1522
 
1523
  try:
1524
  # Create session with dedicated environment
1525
+ session_id, session_env = await self._create_session(mode=mode)
1526
  if session_env is None:
1527
  raise RuntimeError(
1528
  "Session environment not initialized for MCP websocket"
 
1769
  tags=["Schema"],
1770
  summary="Get all JSON schemas",
1771
  description="""
1772
+ Get JSON schemas for actions, observations, state, and reset parameters in a single response.
1773
 
1774
  Returns a combined schema object containing:
1775
  - **action**: JSON schema for actions accepted by this environment
1776
  - **observation**: JSON schema for observations returned by step
1777
  - **reset_observation**: JSON schema for observations returned by reset
1778
  - **state**: JSON schema for environment state objects
1779
+ - **reset**: JSON schema for reset parameters accepted by this environment
1780
 
1781
  This is more efficient than calling individual schema endpoints and provides
1782
  all schema information needed to interact with the environment.
 
1799
  "type": "object",
1800
  "properties": {"step_count": {"type": "integer"}},
1801
  },
1802
+ "reset": {
1803
+ "type": "object",
1804
+ "properties": {"seed": {"type": "integer"}},
1805
+ },
1806
  }
1807
  }
1808
  },
 
1816
  observation=self.observation_cls.model_json_schema(),
1817
  reset_observation=self.reset_observation_cls.model_json_schema(),
1818
  state=self.state_cls.model_json_schema(),
1819
+ reset=self.reset_cls.model_json_schema(),
1820
  )
1821
 
1822
  # Register MCP endpoint for production mode (direct MCP access)
 
1875
  attached_env = self._sessions.get(
1876
  requested_session_id, _MISSING
1877
  )
1878
+ session_mode = self._session_modes.get(requested_session_id)
1879
  if attached_env is _MISSING:
1880
  raise RuntimeError(
1881
  f"Unknown session_id: {requested_session_id}"
1882
  )
1883
+ if session_mode is not None and session_mode != mode.value:
1884
+ raise RuntimeError(
1885
+ f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'"
1886
+ )
1887
  if attached_env is None:
1888
  raise RuntimeError(
1889
  f"Session {requested_session_id} is still initializing"
 
1899
  attached_session = True
1900
  self._update_session_activity(session_id)
1901
  else:
1902
+ session_id, session_env = await self._create_session(mode=mode)
1903
  owns_session = True
1904
 
1905
  if session_env is None:
 
2122
  *,
2123
  mode: Optional[ServerMode | str] = None,
2124
  reset_observation_cls: Optional[Type[Observation]] = None,
2125
+ reset_cls: Type[ResetRequest] = ResetRequest,
2126
  ) -> FastAPI:
2127
  """
2128
  Create a FastAPI application with or without web interface.
 
2167
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2168
  The `State` subclass this environment reports, used for the `/state`
2169
  response model and the `state` entry of `/schema`.
2170
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
2171
+ The `ResetRequest` subclass describing this environment's reset parameters,
2172
+ published as the `reset` entry of `/schema`. Not used for validation.
2173
  mode (`ServerMode` or `str`, *optional*):
2174
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2175
  environment variable, defaulting to simulation.
 
2197
  max_concurrent_envs,
2198
  concurrency_config,
2199
  state_cls=state_cls,
2200
+ reset_cls=reset_cls,
2201
  reset_observation_cls=reset_observation_cls,
2202
  gradio_builder=gradio_builder,
2203
  custom_tab_name=custom_tab_name,
 
2216
  concurrency_config,
2217
  env_name=env_name,
2218
  state_cls=state_cls,
2219
+ reset_cls=reset_cls,
2220
  reset_observation_cls=reset_observation_cls,
2221
  mode=mode,
2222
  )
 
2233
  *,
2234
  mode: Optional[ServerMode | str] = None,
2235
  reset_observation_cls: Optional[Type[Observation]] = None,
2236
+ reset_cls: Type[ResetRequest] = ResetRequest,
2237
  ) -> FastAPI:
2238
  """
2239
  Create a FastAPI application with comprehensive documentation.
 
2259
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2260
  The `State` subclass this environment reports, used for the `/state`
2261
  response model and the `state` entry of `/schema`.
2262
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
2263
+ The `ResetRequest` subclass describing this environment's reset parameters,
2264
+ published as the `reset` entry of `/schema`. Not used for validation.
2265
  mode (`ServerMode` or `str`, *optional*):
2266
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2267
  environment variable, defaulting to simulation.
 
2289
  * **Environment Reset**: Initialize or restart episodes
2290
  * **Action Execution**: Send actions and receive observations
2291
  * **State Inspection**: Query current environment state
2292
+ * **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters
2293
 
2294
  ## Workflow
2295
 
 
2319
  },
2320
  {
2321
  "name": "Schema",
2322
+ "description": "JSON Schema endpoints for actions, observations, state, and reset parameters",
2323
  },
2324
  {"name": "Health", "description": "Service health and status checks"},
2325
  ],
 
2328
  openapi_url="/openapi.json",
2329
  contact={
2330
  "name": "OpenEnv Team",
2331
+ "url": "https://github.com/openenv/OpenEnv",
2332
  },
2333
  license_info={
2334
  "name": "BSD-3-Clause",
2335
+ "url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE",
2336
  },
2337
  )
2338
 
 
2344
  concurrency_config=concurrency_config,
2345
  env_name=env_name,
2346
  state_cls=state_cls,
2347
+ reset_cls=reset_cls,
2348
  reset_observation_cls=reset_observation_cls,
2349
  )
2350
  if mode is None:
src/core/env_server/interfaces.py CHANGED
@@ -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*):
 
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
@@ -195,6 +195,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."""
@@ -496,7 +501,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 +525,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)
 
195
 
196
  # Track tool schemas for list_tools: {tool_name: {mode: schema}}
197
  self._mode_tool_schemas = defaultdict(dict)
198
+ self._mode: Optional[str] = None
199
+
200
+ def set_mode(self, mode: Optional[str]) -> None:
201
+ """Set the active mode ('production' or 'simulation') for mode-aware tools."""
202
+ self._mode = mode
203
 
204
  def _require_mcp_client(self) -> Any:
205
  """Return MCP client or raise if environment has been closed."""
 
501
  tools_result = await self._async_list_tools()
502
  tools = []
503
  for tool in tools_result:
504
+ mode_schemas = self._mode_tool_schemas.get(tool.name, {})
505
+ if _schema_for_mode(mode_schemas, current_mode) is None:
506
  tools.append(_tool_from_server_tool(tool))
507
  for mode_schemas in self._mode_tool_schemas.values():
508
  schema = _schema_for_mode(mode_schemas, current_mode)
 
525
  tool_name = action.tool_name
526
  current_mode = getattr(self, "_mode", None)
527
 
528
+ mode_info = self._mode_tools.get(tool_name, {})
529
+ if None in mode_info or current_mode in mode_info:
530
  if None in mode_info:
531
  func = mode_info[None]
532
  elif current_mode in mode_info:
533
  func = mode_info[current_mode]
 
 
 
 
 
 
 
 
 
534
  try:
535
  if inspect.iscoroutinefunction(func):
536
  result = await func(**action.arguments)
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"}
@@ -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
  )
 
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"}
 
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
  )
src/core/harness/collect.py CHANGED
@@ -23,7 +23,7 @@ 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
@@ -237,9 +237,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 +255,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 +268,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 +316,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 +518,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)}",
 
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
 
237
  class CollectRunner:
238
  """Drive repeated rollouts into an append-only JSONL dataset.
239
 
240
+ Resume state lives on disk via the ``RolloutSerializer``. Repeatable task
241
+ iterables, such as lists and tuples, restart at the first task on each
242
+ ``run()`` so tasks stay aligned with episode ids. One-shot iterators work
243
+ for one run; reusing them raises ``ValueError`` before accessing results.
244
  """
245
 
246
  def __init__(
 
255
  self._session_factory = session_factory
256
  self._harness_adapter = harness_adapter
257
  self._serializer = serializer
258
+ self._tasks = tasks
259
+ self._tasks_used = False
260
  self._limits = limits
261
 
 
 
 
 
 
 
 
 
262
  def run(
263
  self,
264
  *,
 
268
  resume: bool = True,
269
  should_keep: Callable[[EpisodeRecord], bool] | None = None,
270
  ) -> CollectResult:
271
+ task_iterator = iter(self._tasks) if self._tasks is not None else None
272
+ if (
273
+ task_iterator is not None
274
+ and task_iterator is self._tasks
275
+ and self._tasks_used
276
+ ):
277
+ raise ValueError(
278
+ "Cannot reuse a one-shot task iterator; pass a repeatable iterable "
279
+ "or create a new CollectRunner with a fresh iterator."
280
+ )
281
  planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)]
282
 
283
  if resume:
 
316
  with progress:
317
  for episode_id in planned_ids:
318
  # Preserve task-to-episode alignment even when resume skips ids.
319
+ self._tasks_used = True
320
+ task = next(task_iterator, None) if task_iterator is not None else None
321
  if episode_id in already:
322
  num_skipped += 1
323
  progress.advance(task_id)
 
518
  "",
519
  "# OpenEnv rollouts",
520
  "",
521
+ "Collected with [OpenEnv](https://github.com/openenv/OpenEnv) "
522
  "(`openenv collect`).",
523
  "",
524
  f"- **Episodes:** {_count_episodes(results_path)}",
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/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/templates/openenv_env/pyproject.toml CHANGED
@@ -12,7 +12,7 @@ requires-python = ">=3.10"
12
  dependencies = [
13
  # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
14
  # install from github
15
- # "openenv @ git+https://github.com/huggingface/OpenEnv.git",
16
  "openenv>=0.2.2",
17
  # Environment-specific dependencies
18
  # Add all dependencies needed for your environment here
 
12
  dependencies = [
13
  # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
14
  # install from github
15
+ # "openenv @ git+https://github.com/openenv/OpenEnv.git",
16
  "openenv>=0.2.2",
17
  # Environment-specific dependencies
18
  # Add all dependencies needed for your environment here
src/core/openenv/cli/templates/openenv_env/server/app.py CHANGED
@@ -10,7 +10,7 @@ Endpoints:
10
  - POST /reset: Reset the environment
11
  - POST /step: Execute an action
12
  - GET /state: Get current environment state
13
- - GET /schema: Get action/observation schemas
14
  - WS /ws: WebSocket endpoint for persistent sessions
15
 
16
  Usage:
 
10
  - POST /reset: Reset the environment
11
  - POST /step: Execute an action
12
  - GET /state: Get current environment state
13
+ - GET /schema: Get action/observation/state/reset schemas
14
  - WS /ws: WebSocket endpoint for persistent sessions
15
 
16
  Usage:
src/core/openenv/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/openenv/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/openenv/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/openenv/core/containers/runtime/providers.py CHANGED
@@ -10,7 +10,7 @@ This module provides a pluggable architecture for different container providers
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
 
@@ -21,7 +21,9 @@ class ContainerProvider(ABC):
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 +177,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 +188,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()
@@ -207,6 +213,20 @@ class LocalDockerProvider(ContainerProvider):
207
  for key, value in env_vars.items():
208
  cmd.extend(["-e", f"{key}={value}"])
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  # Add image
211
  cmd.append(image)
212
 
@@ -644,19 +664,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.
 
10
  from __future__ import annotations
11
 
12
  from abc import ABC, abstractmethod
13
+ from typing import Any, Dict, Mapping, Optional, Sequence, TypeVar
14
 
15
  _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider")
16
 
 
21
 
22
  Providers implement this interface to support different container platforms:
23
  - LocalDockerProvider: Runs containers on local Docker daemon
24
+ - DockerSwarmProvider: Runs containers as a Docker Swarm service
25
+ - KubernetesProvider: optional ``openenv[kubernetes]`` extra
26
+ (``kubernetes_provider.py``)
27
  - FargateProvider: Runs containers on AWS Fargate
28
  - CloudRunProvider: Runs containers on Google Cloud Run
29
 
 
177
  Port to expose. If `None`, finds an available port.
178
  env_vars (`dict`, *optional*):
179
  Environment variables for the container.
180
+ volumes (`dict`, *optional*):
181
+ Mapping of host paths or volume names to mount configuration.
182
+ Each configuration must contain a `bind` container path and may
183
+ contain a `mode` such as `"ro"` or `"rw"`.
184
 
185
  Returns:
186
  `str`: Base URL to connect to the container.
 
188
  import subprocess
189
  import time
190
 
191
+ volumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes")
192
+
193
  # Find available port if not specified
194
  if port is None:
195
  port = self._find_available_port()
 
213
  for key, value in env_vars.items():
214
  cmd.extend(["-e", f"{key}={value}"])
215
 
216
+ # Add volume mounts before the image name.
217
+ if volumes:
218
+ for source, config in volumes.items():
219
+ bind = config.get("bind")
220
+ if not bind:
221
+ raise ValueError(
222
+ f"Volume config for {source!r} must include a non-empty 'bind'"
223
+ )
224
+ mode = config.get("mode")
225
+ volume_spec = f"{source}:{bind}"
226
+ if mode:
227
+ volume_spec = f"{volume_spec}:{mode}"
228
+ cmd.extend(["--volume", volume_spec])
229
+
230
  # Add image
231
  cmd.append(image)
232
 
 
664
  return f"{clean_image}-swarm-{timestamp}"
665
 
666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667
  class RuntimeProvider(ABC):
668
  """
669
  Abstract base class for runtime providers that are not container providers.
src/core/openenv/core/env_server/http_server.py CHANGED
@@ -56,6 +56,7 @@ from .mcp_types import (
56
  ListToolsAction,
57
  ListToolsObservation,
58
  McpMethod,
 
59
  WSMCPMessage,
60
  WSMCPResponse,
61
  )
@@ -181,6 +182,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 +210,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 +259,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,6 +267,7 @@ 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()
@@ -280,6 +288,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 +379,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
 
@@ -404,6 +415,13 @@ class HTTPEnvServer:
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:
@@ -441,6 +459,8 @@ class HTTPEnvServer:
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,
@@ -465,6 +485,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,7 +554,13 @@ 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:
@@ -544,6 +571,8 @@ class HTTPEnvServer:
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
@@ -569,12 +598,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 +910,24 @@ 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 +1028,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 +1068,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 +1096,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 +1150,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 +1159,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 +1177,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 +1203,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:
@@ -1221,6 +1303,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(
@@ -1414,7 +1522,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 +1769,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 +1799,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 +1816,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)
@@ -1761,10 +1875,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 +1899,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:
@@ -2003,6 +2122,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 +2167,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 +2197,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 +2216,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 +2233,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 +2259,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 +2289,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 +2319,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 +2328,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,6 +2344,7 @@ 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:
 
56
  ListToolsAction,
57
  ListToolsObservation,
58
  McpMethod,
59
+ ToolErrorType,
60
  WSMCPMessage,
61
  WSMCPResponse,
62
  )
 
182
  state_cls: Type[State] = State,
183
  *,
184
  reset_observation_cls: Optional[Type[Observation]] = None,
185
+ reset_cls: Type[ResetRequest] = ResetRequest,
186
  ):
187
  """
188
  Initialize HTTP server wrapper.
 
210
  The `State` subclass this environment reports. Used for the `/state`
211
  response model and the `state` entry of `/schema`, so that fields
212
  declared by the subclass are published and serialized.
213
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
214
+ The `ResetRequest` subclass describing this environment's reset parameters.
215
+ Published as the `reset` entry of `/schema`. It is not used to validate
216
+ reset requests.
217
 
218
  Raises:
219
  `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided.
 
259
  self.observation_cls = observation_cls
260
  self.reset_observation_cls = reset_observation_cls or observation_cls
261
  self.state_cls = state_cls
262
+ self.reset_cls = reset_cls
263
  self.env_name = env_name or self._default_env_name()
264
 
265
  # Session management for WebSocket connections
 
267
  self._session_executors: Dict[str, ThreadPoolExecutor] = {}
268
  self._session_stacks: Dict[str, AsyncExitStack] = {}
269
  self._session_info: Dict[str, SessionInfo] = {}
270
+ self._session_modes: Dict[str, Optional[str]] = {}
271
  self._session_websocket_attachments: set[str] = set()
272
  self._session_pending_closes: set[str] = set()
273
  self._session_lock = asyncio.Lock()
 
288
  self._concurrency_config.session_timeout
289
  )
290
  self._reaper_task: Optional[asyncio.Task[None]] = None
291
+ self._reaper_stop_event = asyncio.Event()
292
 
293
  def _default_env_name(self) -> str:
294
  factory = self._env_factory
 
379
 
380
  return valid_kwargs
381
 
382
+ async def _create_session(
383
+ self, mode: Optional[str | ServerMode] = None
384
+ ) -> tuple[str, Environment]:
385
  """
386
  Create a new WebSocket session with its own environment instance.
387
 
 
415
  # Create environment in the executor thread (outside lock)
416
  loop = asyncio.get_event_loop()
417
  env = await loop.run_in_executor(executor, self._env_factory)
418
+ mode_val = (
419
+ mode.value
420
+ if isinstance(mode, ServerMode)
421
+ else (str(mode) if mode is not None else None)
422
+ )
423
+ if mode_val is not None and hasattr(env, "set_mode"):
424
+ env.set_mode(mode_val)
425
  except Exception as e:
426
  async with self._session_lock:
427
  if executor is not self._shared_session_executor:
 
459
  async with self._session_lock:
460
  self._sessions[session_id] = env
461
  self._session_stacks[session_id] = stack
462
+ if mode is not None:
463
+ self._session_modes[session_id] = mode_val
464
  now = time.time()
465
  self._session_info[session_id] = SessionInfo(
466
  session_id=session_id,
 
485
  executor = self._session_executors.pop(session_id, None)
486
  stack = self._session_stacks.pop(session_id, None)
487
  self._session_info.pop(session_id, None)
488
+ self._session_modes.pop(session_id, None)
489
  self._session_websocket_attachments.discard(session_id)
490
  self._session_pending_closes.discard(session_id)
491
 
 
554
  interval = max(timeout / 4, 5.0) # check frequently enough
555
  while True:
556
  try:
557
+ try:
558
+ await asyncio.wait_for(
559
+ self._reaper_stop_event.wait(), timeout=interval
560
+ )
561
+ return
562
+ except asyncio.TimeoutError:
563
+ pass
564
  now = time.time()
565
  stale_ids: list[str] = []
566
  async with self._session_lock:
 
571
  ):
572
  stale_ids.append(sid)
573
  for sid in stale_ids:
574
+ if self._reaper_stop_event.is_set():
575
+ return
576
  # Re-check under lock: activity may have arrived since
577
  # the snapshot was taken, making this session active again.
578
  # Refresh `now` so slow _destroy_session calls don't cause
 
598
  def _start_reaper(self) -> None:
599
  """Start the idle-session reaper if a timeout is configured."""
600
  if self._session_idle_timeout_s is not None and self._reaper_task is None:
601
+ self._reaper_stop_event.clear()
602
  self._reaper_task = asyncio.create_task(self._reap_idle_sessions())
603
 
604
+ async def _stop_reaper(self) -> None:
605
+ """Stop the reaper after any in-progress session cleanup finishes."""
606
  if self._reaper_task is not None:
607
+ self._reaper_stop_event.set()
608
+ await self._reaper_task
609
  self._reaper_task = None
610
 
611
  def get_session_info(self, session_id: str) -> Optional[SessionInfo]:
 
910
  f"Invalid mode: '{mode}'. Must be one of: {valid_modes}"
911
  )
912
 
913
+ # Wire up session lifecycle via app events
914
  server_ref = self
915
 
916
  async def _start_session_reaper() -> None:
917
  server_ref._start_reaper()
918
 
919
+ async def _shutdown_sessions() -> None:
920
+ await server_ref._stop_reaper()
921
+ async with server_ref._session_lock:
922
+ session_ids = list(server_ref._sessions)
923
+ for session_id in session_ids:
924
+ await server_ref._destroy_session(session_id)
925
  if server_ref._shared_session_executor is not None:
926
  server_ref._shared_session_executor.shutdown(wait=True)
927
 
928
  if not getattr(app.router, "_openenv_reaper_registered", False):
929
  app.router.on_startup.append(_start_session_reaper)
930
+ app.router.on_shutdown.append(_shutdown_sessions)
931
  app.router._openenv_reaper_registered = True # type: ignore[attr-defined]
932
 
933
  # Helper function to handle reset endpoint
 
1028
  request_id=request_id,
1029
  )
1030
  try:
1031
+ created_session_id, _ = await self._create_session(mode=mode)
1032
  except SessionCapacityError as e:
1033
  return JsonRpcResponse.error_response(
1034
  JsonRpcErrorCode.SERVER_ERROR,
 
1068
  )
1069
 
1070
  async with self._session_lock:
1071
+ session_mode = self._session_modes.get(target_session_id)
1072
+ if (
1073
+ (
1074
+ target_session_id in self._sessions
1075
+ or target_session_id in self._session_websocket_attachments
1076
+ )
1077
+ and session_mode is not None
1078
+ and session_mode != mode.value
1079
+ ):
1080
+ return JsonRpcResponse.error_response(
1081
+ JsonRpcErrorCode.INVALID_PARAMS,
1082
+ f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",
1083
+ request_id=request_id,
1084
+ )
1085
+
1086
  if target_session_id in self._session_websocket_attachments:
1087
  env = _MISSING
1088
  attached = True
 
1096
  executor = self._session_executors.pop(target_session_id, None)
1097
  stack = self._session_stacks.pop(target_session_id, None)
1098
  self._session_info.pop(target_session_id, None)
1099
+ self._session_modes.pop(target_session_id, None)
1100
  elif not attached:
1101
  executor = None
1102
  stack = None
 
1150
  elif requested_session_id:
1151
  async with self._session_lock:
1152
  _env = self._sessions.get(requested_session_id, _MISSING)
1153
+ session_mode = self._session_modes.get(requested_session_id)
1154
 
1155
  if _env is _MISSING:
1156
  return JsonRpcResponse.error_response(
 
1159
  request_id=request_id,
1160
  )
1161
 
1162
+ if session_mode is not None and session_mode != mode.value:
1163
+ return JsonRpcResponse.error_response(
1164
+ JsonRpcErrorCode.INVALID_PARAMS,
1165
+ f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'",
1166
+ request_id=request_id,
1167
+ )
1168
+
1169
  if _env is None:
1170
  return JsonRpcResponse.error_response(
1171
  JsonRpcErrorCode.INVALID_REQUEST,
 
1177
  managed_session_id = requested_session_id
1178
  else:
1179
  _env = self._env_factory()
1180
+ if hasattr(_env, "set_mode"):
1181
+ _env.set_mode(mode.value)
1182
  should_close = True
1183
  try:
1184
  mcp_client = getattr(_env, "mcp_client", None)
 
1203
  }
1204
 
1205
  if method == McpMethod.TOOLS_LIST:
1206
+ if hasattr(_env, "_async_handle_list_tools"):
1207
+ obs = await _env._async_handle_list_tools()
1208
+ if obs.metadata and "error" in obs.metadata:
1209
+ return JsonRpcResponse.error_response(
1210
+ JsonRpcErrorCode.INTERNAL_ERROR,
1211
+ obs.metadata["error"],
1212
+ request_id=request_id,
1213
+ )
1214
+ tools = [
1215
+ {
1216
+ "name": t.name,
1217
+ "description": t.description or "",
1218
+ "inputSchema": t.input_schema,
1219
+ }
1220
+ for t in obs.tools
1221
+ ]
1222
+ return JsonRpcResponse.success(
1223
+ result={"tools": tools},
1224
+ request_id=request_id,
1225
+ )
1226
+
1227
  # Check if environment is MCP-enabled
1228
  if mcp_client is None and mcp_server is None:
1229
  if supports_mcp_style_actions:
 
1303
  request_id=request_id,
1304
  )
1305
 
1306
+ if hasattr(_env, "_mode_tools") and any(
1307
+ m is not None for m in _env._mode_tools.get(tool_name, {})
1308
+ ):
1309
+ obs = await _env._async_handle_call_tool(
1310
+ CallToolAction(tool_name=tool_name, arguments=arguments)
1311
+ )
1312
+ if obs.error:
1313
+ err_code = (
1314
+ JsonRpcErrorCode.INVALID_PARAMS
1315
+ if obs.error.error_type
1316
+ in (
1317
+ ToolErrorType.INVALID_ARGS,
1318
+ ToolErrorType.TOOL_NOT_FOUND,
1319
+ )
1320
+ else JsonRpcErrorCode.INTERNAL_ERROR
1321
+ )
1322
+ return JsonRpcResponse.error_response(
1323
+ err_code,
1324
+ obs.error.message,
1325
+ request_id=request_id,
1326
+ )
1327
+ return JsonRpcResponse.success(
1328
+ result=_make_json_serializable(obs.result),
1329
+ request_id=request_id,
1330
+ )
1331
+
1332
  if mcp_client is None and mcp_server is None:
1333
  if supports_mcp_style_actions:
1334
  observation = await call_mcp_style_step(
 
1522
 
1523
  try:
1524
  # Create session with dedicated environment
1525
+ session_id, session_env = await self._create_session(mode=mode)
1526
  if session_env is None:
1527
  raise RuntimeError(
1528
  "Session environment not initialized for MCP websocket"
 
1769
  tags=["Schema"],
1770
  summary="Get all JSON schemas",
1771
  description="""
1772
+ Get JSON schemas for actions, observations, state, and reset parameters in a single response.
1773
 
1774
  Returns a combined schema object containing:
1775
  - **action**: JSON schema for actions accepted by this environment
1776
  - **observation**: JSON schema for observations returned by step
1777
  - **reset_observation**: JSON schema for observations returned by reset
1778
  - **state**: JSON schema for environment state objects
1779
+ - **reset**: JSON schema for reset parameters accepted by this environment
1780
 
1781
  This is more efficient than calling individual schema endpoints and provides
1782
  all schema information needed to interact with the environment.
 
1799
  "type": "object",
1800
  "properties": {"step_count": {"type": "integer"}},
1801
  },
1802
+ "reset": {
1803
+ "type": "object",
1804
+ "properties": {"seed": {"type": "integer"}},
1805
+ },
1806
  }
1807
  }
1808
  },
 
1816
  observation=self.observation_cls.model_json_schema(),
1817
  reset_observation=self.reset_observation_cls.model_json_schema(),
1818
  state=self.state_cls.model_json_schema(),
1819
+ reset=self.reset_cls.model_json_schema(),
1820
  )
1821
 
1822
  # Register MCP endpoint for production mode (direct MCP access)
 
1875
  attached_env = self._sessions.get(
1876
  requested_session_id, _MISSING
1877
  )
1878
+ session_mode = self._session_modes.get(requested_session_id)
1879
  if attached_env is _MISSING:
1880
  raise RuntimeError(
1881
  f"Unknown session_id: {requested_session_id}"
1882
  )
1883
+ if session_mode is not None and session_mode != mode.value:
1884
+ raise RuntimeError(
1885
+ f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'"
1886
+ )
1887
  if attached_env is None:
1888
  raise RuntimeError(
1889
  f"Session {requested_session_id} is still initializing"
 
1899
  attached_session = True
1900
  self._update_session_activity(session_id)
1901
  else:
1902
+ session_id, session_env = await self._create_session(mode=mode)
1903
  owns_session = True
1904
 
1905
  if session_env is None:
 
2122
  *,
2123
  mode: Optional[ServerMode | str] = None,
2124
  reset_observation_cls: Optional[Type[Observation]] = None,
2125
+ reset_cls: Type[ResetRequest] = ResetRequest,
2126
  ) -> FastAPI:
2127
  """
2128
  Create a FastAPI application with or without web interface.
 
2167
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2168
  The `State` subclass this environment reports, used for the `/state`
2169
  response model and the `state` entry of `/schema`.
2170
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
2171
+ The `ResetRequest` subclass describing this environment's reset parameters,
2172
+ published as the `reset` entry of `/schema`. Not used for validation.
2173
  mode (`ServerMode` or `str`, *optional*):
2174
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2175
  environment variable, defaulting to simulation.
 
2197
  max_concurrent_envs,
2198
  concurrency_config,
2199
  state_cls=state_cls,
2200
+ reset_cls=reset_cls,
2201
  reset_observation_cls=reset_observation_cls,
2202
  gradio_builder=gradio_builder,
2203
  custom_tab_name=custom_tab_name,
 
2216
  concurrency_config,
2217
  env_name=env_name,
2218
  state_cls=state_cls,
2219
+ reset_cls=reset_cls,
2220
  reset_observation_cls=reset_observation_cls,
2221
  mode=mode,
2222
  )
 
2233
  *,
2234
  mode: Optional[ServerMode | str] = None,
2235
  reset_observation_cls: Optional[Type[Observation]] = None,
2236
+ reset_cls: Type[ResetRequest] = ResetRequest,
2237
  ) -> FastAPI:
2238
  """
2239
  Create a FastAPI application with comprehensive documentation.
 
2259
  state_cls (`Type[State]`, *optional*, defaults to `State`):
2260
  The `State` subclass this environment reports, used for the `/state`
2261
  response model and the `state` entry of `/schema`.
2262
+ reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`):
2263
+ The `ResetRequest` subclass describing this environment's reset parameters,
2264
+ published as the `reset` entry of `/schema`. Not used for validation.
2265
  mode (`ServerMode` or `str`, *optional*):
2266
  Server mode. When `None`, resolved from the `OPENENV_MODE`
2267
  environment variable, defaulting to simulation.
 
2289
  * **Environment Reset**: Initialize or restart episodes
2290
  * **Action Execution**: Send actions and receive observations
2291
  * **State Inspection**: Query current environment state
2292
+ * **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters
2293
 
2294
  ## Workflow
2295
 
 
2319
  },
2320
  {
2321
  "name": "Schema",
2322
+ "description": "JSON Schema endpoints for actions, observations, state, and reset parameters",
2323
  },
2324
  {"name": "Health", "description": "Service health and status checks"},
2325
  ],
 
2328
  openapi_url="/openapi.json",
2329
  contact={
2330
  "name": "OpenEnv Team",
2331
+ "url": "https://github.com/openenv/OpenEnv",
2332
  },
2333
  license_info={
2334
  "name": "BSD-3-Clause",
2335
+ "url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE",
2336
  },
2337
  )
2338
 
 
2344
  concurrency_config=concurrency_config,
2345
  env_name=env_name,
2346
  state_cls=state_cls,
2347
+ reset_cls=reset_cls,
2348
  reset_observation_cls=reset_observation_cls,
2349
  )
2350
  if mode is None:
src/core/openenv/core/env_server/interfaces.py CHANGED
@@ -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*):
 
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/openenv/core/env_server/mcp_environment.py CHANGED
@@ -195,6 +195,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."""
@@ -496,7 +501,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 +525,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)
 
195
 
196
  # Track tool schemas for list_tools: {tool_name: {mode: schema}}
197
  self._mode_tool_schemas = defaultdict(dict)
198
+ self._mode: Optional[str] = None
199
+
200
+ def set_mode(self, mode: Optional[str]) -> None:
201
+ """Set the active mode ('production' or 'simulation') for mode-aware tools."""
202
+ self._mode = mode
203
 
204
  def _require_mcp_client(self) -> Any:
205
  """Return MCP client or raise if environment has been closed."""
 
501
  tools_result = await self._async_list_tools()
502
  tools = []
503
  for tool in tools_result:
504
+ mode_schemas = self._mode_tool_schemas.get(tool.name, {})
505
+ if _schema_for_mode(mode_schemas, current_mode) is None:
506
  tools.append(_tool_from_server_tool(tool))
507
  for mode_schemas in self._mode_tool_schemas.values():
508
  schema = _schema_for_mode(mode_schemas, current_mode)
 
525
  tool_name = action.tool_name
526
  current_mode = getattr(self, "_mode", None)
527
 
528
+ mode_info = self._mode_tools.get(tool_name, {})
529
+ if None in mode_info or current_mode in mode_info:
530
  if None in mode_info:
531
  func = mode_info[None]
532
  elif current_mode in mode_info:
533
  func = mode_info[current_mode]
 
 
 
 
 
 
 
 
 
534
  try:
535
  if inspect.iscoroutinefunction(func):
536
  result = await func(**action.arguments)
src/core/openenv/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/openenv/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"}
@@ -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
  )
 
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"}
 
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
  )
src/core/openenv/core/harness/collect.py CHANGED
@@ -23,7 +23,7 @@ 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
@@ -237,9 +237,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 +255,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 +268,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 +316,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 +518,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)}",
 
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
 
237
  class CollectRunner:
238
  """Drive repeated rollouts into an append-only JSONL dataset.
239
 
240
+ Resume state lives on disk via the ``RolloutSerializer``. Repeatable task
241
+ iterables, such as lists and tuples, restart at the first task on each
242
+ ``run()`` so tasks stay aligned with episode ids. One-shot iterators work
243
+ for one run; reusing them raises ``ValueError`` before accessing results.
244
  """
245
 
246
  def __init__(
 
255
  self._session_factory = session_factory
256
  self._harness_adapter = harness_adapter
257
  self._serializer = serializer
258
+ self._tasks = tasks
259
+ self._tasks_used = False
260
  self._limits = limits
261
 
 
 
 
 
 
 
 
 
262
  def run(
263
  self,
264
  *,
 
268
  resume: bool = True,
269
  should_keep: Callable[[EpisodeRecord], bool] | None = None,
270
  ) -> CollectResult:
271
+ task_iterator = iter(self._tasks) if self._tasks is not None else None
272
+ if (
273
+ task_iterator is not None
274
+ and task_iterator is self._tasks
275
+ and self._tasks_used
276
+ ):
277
+ raise ValueError(
278
+ "Cannot reuse a one-shot task iterator; pass a repeatable iterable "
279
+ "or create a new CollectRunner with a fresh iterator."
280
+ )
281
  planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)]
282
 
283
  if resume:
 
316
  with progress:
317
  for episode_id in planned_ids:
318
  # Preserve task-to-episode alignment even when resume skips ids.
319
+ self._tasks_used = True
320
+ task = next(task_iterator, None) if task_iterator is not None else None
321
  if episode_id in already:
322
  num_skipped += 1
323
  progress.advance(task_id)
 
518
  "",
519
  "# OpenEnv rollouts",
520
  "",
521
+ "Collected with [OpenEnv](https://github.com/openenv/OpenEnv) "
522
  "(`openenv collect`).",
523
  "",
524
  f"- **Episodes:** {_count_episodes(results_path)}",
src/core/openenv/core/rubrics/containers.py CHANGED
@@ -85,8 +85,7 @@ class Sequential(Rubric):
85
  else:
86
  # Continue with sync path
87
  if first_result == 0.0:
88
- self._run_forward_pre_hooks(action, observation, start=ran)
89
- return self._finish_forward(action, observation, 0.0)
90
 
91
  final_result = first_result
92
  for i, rubric in enumerate(self._rubric_list[1:], start=1):
@@ -102,16 +101,21 @@ class Sequential(Rubric):
102
  ran,
103
  )
104
  if score == 0.0:
105
- self._run_forward_pre_hooks(action, observation, start=ran)
106
- return self._finish_forward(action, observation, 0.0)
107
  final_result = score
108
 
109
- # All sync - check if in async context
110
- if _in_async_context():
111
- return self._wrap_sync_result(action, observation, final_result, ran)
112
- else:
113
- self._run_forward_pre_hooks(action, observation, start=ran)
114
- return self._finish_forward(action, observation, final_result)
 
 
 
 
 
 
115
 
116
  async def _empty_async(self, action, observation):
117
  """Async path for empty sequential."""
 
85
  else:
86
  # Continue with sync path
87
  if first_result == 0.0:
88
+ return self._finish_sync(action, observation, 0.0, ran)
 
89
 
90
  final_result = first_result
91
  for i, rubric in enumerate(self._rubric_list[1:], start=1):
 
101
  ran,
102
  )
103
  if score == 0.0:
104
+ return self._finish_sync(action, observation, 0.0, ran)
 
105
  final_result = score
106
 
107
+ return self._finish_sync(action, observation, final_result, ran)
108
+
109
+ def _finish_sync(self, action, observation, result, ran=0):
110
+ """Finish a run where every evaluated child was sync.
111
+
112
+ In an async context, return an awaitable even when a child stopped
113
+ the chain, so callers can always ``await`` the result.
114
+ """
115
+ if _in_async_context():
116
+ return self._wrap_sync_result(action, observation, result, ran)
117
+ self._run_forward_pre_hooks(action, observation, start=ran)
118
+ return self._finish_forward(action, observation, result)
119
 
120
  async def _empty_async(self, action, observation):
121
  """Async path for empty sequential."""
src/core/openenv/core/sync_client.py CHANGED
@@ -243,8 +243,15 @@ class SyncEnvClient(Generic[ActT, ObsT, StateT]):
243
  WebSocket can fail and is surfaced as a connection error.
244
  """
245
  async_client = self._async._create_session_client()
246
- client = SyncEnvClient(async_client)
247
- client.connect()
 
 
 
 
 
 
 
248
  self._child_clients.append(client)
249
  return client
250
 
 
243
  WebSocket can fail and is surfaced as a connection error.
244
  """
245
  async_client = self._async._create_session_client()
246
+ client = async_client.sync()
247
+ try:
248
+ client.connect()
249
+ except Exception:
250
+ # No caller receives this child on failure. Release its loop here
251
+ # while preserving the connection error if cleanup also fails.
252
+ with suppress(Exception):
253
+ client.close()
254
+ raise
255
  self._child_clients.append(client)
256
  return client
257
 
src/core/openenv/core/tools/git_server_client.py CHANGED
@@ -17,7 +17,7 @@ import tempfile
17
  import time
18
  from dataclasses import dataclass
19
  from pathlib import Path
20
- from urllib.parse import urlparse
21
 
22
 
23
  @dataclass
@@ -101,10 +101,13 @@ class GitServerClient:
101
  config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-"))
102
  atexit.register(shutil.rmtree, config_dir, ignore_errors=True)
103
 
104
- # Git credentials
105
- git_credentials = (
106
- f"http://{self.username}:{self.password}@{self.domain}:{self.port}\n"
107
- )
 
 
 
108
  gitcreds_path = config_dir / "git-credentials"
109
  gitcreds_path.write_text(git_credentials)
110
  gitcreds_path.chmod(0o600)
 
17
  import time
18
  from dataclasses import dataclass
19
  from pathlib import Path
20
+ from urllib.parse import quote, urlparse
21
 
22
 
23
  @dataclass
 
101
  config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-"))
102
  atexit.register(shutil.rmtree, config_dir, ignore_errors=True)
103
 
104
+ # Git credentials. The entry must match the URL git is given (scheme and
105
+ # host[:port]), and the user name and password must be percent-encoded
106
+ # so characters such as "@", ":", "/" or "#" do not break the URL.
107
+ parsed = urlparse(self.gitea_url)
108
+ user = quote(self.username, safe="")
109
+ password = quote(self.password, safe="")
110
+ git_credentials = f"{parsed.scheme}://{user}:{password}@{parsed.netloc}\n"
111
  gitcreds_path = config_dir / "git-credentials"
112
  gitcreds_path.write_text(git_credentials)
113
  gitcreds_path.chmod(0o600)
src/core/openenv/discovery/schemas/0.1-draft/catalog.schema.json CHANGED
@@ -652,7 +652,7 @@
652
  "type": "object"
653
  }
654
  },
655
- "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json",
656
  "$schema": "https://json-schema.org/draft/2020-12/schema",
657
  "additionalProperties": false,
658
  "properties": {
 
652
  "type": "object"
653
  }
654
  },
655
+ "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json",
656
  "$schema": "https://json-schema.org/draft/2020-12/schema",
657
  "additionalProperties": false,
658
  "properties": {
src/core/openenv/discovery/schemas/0.1-draft/declaration.schema.json CHANGED
@@ -49,7 +49,7 @@
49
  "type": "object"
50
  }
51
  },
52
- "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json",
53
  "$schema": "https://json-schema.org/draft/2020-12/schema",
54
  "additionalProperties": false,
55
  "properties": {
 
49
  "type": "object"
50
  }
51
  },
52
+ "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json",
53
  "$schema": "https://json-schema.org/draft/2020-12/schema",
54
  "additionalProperties": false,
55
  "properties": {
src/core/openenv/discovery/schemas/0.1-draft/environment-card.schema.json CHANGED
@@ -186,7 +186,7 @@
186
  "type": "object"
187
  }
188
  },
189
- "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json",
190
  "$schema": "https://json-schema.org/draft/2020-12/schema",
191
  "additionalProperties": false,
192
  "allOf": [
 
186
  "type": "object"
187
  }
188
  },
189
+ "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json",
190
  "$schema": "https://json-schema.org/draft/2020-12/schema",
191
  "additionalProperties": false,
192
  "allOf": [
src/core/openenv/harbor/atif.py CHANGED
@@ -325,6 +325,26 @@ def reconcile(document: dict[str, Any], atif: dict[str, Any] | None) -> Report:
325
  )
326
  return report
327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  # Compare against EVERY call the agent made, in arrival order, across ALL agent roots.
329
  #
330
  # Two reasons this is the right comparison rather than the surviving training path:
@@ -473,25 +493,6 @@ def reconcile(document: dict[str, Any], atif: dict[str, Any] | None) -> Report:
473
  f"Graph found {document['stats']['n_discarded']} discarded turn(s).",
474
  )
475
 
476
- subagents = atif.get("subagent_trajectories") or []
477
- if subagents:
478
- # FATAL, not WARN. The old text said subagent turns "must not be trained with the parent
479
- # rollout's reward" and then did nothing to stop it: no node ids were collected, no role was
480
- # changed, so if a subagent's calls landed in the same session as `agent` roots they shipped as
481
- # trainable carrying the parent's reward — the exact outcome the sentence forbade. The aux path
482
- # right above demotes; this one only complained.
483
- #
484
- # Refusing rather than guessing which roots belong to the subagent: ATIF gives trajectories,
485
- # not the node ids that would let us demote precisely, and picking roots by shape here would be
486
- # inventing an attribution. A rollout whose reward cannot be attributed is not trainable.
487
- report.add(
488
- FATAL,
489
- "atif_subagents",
490
- f"ATIF reports {len(subagents)} subagent trajectory(ies) and the graph has "
491
- f"{document['stats']['n_roots']} root(s). Subagent turns must not be trained with the "
492
- "parent rollout's reward, and ATIF does not say which captured calls are theirs, so "
493
- "this rollout cannot be attributed. Run this harness without subagents to train on it.",
494
- )
495
  return report
496
 
497
 
 
325
  )
326
  return report
327
 
328
+ subagents = atif.get("subagent_trajectories") or []
329
+ if subagents:
330
+ # FATAL, not WARN. The old text said subagent turns "must not be trained with the parent
331
+ # rollout's reward" and then did nothing to stop it: no node ids were collected, no role was
332
+ # changed, so if a subagent's calls landed in the same session as `agent` roots they shipped as
333
+ # trainable carrying the parent's reward — the exact outcome the sentence forbade. The aux path
334
+ # below demotes; this one only complained.
335
+ #
336
+ # Refusing rather than guessing which roots belong to the subagent: ATIF gives trajectories,
337
+ # not the node ids that would let us demote precisely, and picking roots by shape here would be
338
+ # inventing an attribution. A rollout whose reward cannot be attributed is not trainable.
339
+ report.add(
340
+ FATAL,
341
+ "atif_subagents",
342
+ f"ATIF reports {len(subagents)} subagent trajectory(ies) and the graph has "
343
+ f"{document['stats']['n_roots']} root(s). Subagent turns must not be trained with the "
344
+ "parent rollout's reward, and ATIF does not say which captured calls are theirs, so "
345
+ "this rollout cannot be attributed. Run this harness without subagents to train on it.",
346
+ )
347
+
348
  # Compare against EVERY call the agent made, in arrival order, across ALL agent roots.
349
  #
350
  # Two reasons this is the right comparison rather than the surviving training path:
 
493
  f"Graph found {document['stats']['n_discarded']} discarded turn(s).",
494
  )
495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  return report
497
 
498
 
src/core/rubrics/containers.py CHANGED
@@ -85,8 +85,7 @@ class Sequential(Rubric):
85
  else:
86
  # Continue with sync path
87
  if first_result == 0.0:
88
- self._run_forward_pre_hooks(action, observation, start=ran)
89
- return self._finish_forward(action, observation, 0.0)
90
 
91
  final_result = first_result
92
  for i, rubric in enumerate(self._rubric_list[1:], start=1):
@@ -102,16 +101,21 @@ class Sequential(Rubric):
102
  ran,
103
  )
104
  if score == 0.0:
105
- self._run_forward_pre_hooks(action, observation, start=ran)
106
- return self._finish_forward(action, observation, 0.0)
107
  final_result = score
108
 
109
- # All sync - check if in async context
110
- if _in_async_context():
111
- return self._wrap_sync_result(action, observation, final_result, ran)
112
- else:
113
- self._run_forward_pre_hooks(action, observation, start=ran)
114
- return self._finish_forward(action, observation, final_result)
 
 
 
 
 
 
115
 
116
  async def _empty_async(self, action, observation):
117
  """Async path for empty sequential."""
 
85
  else:
86
  # Continue with sync path
87
  if first_result == 0.0:
88
+ return self._finish_sync(action, observation, 0.0, ran)
 
89
 
90
  final_result = first_result
91
  for i, rubric in enumerate(self._rubric_list[1:], start=1):
 
101
  ran,
102
  )
103
  if score == 0.0:
104
+ return self._finish_sync(action, observation, 0.0, ran)
 
105
  final_result = score
106
 
107
+ return self._finish_sync(action, observation, final_result, ran)
108
+
109
+ def _finish_sync(self, action, observation, result, ran=0):
110
+ """Finish a run where every evaluated child was sync.
111
+
112
+ In an async context, return an awaitable even when a child stopped
113
+ the chain, so callers can always ``await`` the result.
114
+ """
115
+ if _in_async_context():
116
+ return self._wrap_sync_result(action, observation, result, ran)
117
+ self._run_forward_pre_hooks(action, observation, start=ran)
118
+ return self._finish_forward(action, observation, result)
119
 
120
  async def _empty_async(self, action, observation):
121
  """Async path for empty sequential."""
src/core/sync_client.py CHANGED
@@ -243,8 +243,15 @@ class SyncEnvClient(Generic[ActT, ObsT, StateT]):
243
  WebSocket can fail and is surfaced as a connection error.
244
  """
245
  async_client = self._async._create_session_client()
246
- client = SyncEnvClient(async_client)
247
- client.connect()
 
 
 
 
 
 
 
248
  self._child_clients.append(client)
249
  return client
250
 
 
243
  WebSocket can fail and is surfaced as a connection error.
244
  """
245
  async_client = self._async._create_session_client()
246
+ client = async_client.sync()
247
+ try:
248
+ client.connect()
249
+ except Exception:
250
+ # No caller receives this child on failure. Release its loop here
251
+ # while preserving the connection error if cleanup also fails.
252
+ with suppress(Exception):
253
+ client.close()
254
+ raise
255
  self._child_clients.append(client)
256
  return client
257
 
src/core/tools/git_server_client.py CHANGED
@@ -17,7 +17,7 @@ import tempfile
17
  import time
18
  from dataclasses import dataclass
19
  from pathlib import Path
20
- from urllib.parse import urlparse
21
 
22
 
23
  @dataclass
@@ -101,10 +101,13 @@ class GitServerClient:
101
  config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-"))
102
  atexit.register(shutil.rmtree, config_dir, ignore_errors=True)
103
 
104
- # Git credentials
105
- git_credentials = (
106
- f"http://{self.username}:{self.password}@{self.domain}:{self.port}\n"
107
- )
 
 
 
108
  gitcreds_path = config_dir / "git-credentials"
109
  gitcreds_path.write_text(git_credentials)
110
  gitcreds_path.chmod(0o600)
 
17
  import time
18
  from dataclasses import dataclass
19
  from pathlib import Path
20
+ from urllib.parse import quote, urlparse
21
 
22
 
23
  @dataclass
 
101
  config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-"))
102
  atexit.register(shutil.rmtree, config_dir, ignore_errors=True)
103
 
104
+ # Git credentials. The entry must match the URL git is given (scheme and
105
+ # host[:port]), and the user name and password must be percent-encoded
106
+ # so characters such as "@", ":", "/" or "#" do not break the URL.
107
+ parsed = urlparse(self.gitea_url)
108
+ user = quote(self.username, safe="")
109
+ password = quote(self.password, safe="")
110
+ git_credentials = f"{parsed.scheme}://{user}:{password}@{parsed.netloc}\n"
111
  gitcreds_path = config_dir / "git-credentials"
112
  gitcreds_path.write_text(git_credentials)
113
  gitcreds_path.chmod(0o600)
src/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/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/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/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/openenv/cli/templates/openenv_env/pyproject.toml CHANGED
@@ -12,7 +12,7 @@ requires-python = ">=3.10"
12
  dependencies = [
13
  # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
14
  # install from github
15
- # "openenv @ git+https://github.com/huggingface/OpenEnv.git",
16
  "openenv>=0.2.2",
17
  # Environment-specific dependencies
18
  # Add all dependencies needed for your environment here
 
12
  dependencies = [
13
  # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
14
  # install from github
15
+ # "openenv @ git+https://github.com/openenv/OpenEnv.git",
16
  "openenv>=0.2.2",
17
  # Environment-specific dependencies
18
  # Add all dependencies needed for your environment here
src/openenv/cli/templates/openenv_env/server/app.py CHANGED
@@ -10,7 +10,7 @@ Endpoints:
10
  - POST /reset: Reset the environment
11
  - POST /step: Execute an action
12
  - GET /state: Get current environment state
13
- - GET /schema: Get action/observation schemas
14
  - WS /ws: WebSocket endpoint for persistent sessions
15
 
16
  Usage:
 
10
  - POST /reset: Reset the environment
11
  - POST /step: Execute an action
12
  - GET /state: Get current environment state
13
+ - GET /schema: Get action/observation/state/reset schemas
14
  - WS /ws: WebSocket endpoint for persistent sessions
15
 
16
  Usage: