Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Dockerfile+52-25
- README.md+2-2
- client.py+8-32
- envs/chat_env/client.py+8-32
- envs/chat_env/models.py+33-14
- envs/chat_env/openenv_chat_env.egg-info/PKG-INFOAdded+14
- envs/chat_env/openenv_chat_env.egg-info/SOURCES.txtAdded+18
- envs/chat_env/openenv_chat_env.egg-info/dependency_links.txtAdded+1
- envs/chat_env/openenv_chat_env.egg-info/entry_points.txtAdded+2
- envs/chat_env/openenv_chat_env.egg-info/requires.txtAdded+10
- envs/chat_env/openenv_chat_env.egg-info/top_level.txtAdded+1
- envs/chat_env/pyproject.tomlAdded+37
- envs/chat_env/server/Dockerfile+49-25
- envs/chat_env/server/app.py+16-3
- envs/chat_env/server/chat_environment.py+40-29
- envs/chat_env/server/requirements.txt-1
- envs/chat_env/server/test_chat_env.py+17-16
- models.py+33-14
- openenv_chat_env.egg-info/PKG-INFOAdded+14
- openenv_chat_env.egg-info/SOURCES.txtAdded+18
- openenv_chat_env.egg-info/dependency_links.txtAdded+1
- openenv_chat_env.egg-info/entry_points.txtAdded+2
- openenv_chat_env.egg-info/requires.txtAdded+10
- openenv_chat_env.egg-info/top_level.txtAdded+1
- pyproject.toml+19-129
- server/Dockerfile+49-25
- server/app.py+16-3
- server/chat_environment.py+40-29
- server/requirements.txt-1
- server/test_chat_env.py+17-16
- src/core/env_server/http_server.py+537-282
- src/core/env_server/mcp_environment.py+113-92
- src/core/env_server/serialization.py+35-1
- src/core/env_server/web_interface.py+62-9
- src/core/mcp_client.py+126-19
- src/core/openenv/__init__.py+12-4
- src/core/openenv/cli/templates/openenv_env/pyproject.toml+1-1
- src/core/openenv/core/env_server/http_server.py+537-282
- src/core/openenv/core/env_server/mcp_environment.py+113-92
- src/core/openenv/core/env_server/serialization.py+35-1
- src/core/openenv/core/env_server/web_interface.py+62-9
- src/core/openenv/core/mcp_client.py+126-19
- src/openenv/__init__.py+12-4
- src/openenv/cli/templates/openenv_env/pyproject.toml+1-1
- src/openenv/core/env_server/http_server.py+537-282
- src/openenv/core/env_server/mcp_environment.py+113-92
- src/openenv/core/env_server/serialization.py+35-1
- src/openenv/core/env_server/web_interface.py+62-9
- src/openenv/core/mcp_client.py+126-19
- src/openenv_core.egg-info/PKG-INFO+3-2
3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041423 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.# Use the standard openenv base image# Built from: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# In GitHub Actions, this is overridden to use the GHCR base imageARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ghcr.io/meta-pytorch/openenv-base:latest# Install dependencies and run setupCOPY envs/chat_env/server/requirements.txt /tmp/requirements.txtCOPY envs/chat_env/server/install_deps.sh /tmp/install_deps.shRUN chmod +x /tmp/install_deps.sh && \/tmp/install_deps.sh && \rm /tmp/install_deps.sh /tmp/requirements.txt# Set environment variablesENV HF_HOME=/.cacheENV TRANSFORMERS_CACHE=/.cache# Environment variables that can be overridden at runtimeENV TOKENIZER_NAME=gpt2ENV SYSTEM_PROMPT="You are a helpful AI assistant."ENV ENABLE_WEB_INTERFACE=false# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY envs/chat_env/ /app/envs/chat_env/# Copy README for web interface documentationCOPY envs/chat_env/README.md /app/README.md# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD curl -f http://localhost:8000/health || exit 1# Run the FastAPI serverCMD ["uvicorn", "envs.chat_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]ENV PYTHONPATH=/app/src/core:/app/src:${PYTHONPATH}3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768693 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ghcr.io/meta-pytorch/openenv-base:latest AS builderWORKDIR /appCOPY . /app/envWORKDIR /app/envRUN if ! command -v uv >/dev/null 2>&1; then \curl -LsSf https://astral.sh/uv/install.sh | sh && \mv /root/.local/bin/uv /usr/local/bin/uv && \mv /root/.local/bin/uvx /usr/local/bin/uvx; \fiRUN apt-get update && apt-get install -y --no-install-recommends \git \&& rm -rf /var/lib/apt/lists/*RUN curl -LsSf https://astral.sh/uv/install.sh | sh && \install -m 0755 /root/.local/bin/uv /usr/local/bin/uv && \install -m 0755 /root/.local/bin/uvx /usr/local/bin/uvxRUN --mount=type=cache,target=/root/.cache/uv \if [ -f uv.lock ]; then \uv sync --no-install-project --no-editable; \else \uv sync --no-install-project --no-editable; \fiRUN --mount=type=cache,target=/root/.cache/uv \if [ -f uv.lock ]; then \uv sync --no-editable; \else \uv sync --no-editable; \fi# Pre-download GPT-2 tokenizer to avoid permission issues at runtime.# HF_HOME must match the runtime value so the cache is copied to the right place.RUN HF_HOME=/.cache /app/env/.venv/bin/python -c "from transformers import GPT2Tokenizer; GPT2Tokenizer.from_pretrained('gpt2')"# Final runtime stageFROM ghcr.io/meta-pytorch/openenv-base:latestWORKDIR /appCOPY --from=builder /app/env/.venv /app/.venvCOPY --from=builder /app/env /app/envCOPY --from=builder /.cache /.cacheENV PATH="/app/.venv/bin:$PATH"ENV PYTHONPATH="/app/env:$PYTHONPATH"ENV HF_HOME=/.cacheENV TRANSFORMERS_CACHE=/.cacheENV TOKENIZER_NAME=gpt2ENV SYSTEM_PROMPT="You are a helpful AI assistant."ENV ENABLE_WEB_INTERFACE=trueHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
7 unmodified lines8910111213142 unmodified lines171819202122237 unmodified linesapp_port: 8000base_path: /webtags:- openenv-main- openenv---2 unmodified linesThis Space is built from OpenEnv environment `chat_env`.- Space URL: `https://huggingface.co/spaces/openenv/chat_env`- OpenEnv pinned ref: `main`- Hub tag: `openenv`### Connecting from Code7 unmodified lines8910111213142 unmodified lines171819202122237 unmodified linesapp_port: 8000base_path: /webtags:- openenv-0.2.3- openenv---2 unmodified linesThis Space is built from OpenEnv environment `chat_env`.- Space URL: `https://huggingface.co/spaces/openenv/chat_env`- OpenEnv pinned ref: `0.2.3`- Hub tag: `openenv`### Connecting from Code
12 unmodified lines131415161718198 unmodified lines28293031323334352 unmodified lines38394041424344453 unmodified lines495051525354552 unmodified lines58596061626364656667686970717273747576777879809 unmodified lines9091929394959697989910010110210310425 unmodified lines13013113213313413513613713813914014114214332 unmodified lines17617717817918018118218312 unmodified linesfrom typing import Any, Dictimport torchfrom openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClientfrom openenv.core.env_server.interfaces import Message8 unmodified linesThis client maintains a persistent WebSocket connection to the environmentserver, enabling efficient multi-step interactions with lower latency.Note: Since ChatEnvironment works with PyTorch tensors, the clientserializes tokens as lists for transport and deserializes them back to tensors.Example:>>> # Connect to a running server2 unmodified lines... print(result.observation.messages)...... # Send an action with tokens... import torch... tokens = torch.tensor([[1, 2, 3, 4, 5]])... result = client.step(ChatAction(tokens=tokens))... print(result.observation.messages)... print(result.reward)3 unmodified lines>>> client = ChatEnv.from_docker_image("chat-env:latest")>>> try:... result = client.reset()... result = client.step(ChatAction(tokens=torch.tensor([[1, 2, 3]])))... finally:... client.close()"""2 unmodified lines"""Convert ChatAction to JSON payload for step request.Since PyTorch tensors can't be directly serialized to JSON,we convert them to nested lists.Args:action: ChatAction instance with tokensReturns:Dictionary representation suitable for JSON encoding"""# Convert tensor to list for JSON serializationif isinstance(action.tokens, torch.Tensor):tokens_list = action.tokens.tolist()else:tokens_list = action.tokensreturn {"tokens": tokens_list,"metadata": action.metadata,}9 unmodified lines"""obs_data = payload.get("observation", {})# Convert tokens list back to tensortokens_data = obs_data.get("tokens", [])if isinstance(tokens_data, list):if tokens_data:tokens = torch.tensor(tokens_data)else:tokens = torch.tensor([])else:tokens = torch.tensor([])# Parse messagesmessages = obs_data.get("messages", [])25 unmodified lines# Parse history messageshistory_messages = payload.get("history_messages", [])# Parse history tokens - convert lists back to tensorshistory_tokens_data = payload.get("history_tokens", [])history_tokens = []for token_list in history_tokens_data:if token_list:history_tokens.append(torch.tensor(token_list))else:history_tokens.append(torch.tensor([]))return ChatState(episode_id=payload.get("episode_id"),32 unmodified linesraise ValueError("Message content cannot be None")# Tokenize the messagetokens = tokenizer.apply_chat_template(conversation=[message], tokenize=True, return_tensors="pt")return ChatAction(tokens=tokens)12 unmodified lines1314151617188 unmodified lines272829303132332 unmodified lines363738394041423 unmodified lines464748495051522 unmodified lines55565758596061626364656667689 unmodified lines787980818283848525 unmodified lines11111211311411511611711811912012132 unmodified lines15415515615715815912 unmodified linesfrom typing import Any, Dictfrom openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClientfrom openenv.core.env_server.interfaces import Message8 unmodified linesThis client maintains a persistent WebSocket connection to the environmentserver, enabling efficient multi-step interactions with lower latency.The client transports token ids as plain JSON lists.Example:>>> # Connect to a running server2 unmodified lines... print(result.observation.messages)...... # Send an action with tokens... tokens = [1, 2, 3, 4, 5]... result = client.step(ChatAction(tokens=tokens))... print(result.observation.messages)... print(result.reward)3 unmodified lines>>> client = ChatEnv.from_docker_image("chat-env:latest")>>> try:... result = client.reset()... result = client.step(ChatAction(tokens=[1, 2, 3]))... finally:... client.close()"""2 unmodified lines"""Convert ChatAction to JSON payload for step request.Args:action: ChatAction instance with tokensReturns:Dictionary representation suitable for JSON encoding"""return {"tokens": action.tokens,"metadata": action.metadata,}9 unmodified lines"""obs_data = payload.get("observation", {})tokens_data = obs_data.get("tokens", [])tokens = tokens_data if isinstance(tokens_data, list) else []# Parse messagesmessages = obs_data.get("messages", [])25 unmodified lines# Parse history messageshistory_messages = payload.get("history_messages", [])# Parse history tokenshistory_tokens_data = payload.get("history_tokens", [])history_tokens = []for token_list in history_tokens_data:history_tokens.append(token_list if isinstance(token_list, list) else [])return ChatState(episode_id=payload.get("episode_id"),32 unmodified linesraise ValueError("Message content cannot be None")# Tokenize the messagetokens = tokenizer.apply_chat_template(conversation=[message], tokenize=True)return ChatAction(tokens=tokens)
12 unmodified lines131415161718198 unmodified lines28293031323334352 unmodified lines38394041424344453 unmodified lines495051525354552 unmodified lines58596061626364656667686970717273747576777879809 unmodified lines9091929394959697989910010110210310425 unmodified lines13013113213313413513613713813914014114214332 unmodified lines17617717817918018118218312 unmodified linesfrom typing import Any, Dictimport torchfrom openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClientfrom openenv.core.env_server.interfaces import Message8 unmodified linesThis client maintains a persistent WebSocket connection to the environmentserver, enabling efficient multi-step interactions with lower latency.Note: Since ChatEnvironment works with PyTorch tensors, the clientserializes tokens as lists for transport and deserializes them back to tensors.Example:>>> # Connect to a running server2 unmodified lines... print(result.observation.messages)...... # Send an action with tokens... import torch... tokens = torch.tensor([[1, 2, 3, 4, 5]])... result = client.step(ChatAction(tokens=tokens))... print(result.observation.messages)... print(result.reward)3 unmodified lines>>> client = ChatEnv.from_docker_image("chat-env:latest")>>> try:... result = client.reset()... result = client.step(ChatAction(tokens=torch.tensor([[1, 2, 3]])))... finally:... client.close()"""2 unmodified lines"""Convert ChatAction to JSON payload for step request.Since PyTorch tensors can't be directly serialized to JSON,we convert them to nested lists.Args:action: ChatAction instance with tokensReturns:Dictionary representation suitable for JSON encoding"""# Convert tensor to list for JSON serializationif isinstance(action.tokens, torch.Tensor):tokens_list = action.tokens.tolist()else:tokens_list = action.tokensreturn {"tokens": tokens_list,"metadata": action.metadata,}9 unmodified lines"""obs_data = payload.get("observation", {})# Convert tokens list back to tensortokens_data = obs_data.get("tokens", [])if isinstance(tokens_data, list):if tokens_data:tokens = torch.tensor(tokens_data)else:tokens = torch.tensor([])else:tokens = torch.tensor([])# Parse messagesmessages = obs_data.get("messages", [])25 unmodified lines# Parse history messageshistory_messages = payload.get("history_messages", [])# Parse history tokens - convert lists back to tensorshistory_tokens_data = payload.get("history_tokens", [])history_tokens = []for token_list in history_tokens_data:if token_list:history_tokens.append(torch.tensor(token_list))else:history_tokens.append(torch.tensor([]))return ChatState(episode_id=payload.get("episode_id"),32 unmodified linesraise ValueError("Message content cannot be None")# Tokenize the messagetokens = tokenizer.apply_chat_template(conversation=[message], tokenize=True, return_tensors="pt")return ChatAction(tokens=tokens)12 unmodified lines1314151617188 unmodified lines272829303132332 unmodified lines363738394041423 unmodified lines464748495051522 unmodified lines55565758596061626364656667689 unmodified lines787980818283848525 unmodified lines11111211311411511611711811912012132 unmodified lines15415515615715815912 unmodified linesfrom typing import Any, Dictfrom openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClientfrom openenv.core.env_server.interfaces import Message8 unmodified linesThis client maintains a persistent WebSocket connection to the environmentserver, enabling efficient multi-step interactions with lower latency.The client transports token ids as plain JSON lists.Example:>>> # Connect to a running server2 unmodified lines... print(result.observation.messages)...... # Send an action with tokens... tokens = [1, 2, 3, 4, 5]... result = client.step(ChatAction(tokens=tokens))... print(result.observation.messages)... print(result.reward)3 unmodified lines>>> client = ChatEnv.from_docker_image("chat-env:latest")>>> try:... result = client.reset()... result = client.step(ChatAction(tokens=[1, 2, 3]))... finally:... client.close()"""2 unmodified lines"""Convert ChatAction to JSON payload for step request.Args:action: ChatAction instance with tokensReturns:Dictionary representation suitable for JSON encoding"""return {"tokens": action.tokens,"metadata": action.metadata,}9 unmodified lines"""obs_data = payload.get("observation", {})tokens_data = obs_data.get("tokens", [])tokens = tokens_data if isinstance(tokens_data, list) else []# Parse messagesmessages = obs_data.get("messages", [])25 unmodified lines# Parse history messageshistory_messages = payload.get("history_messages", [])# Parse history tokenshistory_tokens_data = payload.get("history_tokens", [])history_tokens = []for token_list in history_tokens_data:history_tokens.append(token_list if isinstance(token_list, list) else [])return ChatState(episode_id=payload.get("episode_id"),32 unmodified linesraise ValueError("Message content cannot be None")# Tokenize the messagetokens = tokenizer.apply_chat_template(conversation=[message], tokenize=True)return ChatAction(tokens=tokens)
10 unmodified lines111213141516171819203 unmodified lines24252627282930313233343536373839404142434412 unmodified lines57585960616210 unmodified linesfor tokenization and message history management."""import torchfrom openenv.core.env_server.interfaces import Messagefrom openenv.core.env_server.types import Action, Observation, Statefrom pydantic import Fieldclass ChatAction(Action):3 unmodified linesThis interfaces directly with models."""tokens: torch.Tensor = Field(default_factory=lambda: torch.tensor([]))def __post_init__(self):"""Validate required Fields after initialization."""if self.tokens.numel() == 0:raise ValueError("tokens is required and cannot be empty")class ChatState(State):"""State of the ChatEnvironment containing message history."""history_messages: list[Message] = Field(default_factory=list)history_tokens: list[torch.Tensor] = Field(default_factory=list) # Same len as messagesclass ChatObservation(Observation):12 unmodified linestokens = tensor([1, 2, 3, 4, 5, ...]) # tokenized entire conversation"""messages: list[Message] = Field(default_factory=list)tokens: torch.Tensor = Field(default_factory=lambda: torch.tensor([]))# Inherited Fields from Observation ABC: reward, done, metadata10 unmodified lines111213141516171819202122232425262728293031323334353 unmodified lines39404142434445464748495051525354555657585960616212 unmodified lines7576777879808110 unmodified linesfor tokenization and message history management."""from openenv.core.env_server.types import Action, Observation, Statefrom pydantic import Field, field_validatordef _flatten_tokens(value) -> list[int]:"""Coerce nested tensor-like or sequence inputs into a flat token list."""if hasattr(value, "tolist") and callable(value.tolist):value = value.tolist()if isinstance(value, tuple):value = list(value)if isinstance(value, list):flattened: list[int] = []for item in value:flattened.extend(_flatten_tokens(item))return flattenedreturn [int(value)]class ChatAction(Action):3 unmodified linesThis interfaces directly with models."""tokens: list[int] = Field(..., min_length=1)@field_validator("tokens", mode="before")@classmethoddef _coerce_tokens(cls, value):"""Accept either tensors or JSON arrays on the public HTTP surface."""if isinstance(value, (list, tuple)) or hasattr(value, "tolist"):return _flatten_tokens(value)raise TypeError("tokens must be provided as a sequence of token ids")class ChatState(State):"""State of the ChatEnvironment containing message history."""# TODO: revert to list[Message] once openenv-core ships typing_extensions.TypedDict# in interfaces.py and chat_env/pyproject.toml pins to that release.history_messages: list[dict[str, str]] = Field(default_factory=list)history_tokens: list[list[int]] = Field(default_factory=list) # Same len as messagesclass ChatObservation(Observation):12 unmodified linestokens = tensor([1, 2, 3, 4, 5, ...]) # tokenized entire conversation"""# TODO: revert to list[Message] (same as above)messages: list[dict[str, str]] = Field(default_factory=list)tokens: list[int] = Field(default_factory=list)# Inherited Fields from Observation ABC: reward, done, metadata
1234567891011121314Metadata-Version: 2.4Name: openenv-chat-envVersion: 0.1.0Summary: Chat Environment for OpenEnv - LLM-powered conversational agentRequires-Python: >=3.10Requires-Dist: openenv-core[core]>=0.2.3Requires-Dist: fastapi>=0.115.0Requires-Dist: pydantic>=2.0.0Requires-Dist: uvicorn>=0.24.0Requires-Dist: requests>=2.31.0Requires-Dist: transformersProvides-Extra: devRequires-Dist: pytest>=8.0.0; extra == "dev"Requires-Dist: pytest-cov>=4.0.0; extra == "dev"123456789101112131415161718README.md__init__.pyclient.pymodels.pypyproject.toml./__init__.py./client.py./models.pyopenenv_chat_env.egg-info/PKG-INFOopenenv_chat_env.egg-info/SOURCES.txtopenenv_chat_env.egg-info/dependency_links.txtopenenv_chat_env.egg-info/entry_points.txtopenenv_chat_env.egg-info/requires.txtopenenv_chat_env.egg-info/top_level.txtserver/__init__.pyserver/app.pyserver/chat_environment.pyserver/test_chat_env.py1
12[console_scripts]server = chat_env.server.app:main12345678910openenv-core[core]>=0.2.3fastapi>=0.115.0pydantic>=2.0.0uvicorn>=0.24.0requests>=2.31.0transformers
[dev]pytest>=8.0.0pytest-cov>=4.0.01chat_env12345678910111213141516171819202122232425262728293031323334353637# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "openenv-chat-env"version = "0.1.0"description = "Chat Environment for OpenEnv - LLM-powered conversational agent"requires-python = ">=3.10"dependencies = [ "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git@v0.2.3", "fastapi>=0.115.0", "pydantic>=2.0.0", "uvicorn>=0.24.0", "requests>=2.31.0", "transformers",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "pytest-cov>=4.0.0",]
[project.scripts]server = "chat_env.server.app:main"
[tool.setuptools]include-package-data = truepackages = ["chat_env", "chat_env.server"]package-dir = { "chat_env" = ".", "chat_env.server" = "server" }3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940413 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.# Use the standard openenv base image# Built from: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# In GitHub Actions, this is overridden to use the GHCR base imageARG BASE_IMAGE=openenv-base:latestFROM ${BASE_IMAGE}# Install dependencies and run setupCOPY envs/chat_env/server/requirements.txt /tmp/requirements.txtCOPY envs/chat_env/server/install_deps.sh /tmp/install_deps.shRUN chmod +x /tmp/install_deps.sh && \/tmp/install_deps.sh && \rm /tmp/install_deps.sh /tmp/requirements.txt# Set environment variablesENV HF_HOME=/.cacheENV TRANSFORMERS_CACHE=/.cache# Environment variables that can be overridden at runtimeENV TOKENIZER_NAME=gpt2ENV SYSTEM_PROMPT="You are a helpful AI assistant."ENV ENABLE_WEB_INTERFACE=false# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY envs/chat_env/ /app/envs/chat_env/# Copy README for web interface documentationCOPY envs/chat_env/README.md /app/README.md# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD curl -f http://localhost:8000/health || exit 1# Run the FastAPI serverCMD ["uvicorn", "envs.chat_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364653 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ${BASE_IMAGE} AS builderWORKDIR /appCOPY . /app/envWORKDIR /app/envRUN if ! command -v uv >/dev/null 2>&1; then \curl -LsSf https://astral.sh/uv/install.sh | sh && \mv /root/.local/bin/uv /usr/local/bin/uv && \mv /root/.local/bin/uvx /usr/local/bin/uvx; \fiRUN apt-get update && apt-get install -y --no-install-recommends \git \&& rm -rf /var/lib/apt/lists/*RUN --mount=type=cache,target=/root/.cache/uv \if [ -f uv.lock ]; then \uv sync --frozen --no-install-project --no-editable; \else \uv sync --no-install-project --no-editable; \fiRUN --mount=type=cache,target=/root/.cache/uv \if [ -f uv.lock ]; then \uv sync --frozen --no-editable; \else \uv sync --no-editable; \fi# Pre-download GPT-2 tokenizer to avoid permission issues at runtime.# HF_HOME must match the runtime value so the cache is copied to the right place.RUN HF_HOME=/.cache /app/env/.venv/bin/python -c "from transformers import GPT2Tokenizer; GPT2Tokenizer.from_pretrained('gpt2')"# Final runtime stageFROM ${BASE_IMAGE}WORKDIR /appCOPY --from=builder /app/env/.venv /app/.venvCOPY --from=builder /app/env /app/envCOPY --from=builder /.cache /.cacheENV PATH="/app/.venv/bin:$PATH"ENV PYTHONPATH="/app/env:$PYTHONPATH"ENV HF_HOME=/.cacheENV TRANSFORMERS_CACHE=/.cacheENV TOKENIZER_NAME=gpt2ENV SYSTEM_PROMPT="You are a helpful AI assistant."ENV ENABLE_WEB_INTERFACE=trueHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
27 unmodified lines282930313233343542 unmodified lines7879808182838427 unmodified linesfrom openenv.core.env_server import create_appfrom ..models import ChatAction, ChatObservationfrom .chat_environment import ChatEnvironment# Initialize tokenizer based on environment variable42 unmodified lines)if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)27 unmodified lines282930313233343536373839404142434442 unmodified lines878889909192939495969727 unmodified linesfrom openenv.core.env_server import create_app# Support both in-repo and standalone importstry:# In-repo imports (when running from OpenEnv repository)from ..models import ChatAction, ChatObservationfrom .chat_environment import ChatEnvironmentexcept ImportError as e:if "relative import" not in str(e) and "no known parent package" not in str(e):raise# Standalone imports (when running via uvicorn server.app:app)from models import ChatAction, ChatObservationfrom server.chat_environment import ChatEnvironment# Initialize tokenizer based on environment variable42 unmodified lines)def main():import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)if __name__ == "__main__":main()
9 unmodified lines101112131415161 unmodified line1819202122232439 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969723 unmodified lines1211221231241251261271281291301311321339 unmodified lines1431441451461471481491501511521531547 unmodified lines1621631641651661671689 unmodified linesA chat-based environment for LLMs, designed as a blank canvas for conversation and RL."""import torchfrom openenv.core.env_server.interfaces import (Environment,Message,1 unmodified lineTransform,)from ..models import ChatAction, ChatObservation, ChatStateclass ChatEnvironment(Environment):39 unmodified linessystem_tokens = self._tokenize_conversation([system_message])self._state.history_tokens.append(system_tokens)def _tokenize_conversation(self, conversation: list[Message]) -> torch.Tensor:"""Tokenize a conversation with a chat-template fallback for base tokenizers."""try:tokens = self.tokenizer.apply_chat_template(conversation=conversation,tokenize=True,return_tensors="pt", # type: ignore[arg-type])except Exception:# Some tokenizers (e.g. gpt2) do not define `chat_template`.fallback_text = "".join(f"{m['role']}: {m['content']}\n" for m in conversation)if hasattr(self.tokenizer, "encode"):try:tokens = self.tokenizer.encode( # type: ignore[attr-defined]fallback_text,return_tensors="pt",)except TypeError:token_ids = self.tokenizer.encode(fallback_text) # type: ignore[attr-defined]tokens = torch.tensor([token_ids], dtype=torch.long)else:raise ValueError("Tokenizer must support apply_chat_template or encode")if isinstance(tokens, torch.Tensor):return tokensreturn torch.tensor(tokens, dtype=torch.long)def reset(self) -> ChatObservation:"""Reset the environment to initial state.23 unmodified linesReturns:ChatObservation: The updated observation with the new tokens added."""# Store the tokens directly from the actionself._state.history_tokens.append(action.tokens)# Decode tokens to text and add as a message to historydecoded_text = self.tokenizer.decode(action.tokens.squeeze(), skip_special_tokens=True)assistant_message: Message = {"role": "assistant", "content": decoded_text}self._state.history_messages.append(assistant_message)9 unmodified linesChatObservation: Observation with messages and flattened tokens"""if self._state.history_tokens:# Flatten all tokens into a single 1D tensorflattened_tokens = torch.cat((t.flatten() for t in self._state.history_tokens), dim=0)else:flattened_tokens = torch.tensor([])observation = ChatObservation(messages=self._state.history_messages.copy(), # Copy to prevent external mutation7 unmodified lines# If transform returns base Observation, convert back to ChatObservationreturn ChatObservation(messages=getattr(transformed, "messages", []),tokens=getattr(transformed, "tokens", torch.tensor([])),done=transformed.done,reward=transformed.reward,)9 unmodified lines1011121314151 unmodified line17181920212223242526272829303139 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610723 unmodified lines1311321331341351361371381391401411421439 unmodified lines1531541551561571581591601611621631641657 unmodified lines1731741751761771781799 unmodified linesA chat-based environment for LLMs, designed as a blank canvas for conversation and RL."""from openenv.core.env_server.interfaces import (Environment,Message,1 unmodified lineTransform,)# Support both in-repo and standalone importstry:# In-repo imports (when running from OpenEnv repository)from ..models import ChatAction, ChatObservation, ChatStateexcept ImportError as e:if "relative import" not in str(e) and "no known parent package" not in str(e):raise# Standalone imports (when running via uvicorn server.app:app)from models import ChatAction, ChatObservation, ChatStateclass ChatEnvironment(Environment):39 unmodified linessystem_tokens = self._tokenize_conversation([system_message])self._state.history_tokens.append(system_tokens)def _coerce_tokens(self, tokens) -> list[int]:"""Normalize tokenizer outputs into a flat list of ints."""if hasattr(tokens, "tolist") and callable(tokens.tolist):tokens = tokens.tolist()if isinstance(tokens, tuple):tokens = list(tokens)if isinstance(tokens, list):flattened: list[int] = []for token in tokens:flattened.extend(self._coerce_tokens(token))return flattenedreturn [int(tokens)]def _tokenize_conversation(self, conversation: list[Message]) -> list[int]:"""Tokenize a conversation with a chat-template fallback for base tokenizers."""try:tokens = self.tokenizer.apply_chat_template(conversation=conversation, tokenize=True)except Exception:# Some tokenizers (e.g. gpt2) do not define `chat_template`.fallback_text = "".join(f"{m['role']}: {m['content']}\n" for m in conversation)if hasattr(self.tokenizer, "encode"):tokens = self.tokenizer.encode(fallback_text) # type: ignore[attr-defined]else:raise ValueError("Tokenizer must support apply_chat_template or encode")return self._coerce_tokens(tokens)def reset(self) -> ChatObservation:"""Reset the environment to initial state.23 unmodified linesReturns:ChatObservation: The updated observation with the new tokens added."""action_tokens = [int(token) for token in action.tokens]# Store the tokens directly from the actionself._state.history_tokens.append(action_tokens)# Decode tokens to text and add as a message to historydecoded_text = self.tokenizer.decode(action_tokens, skip_special_tokens=True)assistant_message: Message = {"role": "assistant", "content": decoded_text}self._state.history_messages.append(assistant_message)9 unmodified linesChatObservation: Observation with messages and flattened tokens"""if self._state.history_tokens:flattened_tokens = [tokenfor token_list in self._state.history_tokensfor token in token_list]else:flattened_tokens = []observation = ChatObservation(messages=self._state.history_messages.copy(), # Copy to prevent external mutation7 unmodified lines# If transform returns base Observation, convert back to ChatObservationreturn ChatObservation(messages=getattr(transformed, "messages", []),tokens=self._coerce_tokens(getattr(transformed, "tokens", [])),done=transformed.done,reward=transformed.reward,)
12torchtransformers1transformers
9 unmodified lines1011121314151610 unmodified lines27282930313233343536373839404142434445464715 unmodified lines63646566676869707172737476 unmodified lines1511521531541551561571581591601611621632 unmodified lines1661671681691701711721 unmodified line1741751761771781791801818 unmodified lines1901911921931941951964 unmodified lines2012022032042052062073 unmodified lines2112122132142152162172182192209 unmodified linesProper unit tests with assertions to verify correct behavior."""import torchfrom openenv.core.env_server.interfaces import Messagefrom ..models import ChatAction10 unmodified linesreturn_tensors: str | None = None,**kwargs,):"""Mock implementation that creates deterministic token tensors from text."""# Concatenate all message contenttext = " ".join([msg["content"] for msg in conversation])# Create deterministic tokens based on text content# Use character codes modulo 256 to get valid token IDstokens = [ord(c) % 256 for c in text]if return_tensors == "pt":return torch.tensor([tokens])return tokensdef decode(self, token_ids, skip_special_tokens: bool = False, **kwargs) -> str:"""Mock decode that reverses the encoding process."""if isinstance(token_ids, torch.Tensor):token_ids = token_ids.tolist()# Reverse the encoding: convert tokens back to characters15 unmodified linesaction2 = env.message_to_action(message2)# Verify tokens are identicalassert torch.equal(action1.tokens, action2.tokens), ("Same message should produce identical tokens")# Verify tokens are not emptyassert action1.tokens.numel() > 0, "Tokens should not be empty"print("✓ test_tokenization_consistency passed")76 unmodified linesenv = ChatEnvironment(tokenizer=tokenizer)obs = env.reset()initial_token_count = obs.tokens.numel()# Step with first messagemessage1 = {"role": "user", "content": "Hi"}action1 = env.message_to_action(message1)obs1 = env.step(action1)token_count_1 = obs1.tokens.numel()# Tokens should increaseassert token_count_1 > initial_token_count, "Token count should increase after step"2 unmodified linesmessage2 = {"role": "assistant", "content": "Hello there"}action2 = env.message_to_action(message2)obs2 = env.step(action2)token_count_2 = obs2.tokens.numel()# Tokens should continue to accumulateassert token_count_2 > token_count_1, (1 unmodified line)# Verify tokens are the concatenation of both messagesexpected_tokens = torch.cat([action1.tokens.flatten(), action2.tokens.flatten()])assert torch.equal(obs2.tokens, expected_tokens), ("Tokens should be concatenation of all actions")8 unmodified linesenv.reset()# Create raw tokensraw_tokens = torch.tensor([[72, 101, 108, 108, 111]]) # ASCII for "Hello"action = ChatAction(tokens=raw_tokens)# Step with raw tokens4 unmodified linesassert obs.messages[0]["role"] == "assistant", "Should default to assistant role"# Verify tokens match what we sent (flattened)assert torch.equal(obs.tokens, raw_tokens.flatten()), ("Observation tokens should match input tokens")3 unmodified linesdef test_empty_tokens_validation():"""Test that empty tokens raise a ValueError."""try:action = ChatAction(tokens=torch.tensor([]))assert False, "Should have raised ValueError for empty tokens"except ValueError as e:assert "empty" in str(e).lower(), "Error message should mention empty tokens"print("✓ test_empty_tokens_validation passed")9 unmodified lines10111213141510 unmodified lines26272829303132333435363738394041424344454615 unmodified lines62636465666768697071727376 unmodified lines1501511521531541551561571581591601611622 unmodified lines1651661671681691701711 unmodified line1731741751761771781791808 unmodified lines1891901911921931941954 unmodified lines2002012022032042052063 unmodified lines2102112122132142152162172182192202219 unmodified linesProper unit tests with assertions to verify correct behavior."""from openenv.core.env_server.interfaces import Messagefrom ..models import ChatAction10 unmodified linesreturn_tensors: str | None = None,**kwargs,):"""Mock implementation that creates deterministic tokens from text."""# Concatenate all message contentdel tokenize, return_tensors, kwargstext = " ".join([msg["content"] for msg in conversation])# Create deterministic tokens based on text content# Use character codes modulo 256 to get valid token IDstokens = [ord(c) % 256 for c in text]return tokensdef decode(self, token_ids, skip_special_tokens: bool = False, **kwargs) -> str:"""Mock decode that reverses the encoding process."""del skip_special_tokens, kwargsif hasattr(token_ids, "tolist") and callable(token_ids.tolist):token_ids = token_ids.tolist()# Reverse the encoding: convert tokens back to characters15 unmodified linesaction2 = env.message_to_action(message2)# Verify tokens are identicalassert action1.tokens == action2.tokens, ("Same message should produce identical tokens")# Verify tokens are not emptyassert len(action1.tokens) > 0, "Tokens should not be empty"print("✓ test_tokenization_consistency passed")76 unmodified linesenv = ChatEnvironment(tokenizer=tokenizer)obs = env.reset()initial_token_count = len(obs.tokens)# Step with first messagemessage1 = {"role": "user", "content": "Hi"}action1 = env.message_to_action(message1)obs1 = env.step(action1)token_count_1 = len(obs1.tokens)# Tokens should increaseassert token_count_1 > initial_token_count, "Token count should increase after step"2 unmodified linesmessage2 = {"role": "assistant", "content": "Hello there"}action2 = env.message_to_action(message2)obs2 = env.step(action2)token_count_2 = len(obs2.tokens)# Tokens should continue to accumulateassert token_count_2 > token_count_1, (1 unmodified line)# Verify tokens are the concatenation of both messagesexpected_tokens = action1.tokens + action2.tokensassert obs2.tokens == expected_tokens, ("Tokens should be concatenation of all actions")8 unmodified linesenv.reset()# Create raw tokensraw_tokens = [[72, 101, 108, 108, 111]] # ASCII for "Hello"action = ChatAction(tokens=raw_tokens)# Step with raw tokens4 unmodified linesassert obs.messages[0]["role"] == "assistant", "Should default to assistant role"# Verify tokens match what we sent (flattened)assert obs.tokens == [72, 101, 108, 108, 111], ("Observation tokens should match input tokens")3 unmodified linesdef test_empty_tokens_validation():"""Test that empty tokens raise a ValueError."""try:action = ChatAction(tokens=[])assert False, "Should have raised ValueError for empty tokens"except ValueError as e:assert "at least 1 item" in str(e).lower(), ("Error message should mention the minimum token count")print("✓ test_empty_tokens_validation passed")
10 unmodified lines111213141516171819203 unmodified lines24252627282930313233343536373839404142434412 unmodified lines57585960616210 unmodified linesfor tokenization and message history management."""import torchfrom openenv.core.env_server.interfaces import Messagefrom openenv.core.env_server.types import Action, Observation, Statefrom pydantic import Fieldclass ChatAction(Action):3 unmodified linesThis interfaces directly with models."""tokens: torch.Tensor = Field(default_factory=lambda: torch.tensor([]))def __post_init__(self):"""Validate required Fields after initialization."""if self.tokens.numel() == 0:raise ValueError("tokens is required and cannot be empty")class ChatState(State):"""State of the ChatEnvironment containing message history."""history_messages: list[Message] = Field(default_factory=list)history_tokens: list[torch.Tensor] = Field(default_factory=list) # Same len as messagesclass ChatObservation(Observation):12 unmodified linestokens = tensor([1, 2, 3, 4, 5, ...]) # tokenized entire conversation"""messages: list[Message] = Field(default_factory=list)tokens: torch.Tensor = Field(default_factory=lambda: torch.tensor([]))# Inherited Fields from Observation ABC: reward, done, metadata10 unmodified lines111213141516171819202122232425262728293031323334353 unmodified lines39404142434445464748495051525354555657585960616212 unmodified lines7576777879808110 unmodified linesfor tokenization and message history management."""from openenv.core.env_server.types import Action, Observation, Statefrom pydantic import Field, field_validatordef _flatten_tokens(value) -> list[int]:"""Coerce nested tensor-like or sequence inputs into a flat token list."""if hasattr(value, "tolist") and callable(value.tolist):value = value.tolist()if isinstance(value, tuple):value = list(value)if isinstance(value, list):flattened: list[int] = []for item in value:flattened.extend(_flatten_tokens(item))return flattenedreturn [int(value)]class ChatAction(Action):3 unmodified linesThis interfaces directly with models."""tokens: list[int] = Field(..., min_length=1)@field_validator("tokens", mode="before")@classmethoddef _coerce_tokens(cls, value):"""Accept either tensors or JSON arrays on the public HTTP surface."""if isinstance(value, (list, tuple)) or hasattr(value, "tolist"):return _flatten_tokens(value)raise TypeError("tokens must be provided as a sequence of token ids")class ChatState(State):"""State of the ChatEnvironment containing message history."""# TODO: revert to list[Message] once openenv-core ships typing_extensions.TypedDict# in interfaces.py and chat_env/pyproject.toml pins to that release.history_messages: list[dict[str, str]] = Field(default_factory=list)history_tokens: list[list[int]] = Field(default_factory=list) # Same len as messagesclass ChatObservation(Observation):12 unmodified linestokens = tensor([1, 2, 3, 4, 5, ...]) # tokenized entire conversation"""# TODO: revert to list[Message] (same as above)messages: list[dict[str, str]] = Field(default_factory=list)tokens: list[int] = Field(default_factory=list)# Inherited Fields from Observation ABC: reward, done, metadata
1234567891011121314Metadata-Version: 2.4Name: openenv-chat-envVersion: 0.1.0Summary: Chat Environment for OpenEnv - LLM-powered conversational agentRequires-Python: >=3.10Requires-Dist: openenv-core[core]>=0.2.3Requires-Dist: fastapi>=0.115.0Requires-Dist: pydantic>=2.0.0Requires-Dist: uvicorn>=0.24.0Requires-Dist: requests>=2.31.0Requires-Dist: transformersProvides-Extra: devRequires-Dist: pytest>=8.0.0; extra == "dev"Requires-Dist: pytest-cov>=4.0.0; extra == "dev"123456789101112131415161718README.md__init__.pyclient.pymodels.pypyproject.toml./__init__.py./client.py./models.pyopenenv_chat_env.egg-info/PKG-INFOopenenv_chat_env.egg-info/SOURCES.txtopenenv_chat_env.egg-info/dependency_links.txtopenenv_chat_env.egg-info/entry_points.txtopenenv_chat_env.egg-info/requires.txtopenenv_chat_env.egg-info/top_level.txtserver/__init__.pyserver/app.pyserver/chat_environment.pyserver/test_chat_env.py1
12[console_scripts]server = chat_env.server.app:main12345678910openenv-core[core]>=0.2.3fastapi>=0.115.0pydantic>=2.0.0uvicorn>=0.24.0requests>=2.31.0transformers
[dev]pytest>=8.0.0pytest-cov>=4.0.01chat_env123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"[project]name = "openenv-core"version = "0.2.2.dev0"description = "A unified framework for reinforcement learning environments"readme = "README.md"requires-python = ">=3.10"dependencies = [# Core shared dependencies - minimal set required for all environments# Heavy dependencies (torch, numpy, smolagents, etc.) should be in# individual environment pyproject.toml files"fastapi>=0.104.0","pydantic>=2.0.0","uvicorn>=0.24.0","requests>=2.25.0",# CLI dependencies"typer>=0.9.0","rich>=13.0.0","pyyaml>=6.0","huggingface_hub>=0.20.0","openai>=2.7.2","tomli>=2.3.0","tomli-w>=1.2.0","websockets>=15.0.1",# MCP support"fastmcp>=3.0.0",# Web UI dependencies"gradio>=4.0.0",][project.optional-dependencies]core = ["fastapi>=0.104.0","pydantic>=2.0.0","uvicorn>=0.24.0","requests>=2.25.0","websockets>=15.0.1",]cli = ["typer>=0.9.0","rich>=13.0.0","pyyaml>=6.0","huggingface_hub>=0.20.0","openai>=2.7.2","tomli>=2.3.0","tomli-w>=1.2.0",]docs = ["sphinx==7.2.6","pytorch-sphinx-theme2","sphinxcontrib.katex==0.9.10","docutils>=0.18.1,<0.21","sphinx-design==0.6.1","sphinxcontrib-mermaid==1.0.0","myst-parser","sphinxext-opengraph","sphinx-sitemap==2.7.1","sphinx-gallery>=0.14.0","matplotlib","nest-asyncio","smolagents",]all = ["openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git@main","openenv-core[cli]",]daytona = ["daytona>=0.136.0","pyyaml>=6.0",]inspect = ["inspect-ai>=0.3.0",][project.scripts]openenv = "openenv.cli.__main__:main"[tool.setuptools]package-dir = {"" = "src"}include-package-data = true[tool.setuptools.package-data]"openenv.cli" = ["templates/**/*"][tool.setuptools.packages.find]where = ["src"][tool.coverage.run]omit = ["openenv/cli/templates/**","**/templates/**","openenv/cli/__main__.py",][tool.coverage.report]exclude_lines = ["pragma: no cover","def __repr__","raise AssertionError","raise NotImplementedError","if __name__ == .__main__.:","if TYPE_CHECKING:",][tool.pytest.ini_options]asyncio_mode = "auto"asyncio_default_fixture_loop_scope = "function"markers = ["docker: Tests that require Docker to be running","network: Tests that require network access (HuggingFace, etc.)","integration: Integration tests with external resources",][dependency-groups]dev = ["ruff>=0.14.0","usort>=1.1.0","pytest>=7.0","pytest-asyncio>=0.21",][tool.usort]# Disable first_party auto-detection so all non-stdlib imports land in# the same "third_party" bucket (the default_category). This matches# pyfmt's usort behavior inside arc f, which groups openenv.* and env# package imports together without blank-line separators.first_party_detection = false[tool.ruff]line-length = 88[tool.ruff.lint]select = ["E", "F", "W"]ignore = ["E402", # Module level import not at top of file (needed for pytest.importorskip patterns)"E501", # Line too long (not enforced previously, would require large refactor)][tool.ruff.lint.per-file-ignores]# Context manager variables that are intentionally unused"tests/envs/test_websockets.py" = ["F841"]"tests/test_cli/test_push.py" = ["F841"]# Compatibility shim module"src/openenv_core/__init__.py" = ["F401"]12345678910111213141516171819202122232425262728293031323334353637# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"[project]name = "openenv-chat-env"version = "0.1.0"description = "Chat Environment for OpenEnv - LLM-powered conversational agent"requires-python = ">=3.10"dependencies = ["openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git@v0.2.3","fastapi>=0.115.0","pydantic>=2.0.0","uvicorn>=0.24.0","requests>=2.31.0","transformers",][project.optional-dependencies]dev = ["pytest>=8.0.0","pytest-cov>=4.0.0",][project.scripts]server = "chat_env.server.app:main"[tool.setuptools]include-package-data = truepackages = ["chat_env", "chat_env.server"]package-dir = { "chat_env" = ".", "chat_env.server" = "server" }
3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940413 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.# Use the standard openenv base image# Built from: docker build -t openenv-base:latest -f src/openenv/core/containers/images/Dockerfile .# In GitHub Actions, this is overridden to use the GHCR base imageARG BASE_IMAGE=openenv-base:latestFROM ${BASE_IMAGE}# Install dependencies and run setupCOPY envs/chat_env/server/requirements.txt /tmp/requirements.txtCOPY envs/chat_env/server/install_deps.sh /tmp/install_deps.shRUN chmod +x /tmp/install_deps.sh && \/tmp/install_deps.sh && \rm /tmp/install_deps.sh /tmp/requirements.txt# Set environment variablesENV HF_HOME=/.cacheENV TRANSFORMERS_CACHE=/.cache# Environment variables that can be overridden at runtimeENV TOKENIZER_NAME=gpt2ENV SYSTEM_PROMPT="You are a helpful AI assistant."ENV ENABLE_WEB_INTERFACE=false# Copy only what's needed for this environmentCOPY src/core/ /app/src/core/COPY envs/chat_env/ /app/envs/chat_env/# Copy README for web interface documentationCOPY envs/chat_env/README.md /app/README.md# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD curl -f http://localhost:8000/health || exit 1# Run the FastAPI serverCMD ["uvicorn", "envs.chat_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364653 unmodified lines# This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ${BASE_IMAGE} AS builderWORKDIR /appCOPY . /app/envWORKDIR /app/envRUN if ! command -v uv >/dev/null 2>&1; then \curl -LsSf https://astral.sh/uv/install.sh | sh && \mv /root/.local/bin/uv /usr/local/bin/uv && \mv /root/.local/bin/uvx /usr/local/bin/uvx; \fiRUN apt-get update && apt-get install -y --no-install-recommends \git \&& rm -rf /var/lib/apt/lists/*RUN --mount=type=cache,target=/root/.cache/uv \if [ -f uv.lock ]; then \uv sync --frozen --no-install-project --no-editable; \else \uv sync --no-install-project --no-editable; \fiRUN --mount=type=cache,target=/root/.cache/uv \if [ -f uv.lock ]; then \uv sync --frozen --no-editable; \else \uv sync --no-editable; \fi# Pre-download GPT-2 tokenizer to avoid permission issues at runtime.# HF_HOME must match the runtime value so the cache is copied to the right place.RUN HF_HOME=/.cache /app/env/.venv/bin/python -c "from transformers import GPT2Tokenizer; GPT2Tokenizer.from_pretrained('gpt2')"# Final runtime stageFROM ${BASE_IMAGE}WORKDIR /appCOPY --from=builder /app/env/.venv /app/.venvCOPY --from=builder /app/env /app/envCOPY --from=builder /.cache /.cacheENV PATH="/app/.venv/bin:$PATH"ENV PYTHONPATH="/app/env:$PYTHONPATH"ENV HF_HOME=/.cacheENV TRANSFORMERS_CACHE=/.cacheENV TOKENIZER_NAME=gpt2ENV SYSTEM_PROMPT="You are a helpful AI assistant."ENV ENABLE_WEB_INTERFACE=trueHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
27 unmodified lines282930313233343542 unmodified lines7879808182838427 unmodified linesfrom openenv.core.env_server import create_appfrom ..models import ChatAction, ChatObservationfrom .chat_environment import ChatEnvironment# Initialize tokenizer based on environment variable42 unmodified lines)if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)27 unmodified lines282930313233343536373839404142434442 unmodified lines878889909192939495969727 unmodified linesfrom openenv.core.env_server import create_app# Support both in-repo and standalone importstry:# In-repo imports (when running from OpenEnv repository)from ..models import ChatAction, ChatObservationfrom .chat_environment import ChatEnvironmentexcept ImportError as e:if "relative import" not in str(e) and "no known parent package" not in str(e):raise# Standalone imports (when running via uvicorn server.app:app)from models import ChatAction, ChatObservationfrom server.chat_environment import ChatEnvironment# Initialize tokenizer based on environment variable42 unmodified lines)def main():import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)if __name__ == "__main__":main()
9 unmodified lines101112131415161 unmodified line1819202122232439 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969723 unmodified lines1211221231241251261271281291301311321339 unmodified lines1431441451461471481491501511521531547 unmodified lines1621631641651661671689 unmodified linesA chat-based environment for LLMs, designed as a blank canvas for conversation and RL."""import torchfrom openenv.core.env_server.interfaces import (Environment,Message,1 unmodified lineTransform,)from ..models import ChatAction, ChatObservation, ChatStateclass ChatEnvironment(Environment):39 unmodified linessystem_tokens = self._tokenize_conversation([system_message])self._state.history_tokens.append(system_tokens)def _tokenize_conversation(self, conversation: list[Message]) -> torch.Tensor:"""Tokenize a conversation with a chat-template fallback for base tokenizers."""try:tokens = self.tokenizer.apply_chat_template(conversation=conversation,tokenize=True,return_tensors="pt", # type: ignore[arg-type])except Exception:# Some tokenizers (e.g. gpt2) do not define `chat_template`.fallback_text = "".join(f"{m['role']}: {m['content']}\n" for m in conversation)if hasattr(self.tokenizer, "encode"):try:tokens = self.tokenizer.encode( # type: ignore[attr-defined]fallback_text,return_tensors="pt",)except TypeError:token_ids = self.tokenizer.encode(fallback_text) # type: ignore[attr-defined]tokens = torch.tensor([token_ids], dtype=torch.long)else:raise ValueError("Tokenizer must support apply_chat_template or encode")if isinstance(tokens, torch.Tensor):return tokensreturn torch.tensor(tokens, dtype=torch.long)def reset(self) -> ChatObservation:"""Reset the environment to initial state.23 unmodified linesReturns:ChatObservation: The updated observation with the new tokens added."""# Store the tokens directly from the actionself._state.history_tokens.append(action.tokens)# Decode tokens to text and add as a message to historydecoded_text = self.tokenizer.decode(action.tokens.squeeze(), skip_special_tokens=True)assistant_message: Message = {"role": "assistant", "content": decoded_text}self._state.history_messages.append(assistant_message)9 unmodified linesChatObservation: Observation with messages and flattened tokens"""if self._state.history_tokens:# Flatten all tokens into a single 1D tensorflattened_tokens = torch.cat((t.flatten() for t in self._state.history_tokens), dim=0)else:flattened_tokens = torch.tensor([])observation = ChatObservation(messages=self._state.history_messages.copy(), # Copy to prevent external mutation7 unmodified lines# If transform returns base Observation, convert back to ChatObservationreturn ChatObservation(messages=getattr(transformed, "messages", []),tokens=getattr(transformed, "tokens", torch.tensor([])),done=transformed.done,reward=transformed.reward,)9 unmodified lines1011121314151 unmodified line17181920212223242526272829303139 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610723 unmodified lines1311321331341351361371381391401411421439 unmodified lines1531541551561571581591601611621631641657 unmodified lines1731741751761771781799 unmodified linesA chat-based environment for LLMs, designed as a blank canvas for conversation and RL."""from openenv.core.env_server.interfaces import (Environment,Message,1 unmodified lineTransform,)# Support both in-repo and standalone importstry:# In-repo imports (when running from OpenEnv repository)from ..models import ChatAction, ChatObservation, ChatStateexcept ImportError as e:if "relative import" not in str(e) and "no known parent package" not in str(e):raise# Standalone imports (when running via uvicorn server.app:app)from models import ChatAction, ChatObservation, ChatStateclass ChatEnvironment(Environment):39 unmodified linessystem_tokens = self._tokenize_conversation([system_message])self._state.history_tokens.append(system_tokens)def _coerce_tokens(self, tokens) -> list[int]:"""Normalize tokenizer outputs into a flat list of ints."""if hasattr(tokens, "tolist") and callable(tokens.tolist):tokens = tokens.tolist()if isinstance(tokens, tuple):tokens = list(tokens)if isinstance(tokens, list):flattened: list[int] = []for token in tokens:flattened.extend(self._coerce_tokens(token))return flattenedreturn [int(tokens)]def _tokenize_conversation(self, conversation: list[Message]) -> list[int]:"""Tokenize a conversation with a chat-template fallback for base tokenizers."""try:tokens = self.tokenizer.apply_chat_template(conversation=conversation, tokenize=True)except Exception:# Some tokenizers (e.g. gpt2) do not define `chat_template`.fallback_text = "".join(f"{m['role']}: {m['content']}\n" for m in conversation)if hasattr(self.tokenizer, "encode"):tokens = self.tokenizer.encode(fallback_text) # type: ignore[attr-defined]else:raise ValueError("Tokenizer must support apply_chat_template or encode")return self._coerce_tokens(tokens)def reset(self) -> ChatObservation:"""Reset the environment to initial state.23 unmodified linesReturns:ChatObservation: The updated observation with the new tokens added."""action_tokens = [int(token) for token in action.tokens]# Store the tokens directly from the actionself._state.history_tokens.append(action_tokens)# Decode tokens to text and add as a message to historydecoded_text = self.tokenizer.decode(action_tokens, skip_special_tokens=True)assistant_message: Message = {"role": "assistant", "content": decoded_text}self._state.history_messages.append(assistant_message)9 unmodified linesChatObservation: Observation with messages and flattened tokens"""if self._state.history_tokens:flattened_tokens = [tokenfor token_list in self._state.history_tokensfor token in token_list]else:flattened_tokens = []observation = ChatObservation(messages=self._state.history_messages.copy(), # Copy to prevent external mutation7 unmodified lines# If transform returns base Observation, convert back to ChatObservationreturn ChatObservation(messages=getattr(transformed, "messages", []),tokens=self._coerce_tokens(getattr(transformed, "tokens", [])),done=transformed.done,reward=transformed.reward,)
12torchtransformers1transformers
9 unmodified lines1011121314151610 unmodified lines27282930313233343536373839404142434445464715 unmodified lines63646566676869707172737476 unmodified lines1511521531541551561571581591601611621632 unmodified lines1661671681691701711721 unmodified line1741751761771781791801818 unmodified lines1901911921931941951964 unmodified lines2012022032042052062073 unmodified lines2112122132142152162172182192209 unmodified linesProper unit tests with assertions to verify correct behavior."""import torchfrom openenv.core.env_server.interfaces import Messagefrom ..models import ChatAction10 unmodified linesreturn_tensors: str | None = None,**kwargs,):"""Mock implementation that creates deterministic token tensors from text."""# Concatenate all message contenttext = " ".join([msg["content"] for msg in conversation])# Create deterministic tokens based on text content# Use character codes modulo 256 to get valid token IDstokens = [ord(c) % 256 for c in text]if return_tensors == "pt":return torch.tensor([tokens])return tokensdef decode(self, token_ids, skip_special_tokens: bool = False, **kwargs) -> str:"""Mock decode that reverses the encoding process."""if isinstance(token_ids, torch.Tensor):token_ids = token_ids.tolist()# Reverse the encoding: convert tokens back to characters15 unmodified linesaction2 = env.message_to_action(message2)# Verify tokens are identicalassert torch.equal(action1.tokens, action2.tokens), ("Same message should produce identical tokens")# Verify tokens are not emptyassert action1.tokens.numel() > 0, "Tokens should not be empty"print("✓ test_tokenization_consistency passed")76 unmodified linesenv = ChatEnvironment(tokenizer=tokenizer)obs = env.reset()initial_token_count = obs.tokens.numel()# Step with first messagemessage1 = {"role": "user", "content": "Hi"}action1 = env.message_to_action(message1)obs1 = env.step(action1)token_count_1 = obs1.tokens.numel()# Tokens should increaseassert token_count_1 > initial_token_count, "Token count should increase after step"2 unmodified linesmessage2 = {"role": "assistant", "content": "Hello there"}action2 = env.message_to_action(message2)obs2 = env.step(action2)token_count_2 = obs2.tokens.numel()# Tokens should continue to accumulateassert token_count_2 > token_count_1, (1 unmodified line)# Verify tokens are the concatenation of both messagesexpected_tokens = torch.cat([action1.tokens.flatten(), action2.tokens.flatten()])assert torch.equal(obs2.tokens, expected_tokens), ("Tokens should be concatenation of all actions")8 unmodified linesenv.reset()# Create raw tokensraw_tokens = torch.tensor([[72, 101, 108, 108, 111]]) # ASCII for "Hello"action = ChatAction(tokens=raw_tokens)# Step with raw tokens4 unmodified linesassert obs.messages[0]["role"] == "assistant", "Should default to assistant role"# Verify tokens match what we sent (flattened)assert torch.equal(obs.tokens, raw_tokens.flatten()), ("Observation tokens should match input tokens")3 unmodified linesdef test_empty_tokens_validation():"""Test that empty tokens raise a ValueError."""try:action = ChatAction(tokens=torch.tensor([]))assert False, "Should have raised ValueError for empty tokens"except ValueError as e:assert "empty" in str(e).lower(), "Error message should mention empty tokens"print("✓ test_empty_tokens_validation passed")9 unmodified lines10111213141510 unmodified lines26272829303132333435363738394041424344454615 unmodified lines62636465666768697071727376 unmodified lines1501511521531541551561571581591601611622 unmodified lines1651661671681691701711 unmodified line1731741751761771781791808 unmodified lines1891901911921931941954 unmodified lines2002012022032042052063 unmodified lines2102112122132142152162172182192202219 unmodified linesProper unit tests with assertions to verify correct behavior."""from openenv.core.env_server.interfaces import Messagefrom ..models import ChatAction10 unmodified linesreturn_tensors: str | None = None,**kwargs,):"""Mock implementation that creates deterministic tokens from text."""# Concatenate all message contentdel tokenize, return_tensors, kwargstext = " ".join([msg["content"] for msg in conversation])# Create deterministic tokens based on text content# Use character codes modulo 256 to get valid token IDstokens = [ord(c) % 256 for c in text]return tokensdef decode(self, token_ids, skip_special_tokens: bool = False, **kwargs) -> str:"""Mock decode that reverses the encoding process."""del skip_special_tokens, kwargsif hasattr(token_ids, "tolist") and callable(token_ids.tolist):token_ids = token_ids.tolist()# Reverse the encoding: convert tokens back to characters15 unmodified linesaction2 = env.message_to_action(message2)# Verify tokens are identicalassert action1.tokens == action2.tokens, ("Same message should produce identical tokens")# Verify tokens are not emptyassert len(action1.tokens) > 0, "Tokens should not be empty"print("✓ test_tokenization_consistency passed")76 unmodified linesenv = ChatEnvironment(tokenizer=tokenizer)obs = env.reset()initial_token_count = len(obs.tokens)# Step with first messagemessage1 = {"role": "user", "content": "Hi"}action1 = env.message_to_action(message1)obs1 = env.step(action1)token_count_1 = len(obs1.tokens)# Tokens should increaseassert token_count_1 > initial_token_count, "Token count should increase after step"2 unmodified linesmessage2 = {"role": "assistant", "content": "Hello there"}action2 = env.message_to_action(message2)obs2 = env.step(action2)token_count_2 = len(obs2.tokens)# Tokens should continue to accumulateassert token_count_2 > token_count_1, (1 unmodified line)# Verify tokens are the concatenation of both messagesexpected_tokens = action1.tokens + action2.tokensassert obs2.tokens == expected_tokens, ("Tokens should be concatenation of all actions")8 unmodified linesenv.reset()# Create raw tokensraw_tokens = [[72, 101, 108, 108, 111]] # ASCII for "Hello"action = ChatAction(tokens=raw_tokens)# Step with raw tokens4 unmodified linesassert obs.messages[0]["role"] == "assistant", "Should default to assistant role"# Verify tokens match what we sent (flattened)assert obs.tokens == [72, 101, 108, 108, 111], ("Observation tokens should match input tokens")3 unmodified linesdef test_empty_tokens_validation():"""Test that empty tokens raise a ValueError."""try:action = ChatAction(tokens=[])assert False, "Should have raised ValueError for empty tokens"except ValueError as e:assert "at least 1 item" in str(e).lower(), ("Error message should mention the minimum token count")print("✓ test_empty_tokens_validation passed")
15 unmodified lines1617181920212223242526177 unmodified lines2042052062072082092102111 unmodified line213214215216217218102 unmodified lines32132232332432532632732832933033133210 unmodified lines34334434534634734834935032 unmodified lines38338438538638738869 unmodified lines45845946046146246362 unmodified lines5265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775782 unmodified lines58158258358458558658758858959059159259359459518 unmodified lines61461561661761861917 unmodified lines637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678252 unmodified lines93193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105015 unmodified lines10661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120075 unmodified lines127612771278127912801281128215 unmodified linesimport asyncioimport inspectimport jsonimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Callable, Dict, Optional, Typefrom fastapi import (Body,177 unmodified linesself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Environment] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()1 unmodified line# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)def _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.102 unmodified lines)raise EnvironmentFactoryError(factory_name) from easync with self._session_lock:self._sessions[session_id] = envself._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=current_time,step_count=0,environment_type=type(env).__name__,)10 unmodified linesasync with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:32 unmodified linesif increment_step:self._session_info[session_id].step_count += 1def get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.69 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),62 unmodified lines# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest, session_env: Optional[Environment] = None) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format."""method = request.methodrequest_id = request.id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelse:_env = self._env_factory()should_close = Truetry:if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump() if hasattr(t, "model_dump") else dict(t)for t in tools]},request_id=request_id,)elif method == McpMethod.TOOLS_CALL:params = request.paramstool_name = params.get("name")arguments = params.get("arguments", {})if not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",2 unmodified linesif not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Missing 'name' in params",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)# Ensure result is JSON serializable18 unmodified linesrequest_id=request_id,)finally:if should_close:_env.close()17 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request, session_env=session_env)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass252 unmodified linesJsonRpcErrorCode.PARSE_ERROR).model_dump()method = request.methodparams = request.paramsrequest_id = request.id# Create a temporary environment for MCP access_env = self._env_factory()try:# Check if environment supports MCPif not hasattr(_env, "mcp_client") and not hasattr(_env, "mcp_server"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,).model_dump()if method == McpMethod.TOOLS_LIST:# List tools from MCP serverif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,).model_dump()elif hasattr(_env, "mcp_server") and _env.mcp_server:# Use server directlytools = []for tool_name, tool in get_server_tools(_env.mcp_server).items():tool_dict = {"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},}tools.append(tool_dict)return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'name' is required",request_id=request_id,).model_dump()# Call tool via MCPif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)elif hasattr(_env, "mcp_server") and _env.mcp_server:# Call tool directly on FastMCP serverserver_tools = get_server_tools(_env.mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()# Make result JSON serializableserializable_result = _make_json_serializable(result)return JsonRpcResponse.success(result=serializable_result,request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,f"Method not found: {method}",request_id=request_id,).model_dump()except Exception as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=request_id,).model_dump()finally:_env.close()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")15 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await self._run_in_session_executor(session_id, session_env.reset, **valid_kwargs)self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = await self._run_in_session_executor(session_id, session_env.step, action)self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass75 unmodified linesfrom .web_interface import create_web_interface_appreturn create_web_interface_app(env,action_cls,observation_cls,env_name,15 unmodified lines161718192021222324252627282930177 unmodified lines2082092102112122132142152161 unmodified line218219220221222223224225226227228229230231102 unmodified lines33433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937010 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240340440540640732 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949069 unmodified lines56056156256356456556656756856957057157257357457557657757857962 unmodified lines6426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548552 unmodified lines85885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790818 unmodified lines92792892993093193293393493593693717 unmodified lines95595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013252 unmodified lines1266126712681269127012711272127315 unmodified lines1289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145575 unmodified lines153115321533153415351536153715 unmodified linesimport asyncioimport inspectimport jsonimport loggingimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import AsyncExitStackfrom typing import Any, AsyncContextManager, Callable, cast, Dict, Optional, Type_MISSING = object()from fastapi import (Body,177 unmodified linesself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Optional[Environment]] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_stacks: Dict[str, AsyncExitStack] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()1 unmodified line# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)# Idle session reaper configuration.# Timeout is taken from ConcurrencyConfig.session_timeout;# None means no timeout (default — reaper is a no-op).self._session_idle_timeout_s: Optional[float] = (self._concurrency_config.session_timeout)self._reaper_task: Optional[asyncio.Task[None]] = Nonedef _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.102 unmodified lines)raise EnvironmentFactoryError(factory_name) from e# Hold the MCP session open for the lifetime of this session,# matching the WebSocket path's AsyncExitStack pattern. This# prevents per-request MCP transport teardown/reconnection and# preserves FastMCP session state (ctx.set_state / ctx.get_state)# across HTTP calls within the same OpenEnv session.stack = AsyncExitStack()try:mcp_session_factory = getattr(env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)except Exception:# MCP transport failed to start — clean up the reserved slot,# the env, and the executor so they don't leak permanently# against _max_concurrent_envs.await stack.aclose() # best-effortasync with self._session_lock:self._sessions.pop(session_id, None)self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor)raiseasync with self._session_lock:self._sessions[session_id] = envself._session_stacks[session_id] = stacknow = time.time()self._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=now,step_count=0,environment_type=type(env).__name__,)10 unmodified linesasync with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)stack = self._session_stacks.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor, stack)async def _cleanup_session_resources(self,env: Optional[Environment],executor: Optional[ThreadPoolExecutor],stack: Optional[AsyncExitStack] = None,) -> None:"""Close an environment and shut down its executor (best-effort)."""# Close the MCP session stack first — this gracefully exits the# mcp_session() context (and the underlying FastMCP Client session)# before we tear down the environment references.if stack is not None:try:await stack.aclose()except Exception:pass # Best effort cleanup# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:32 unmodified linesif increment_step:self._session_info[session_id].step_count += 1async def _reap_idle_sessions(self) -> None:"""Background task that periodically destroys sessions idle beyond the timeout."""timeout = self._session_idle_timeout_sif timeout is None:return # no timeout configured — noopinterval = max(timeout / 4, 5.0) # check frequently enoughwhile True:try:await asyncio.sleep(interval)now = time.time()stale_ids: list[str] = []async with self._session_lock:for sid, info in self._session_info.items():if now - info.last_activity_at > timeout:stale_ids.append(sid)for sid in stale_ids:# Re-check under lock: activity may have arrived since# the snapshot was taken, making this session active again.# Refresh `now` so slow _destroy_session calls don't cause# subsequent entries to be validated against a stale clock.now = time.time()async with self._session_lock:info = self._session_info.get(sid)if info is None or (now - info.last_activity_at) <= timeout:continueawait self._destroy_session(sid)except asyncio.CancelledError:breakexcept Exception as exc:logging.getLogger(__name__).warning("Idle-session reaper encountered an error (will retry): %s",exc,)def _start_reaper(self) -> None:"""Start the idle-session reaper if a timeout is configured."""if self._session_idle_timeout_s is not None and self._reaper_task is None:self._reaper_task = asyncio.create_task(self._reap_idle_sessions())def _stop_reaper(self) -> None:"""Cancel the reaper background task."""if self._reaper_task is not None:self._reaper_task.cancel()self._reaper_task = Nonedef get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.69 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Wire up idle-session reaper lifecycle via app eventsserver_ref = selfasync def _start_session_reaper() -> None:server_ref._start_reaper()async def _stop_session_reaper() -> None:server_ref._stop_reaper()if not getattr(app.router, "_openenv_reaper_registered", False):app.router.on_startup.append(_start_session_reaper)app.router.on_shutdown.append(_stop_session_reaper)app.router._openenv_reaper_registered = True # type: ignore[attr-defined]# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),62 unmodified lines# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest,session_env: Optional[Environment] = None,session_id: Optional[str] = None,) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format,plus OpenEnv session lifecycle methods for HTTP MCP:- openenv/session/create- openenv/session/close"""method = request.methodrequest_id = request.idparams = request.paramsif not isinstance(params, dict):return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Params must be an object",request_id=request_id,)# OpenEnv extension methods for explicit MCP session management.# This enables persistent MCP lifecycles over HTTP /mcp, matching WebSocket semantics.if method == "openenv/session/create":if session_env is not None and session_id is not None:return JsonRpcResponse.success(result={"session_id": session_id},request_id=request_id,)try:created_session_id, _ = await self._create_session()except SessionCapacityError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),request_id=request_id,data={"active_sessions": e.active_sessions,"max_sessions": e.max_sessions,},)except EnvironmentFactoryError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),request_id=request_id,data={"factory_name": e.factory_name},)return JsonRpcResponse.success(result={"session_id": created_session_id},request_id=request_id,)if method == "openenv/session/close":target_session_id = params.get("session_id")if not target_session_id:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'session_id' is required",request_id=request_id,)if session_id is not None and target_session_id == session_id:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Cannot close active WebSocket-managed session via MCP method",request_id=request_id,)async with self._session_lock:env = self._sessions.pop(target_session_id, _MISSING)if env is not _MISSING:executor = self._session_executors.pop(target_session_id, None)stack = self._session_stacks.pop(target_session_id, None)self._session_info.pop(target_session_id, None)else:executor = Nonestack = Noneif env is _MISSING:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Unknown session_id: {target_session_id}",request_id=request_id,)if env is None:# Session slot reserved but env factory still running;# re-insert the placeholder AND the executor so# _create_session can finish and the executor remains# tracked for eventual shutdown.async with self._session_lock:self._sessions[target_session_id] = Noneif executor is not None:self._session_executors[target_session_id] = executorreturn JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Session {target_session_id} is still initializing; retry shortly",request_id=request_id,)# env/executor/stack cleanup outside the lockawait self._cleanup_session_resources(env, executor, stack)return JsonRpcResponse.success(result={"session_id": target_session_id, "closed": True},request_id=request_id,)requested_session_id = params.get("session_id")managed_session_id = session_id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelif requested_session_id:async with self._session_lock:_env = self._sessions.get(requested_session_id, _MISSING)if _env is _MISSING:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Unknown session_id: {requested_session_id}",request_id=request_id,)if _env is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Session {requested_session_id} is still initializing; retry shortly",request_id=request_id,)should_close = Falsemanaged_session_id = requested_session_idelse:_env = self._env_factory()should_close = Truetry:mcp_client = getattr(_env, "mcp_client", None)mcp_server = getattr(_env, "mcp_server", None)mcp_session_factory = getattr(_env, "mcp_session", None)if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif mcp_client is None and mcp_server is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)if mcp_client:if managed_session_id and mcp_client.is_connected():# Session-managed with live transport — call# directly, no redundant re-entry.tools = await mcp_client.list_tools()elif callable(mcp_session_factory):# Stateless request, or session-managed but the# background transport was lost: (re-)open.mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())async with mcp_session_cm:tools = await mcp_client.list_tools()else:async with mcp_client:tools = await mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,)if mcp_server:tools = []for _tool_name, tool in get_server_tools(mcp_server).items():tools.append({"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},})return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,)elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if mcp_client is None and mcp_server is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",2 unmodified linesif not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Missing 'name' in params",request_id=request_id,)if mcp_client:if managed_session_id and mcp_client.is_connected():# Session-managed with live transport.result = await mcp_client.call_tool(name=tool_name, arguments=arguments)elif callable(mcp_session_factory):# Stateless request, or session-managed but the# background transport was lost: (re-)open.mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())async with mcp_session_cm:result = await mcp_client.call_tool(name=tool_name, arguments=arguments)else:async with mcp_client:result = await mcp_client.call_tool(name=tool_name, arguments=arguments)elif mcp_server:server_tools = get_server_tools(mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]if inspect.iscoroutinefunction(tool.fn):result = await tool.fn(**arguments)else:result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,)# Ensure result is JSON serializable18 unmodified linesrequest_id=request_id,)finally:if managed_session_id:self._update_session_activity(managed_session_id,increment_step=(method == McpMethod.TOOLS_CALL),)if should_close:_env.close()17 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for MCP websocket")# If environment has an mcp_session context manager, hold it open# for the lifetime of the websocket connectionasync with AsyncExitStack() as stack:mcp_session_factory = getattr(session_env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request,session_env=session_env,session_id=session_id,)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass252 unmodified linesJsonRpcErrorCode.PARSE_ERROR).model_dump()response = await mcp_handler(request)return response.model_dump()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")15 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for websocket")# Keep MCP session open for entire websocket lifetime# (avoids reconnect overhead on every message)async with AsyncExitStack() as stack:mcp_session_factory = getattr(session_env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = (await self._run_in_session_executor(session_id,session_env.reset,**valid_kwargs,))self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = (await self._run_in_session_executor(session_id, session_env.step, action))self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,session_id=session_id,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass75 unmodified linesfrom .web_interface import create_web_interface_appreturn create_web_interface_app(cast(Any, env),action_cls,observation_cls,env_name,
55 unmodified lines565758596061102 unmodified lines164165166167168169122 unmodified lines29229329429529629729873 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943955 unmodified lines4014024034044054064074084094104113 unmodified lines4154164174184194204212 unmodified lines4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874882 unmodified lines49149249349449549649749849950050150250350450550614 unmodified lines5215225235245255265275285295305315325335345355365375385395405415423 unmodified lines5465475485495505515525535545555566 unmodified lines56356456556656756856957057157257357457557657757857958058158258358458558658758858959059155 unmodified linesimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom typing import Any, Callable, Dict, Optionalfrom fastmcp import Client102 unmodified lines# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)@propertydef supports_code_mode(self) -> bool:"""Check if this environment supports code mode (execute_code)."""122 unmodified lines# If mode is None, register with FastMCP as usualif mode is None:decorated_func = self.mcp_server.tool()(func)self._mode_tools[tool_name][None] = funcreturn decorated_func73 unmodified linesreturn self._step_impl(action, timeout_s=timeout_s, **kwargs)def _handle_list_tools(self) -> ListToolsObservation:"""Handle a ListToolsAction by querying the MCP server.Returns:ListToolsObservation containing all available tools with theirnames, descriptions, and input schemas, filtered by current mode."""try:# Get current modecurrent_mode = getattr(self, "_mode", None)# Start with tools from FastMCP server (mode=None tools)tools_result = run_async_safely(self._async_list_tools())# Build list of Tool objectstools = []# Add FastMCP tools that are not mode-specificfor tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(5 unmodified lineselse {},))# Add mode-specific tools available in current modefor tool_name, mode_schemas in self._mode_tool_schemas.items():if None in mode_schemas:# Tool available in all modesschema = mode_schemas[None]tools.append(Tool(3 unmodified lines))elif current_mode in mode_schemas:# Tool available in current modeschema = mode_schemas[current_mode]tools.append(Tool(2 unmodified linesinput_schema=schema["input_schema"],))return ListToolsObservation(tools=tools)except Exception as e:# Return an observation with error in metadatareturn ListToolsObservation(tools=[],metadata={"error": str(e),"error_type": "list_tools_failed",},)async def _async_list_tools(self) -> list:"""Async helper to list tools from the MCP client.Returns:List of tool objects from the MCP server."""async with self.mcp_client:return await self.mcp_client.list_tools()def _handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Handle a CallToolAction by invoking the specified tool.Args:action: The CallToolAction containing tool_name and arguments.timeout_s: Timeout in seconds. Defaults to MCP_TOOL_CALL_TIMEOUT (30s).Returns:CallToolObservation with the tool's result or an error."""timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUT# Check if this is a mode-specific tooltool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]# Check if tool is available in current mode# Tool is available if:# 1. It has a None mode (available in all modes), OR# 2. It has an implementation for the current modeif None in mode_info:# Use the mode-agnostic versionfunc = mode_info[None]elif current_mode in mode_info:# Use the mode-specific versionfunc = mode_info[current_mode]else:# Tool not available in current modereturn CallToolObservation(tool_name=tool_name,result=None,2 unmodified linesmessage=f"Tool '{tool_name}' not available in {current_mode} mode",),)# Call the mode-specific function directlytry:# Check if function is async and await if necessaryif inspect.iscoroutinefunction(func):result = run_async_safely(func(**action.arguments))else:result = func(**action.arguments)# Wrap result in CallToolResult format to match FastMCP behaviorreturn CallToolObservation(tool_name=tool_name,result=CallToolResult(14 unmodified lines),)# Not a mode-specific tool, use FastMCPtry:# Run the async call_tool with timeout# Use run_async_safely to handle both sync and async contextsresult = run_async_safely(asyncio.wait_for(self._async_call_tool(action.tool_name, action.arguments),timeout=timeout,))return CallToolObservation(tool_name=action.tool_name,result=result,)except asyncio.TimeoutError:return CallToolObservation(tool_name=action.tool_name,3 unmodified linesmessage=f"Tool '{action.tool_name}' timed out after {timeout} seconds",),)except Exception as e:error_message = str(e)# Determine error type based on the exceptionif ("not found" in error_message.lower()or "unknown tool" in error_message.lower()6 unmodified lineserror_type = ToolErrorType.INVALID_ARGSelse:error_type = ToolErrorType.EXECUTION_ERRORreturn CallToolObservation(tool_name=action.tool_name,result=None,error=ToolError(error_type=error_type,message=error_message,),)async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:"""Async helper to call a tool on the MCP server.Args:tool_name: Name of the tool to invoke.arguments: Dictionary of arguments to pass to the tool.Returns:The result from the tool execution."""async with self.mcp_client:return await self.mcp_client.call_tool(tool_name, arguments)@abstractmethoddef _step_impl(55 unmodified lines56575859606162102 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216122 unmodified lines33934034134234334434534673 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674685 unmodified lines4744754764774784794804813 unmodified lines4854864874884894902 unmodified lines4934944954964974984995005015025035045055065075085095105115125135145155165175185195205215222 unmodified lines52552652752852953053153253353453514 unmodified lines5505515525535545555565575585595605613 unmodified lines5655665675685695705715726 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161255 unmodified linesimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom contextlib import asynccontextmanagerfrom typing import Any, Callable, Dict, Optionalfrom fastmcp import Client102 unmodified lines# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)def _require_mcp_client(self) -> Any:"""Return MCP client or raise if environment has been closed."""if self.mcp_client is None:raise RuntimeError("MCP client is not available; environment is closed")return self.mcp_clientdef _require_mcp_server(self) -> Any:"""Return MCP server or raise if environment has been closed."""if self.mcp_server is None:raise RuntimeError("MCP server is not available; environment is closed")return self.mcp_server@asynccontextmanagerasync def mcp_session(self):"""Context manager for MCP client sessions.This wrapper serves two purposes:1. **Null guard** — raises a clear error if ``close()`` has alreadybeen called (``mcp_client`` is ``None``).2. **AsyncExitStack adapter** — FastMCP's ``Client.__aenter__``creates a background ``asyncio.Task`` for session management.When entered directly via ``AsyncExitStack`` in the HTTP sessionpath (``_create_session``), this task can be cancelled by ASGIharnesses (e.g. Starlette ``TestClient``) between requests,corrupting session state. Wrapping in an ``asynccontextmanager``generator isolates the task lifecycle: the generator frame keeps``async with client:`` suspended at ``yield``, so cleanup onlyruns when the stack explicitly closes the generator — not whenthe event loop cancels orphaned tasks.Delegates to FastMCP's ``Client`` context manager which isreentrant: the first entry opens the transport and subsequent(nested) entries simply increment an internal reference counter.The transport is closed only when the outermost context exits.No external lock is needed because ``Client._connect`` /``Client._disconnect`` already serialise connection state changesthrough their own ``anyio.Lock``."""client = self._require_mcp_client()async with client:yield client@propertydef supports_code_mode(self) -> bool:"""Check if this environment supports code mode (execute_code)."""122 unmodified lines# If mode is None, register with FastMCP as usualif mode is None:mcp_server = self._require_mcp_server()decorated_func = mcp_server.tool()(func)self._mode_tools[tool_name][None] = funcreturn decorated_func73 unmodified linesreturn self._step_impl(action, timeout_s=timeout_s, **kwargs)def _handle_list_tools(self) -> ListToolsObservation:"""Sync wrapper — delegates to the canonical async implementation."""return run_async_safely(self._async_handle_list_tools())async def _async_list_tools(self) -> list:"""Async helper to list tools from the MCP client.Returns:List of tool objects from the MCP server."""async with self.mcp_session() as client:return await client.list_tools()def _handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Sync wrapper — delegates to the canonical async implementation."""return run_async_safely(self._async_handle_call_tool(action, timeout_s=timeout_s))async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:"""Async helper to call a tool on the MCP server.Args:tool_name: Name of the tool to invoke.arguments: Dictionary of arguments to pass to the tool.Returns:The result from the tool execution."""async with self.mcp_session() as client:return await client.call_tool(tool_name, arguments)async def _async_handle_list_tools(self) -> ListToolsObservation:"""Async version of _handle_list_tools — avoids run_async_safely."""try:current_mode = getattr(self, "_mode", None)tools_result = await self._async_list_tools()tools = []for tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(5 unmodified lineselse {},))for tool_name, mode_schemas in self._mode_tool_schemas.items():if None in mode_schemas:schema = mode_schemas[None]tools.append(Tool(3 unmodified lines))elif current_mode in mode_schemas:schema = mode_schemas[current_mode]tools.append(Tool(2 unmodified linesinput_schema=schema["input_schema"],))return ListToolsObservation(tools=tools)except Exception as e:return ListToolsObservation(tools=[],metadata={"error": str(e), "error_type": "list_tools_failed"},)async def _async_handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Async version of _handle_call_tool — avoids run_async_safely."""timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUTtool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]if None in mode_info:func = mode_info[None]elif current_mode in mode_info:func = mode_info[current_mode]else:return CallToolObservation(tool_name=tool_name,result=None,2 unmodified linesmessage=f"Tool '{tool_name}' not available in {current_mode} mode",),)try:if inspect.iscoroutinefunction(func):result = await func(**action.arguments)else:result = func(**action.arguments)return CallToolObservation(tool_name=tool_name,result=CallToolResult(14 unmodified lines),)try:result = await asyncio.wait_for(self._async_call_tool(action.tool_name, action.arguments),timeout=timeout,)return CallToolObservation(tool_name=action.tool_name, result=result)except asyncio.TimeoutError:return CallToolObservation(tool_name=action.tool_name,3 unmodified linesmessage=f"Tool '{action.tool_name}' timed out after {timeout} seconds",),)except Exception as e:error_message = str(e)if ("not found" in error_message.lower()or "unknown tool" in error_message.lower()6 unmodified lineserror_type = ToolErrorType.INVALID_ARGSelse:error_type = ToolErrorType.EXECUTION_ERRORreturn CallToolObservation(tool_name=action.tool_name,result=None,error=ToolError(error_type=error_type, message=error_message),)async def step_async(self,action: Action,timeout_s: Optional[float] = None,**kwargs: Any,) -> Observation:"""Async step that routes MCP actions without going through run_async_safely.The WebSocket handler calls this directly on the outer event loop, wherethe MCP session is already open, avoiding the thread/event-loop deadlockthat occurs when the sync step() path is used via run_in_executor."""if isinstance(action, ListToolsAction):return await self._async_handle_list_tools()elif isinstance(action, CallToolAction):return await self._async_handle_call_tool(action, timeout_s=timeout_s)else:loop = asyncio.get_event_loop()return await loop.run_in_executor(None, lambda: self._step_impl(action, timeout_s=timeout_s, **kwargs))@abstractmethoddef _step_impl(
13 unmodified lines141516171819202122232425262710 unmodified lines38394041424318 unmodified lines62636465666713 unmodified linesfrom typing import Any, Dict, Typefrom .types import Action, Observationdef deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:"""Convert JSON dict to Action instance using Pydantic validation.This is a basic deserialization that works for most environments.For special cases (e.g., tensor fields, custom type conversions),use deserialize_action_with_preprocessing().10 unmodified linesNote:This uses Pydantic's model_validate() for automatic validation."""return action_cls.model_validate(action_data)18 unmodified linesRaises:ValidationError: If action_data is invalid for the action class"""processed_data = {}for key, value in action_data.items():13 unmodified lines1415161718192021222324252627282930313233343536373839404110 unmodified lines525354555657585960616263646566676818 unmodified lines8788899091929394959697989910010113 unmodified linesfrom typing import Any, Dict, Typefrom .mcp_types import CallToolAction, ListToolsActionfrom .types import Action, Observation# MCP action types keyed by their "type" discriminator value.# These are checked before the environment's own action_cls so that# ListToolsAction / CallToolAction payloads are never rejected by an# unrelated Pydantic model._MCP_ACTION_TYPES: Dict[str, Type[Action]] = {"list_tools": ListToolsAction,"call_tool": CallToolAction,}def deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:"""Convert JSON dict to Action instance using Pydantic validation.MCP action types (``list_tools``, ``call_tool``) are recognisedautomatically via the ``"type"`` discriminator field, regardless ofthe environment's configured ``action_cls``. All other payloadsfall through to ``action_cls.model_validate()``.For special cases (e.g., tensor fields, custom type conversions),use deserialize_action_with_preprocessing().10 unmodified linesNote:This uses Pydantic's model_validate() for automatic validation."""# Route MCP action types before falling through to the env action_cls.# Only intercept when action_cls is the generic Action base or itself an# MCP type (i.e. the server hosts an MCP environment). This avoids# silently bypassing env-specific validation for non-MCP environments# that happen to use "call_tool" / "list_tools" as a type discriminator.action_type = action_data.get("type")if action_type in _MCP_ACTION_TYPES:mcp_cls = _MCP_ACTION_TYPES[action_type]if action_cls is Action or action_cls in _MCP_ACTION_TYPES.values():return mcp_cls.model_validate(action_data)return action_cls.model_validate(action_data)18 unmodified linesRaises:ValidationError: If action_data is invalid for the action class"""# Route MCP action types before preprocessing (they don't need it).# Same guard as deserialize_action: only intercept when action_cls is# the generic Action base or itself an MCP type.action_type = action_data.get("type")if action_type in _MCP_ACTION_TYPES:mcp_cls = _MCP_ACTION_TYPES[action_type]if action_cls is Action or action_cls in _MCP_ACTION_TYPES.values():return mcp_cls.model_validate(action_data)processed_data = {}for key, value in action_data.items():
14 unmodified lines15161718192021222324252627241 unmodified lines26927027127227327442 unmodified lines317318319320321322323324325326327100 unmodified lines42842943043143243315 unmodified lines44945045145245345445545645717 unmodified lines47547647747847948048123 unmodified lines50550650750850951051114 unmodified linesfrom __future__ import annotationsimport asyncioimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Typeimport gradio as grfrom fastapi import FastAPI, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel, ConfigDict, Fieldfrom .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME241 unmodified lines# Thread pool for running sync code (e.g., Playwright sync API) in async contextself._executor = ThreadPoolExecutor(max_workers=1)async def _run_sync_in_thread_pool(self, func, *args, **kwargs):"""Run a synchronous function in the thread pool executor.42 unmodified linesfor client in disconnected_clients:self.connected_clients.remove(client)async def reset_environment(self) -> Dict[str, Any]:"""Reset the environment and update state."""# Run sync reset in thread pool to avoid blocking event loop# and to support environments using sync libraries (e.g., Playwright)observation: Observation = await self._run_sync_in_thread_pool(self.env.reset)state: State = self.env.state# Serialize observation once using shared utility100 unmodified linesweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Web API routes first (so they take precedence over Gradio mount at /web)@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""15 unmodified linesawait web_manager.disconnect_websocket(websocket)@app.post("/web/reset")async def web_reset():"""Reset endpoint for web interface."""return await web_manager.reset_environment()@app.post("/web/step")async def web_step(request: Dict[str, Any]):17 unmodified lines@app.get("/web/state")async def web_state():"""State endpoint for web interface."""return web_manager.get_state()action_fields = _extract_action_fields(action_cls)is_chat_env = _is_chat_env(action_cls)23 unmodified lines)gradio_blocks = gr.TabbedInterface([default_blocks, custom_blocks],tab_names=["Playground", "Visualization"],title=get_gradio_display_title(metadata),)else:14 unmodified lines151617181920212223242526272829241 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729842 unmodified lines341342343344345346347348349350351352353354355356357358359360361362363364100 unmodified lines46546646746846947047147247347447547647747847948015 unmodified lines49649749849950050150250350417 unmodified lines52252352452552652752852953053153253353423 unmodified lines55855956056156256356414 unmodified linesfrom __future__ import annotationsimport asyncioimport inspectimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Typeimport gradio as grfrom fastapi import Body, FastAPI, HTTPException, status, WebSocket, WebSocketDisconnectfrom fastapi.responses import RedirectResponsefrom pydantic import BaseModel, ConfigDict, Fieldfrom .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME241 unmodified lines# Thread pool for running sync code (e.g., Playwright sync API) in async contextself._executor = ThreadPoolExecutor(max_workers=1)@staticmethoddef _get_valid_kwargs(sig: inspect.Signature,kwargs: Dict[str, Any],skip_params: Optional[set[str]] = None,) -> Dict[str, Any]:"""Filter kwargs to only those accepted by the target function."""skip_params = skip_params or set()valid_kwargs: Dict[str, Any] = {}has_var_kwargs = any(param.kind == inspect.Parameter.VAR_KEYWORDfor param in sig.parameters.values())for key, value in kwargs.items():if key in skip_params:continueif key in sig.parameters or has_var_kwargs:valid_kwargs[key] = valuereturn valid_kwargsasync def _run_sync_in_thread_pool(self, func, *args, **kwargs):"""Run a synchronous function in the thread pool executor.42 unmodified linesfor client in disconnected_clients:self.connected_clients.remove(client)async def reset_environment(self, reset_kwargs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Reset the environment and update state."""reset_kwargs = reset_kwargs or {}is_async = self.env.reset_async.__func__ is not Environment.reset_asyncsig = inspect.signature(self.env.reset_async if is_async else self.env.reset)valid_kwargs = self._get_valid_kwargs(sig, reset_kwargs)if is_async:observation = await self.env.reset_async(**valid_kwargs)else:# Run sync reset in thread pool to avoid blocking event loop# and to support environments using sync libraries (e.g., Playwright)observation = await self._run_sync_in_thread_pool(self.env.reset, **valid_kwargs)state: State = self.env.state# Serialize observation once using shared utility100 unmodified linesweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Web API routes first (so they take precedence over Gradio mount at /web)@app.get("/", include_in_schema=False)async def web_root():"""Redirect the app root to the Gradio interface."""return RedirectResponse(url="/web/")@app.get("/web", include_in_schema=False)async def web_root_no_slash():"""Redirect /web to /web/ for mounted Gradio deployments behind proxies."""return RedirectResponse(url="/web/")@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""15 unmodified linesawait web_manager.disconnect_websocket(websocket)@app.post("/web/reset")async def web_reset(request: Optional[Dict[str, Any]] = Body(default=None)):"""Reset endpoint for web interface."""return await web_manager.reset_environment(request)@app.post("/web/step")async def web_step(request: Dict[str, Any]):17 unmodified lines@app.get("/web/state")async def web_state():"""State endpoint for web interface."""try:return web_manager.get_state()except RuntimeError as exc:raise HTTPException(status_code=status.HTTP_409_CONFLICT,detail=str(exc),) from excaction_fields = _extract_action_fields(action_cls)is_chat_env = _is_chat_env(action_cls)23 unmodified lines)gradio_blocks = gr.TabbedInterface([default_blocks, custom_blocks],tab_names=["Playground", "Custom"],title=get_gradio_display_title(metadata),)else:
51 unmodified lines52535455565760 unmodified lines11811912012112212314 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216313 unmodified lines17717817918018118218367 unmodified lines25125225325425525659 unmodified lines31631731831932032151 unmodified lines... result = env.call_tool("echo_message", message="Hello!")"""from typing import Any, Dict, List, Optionalfrom .client_types import StepResult60 unmodified lines)self._tools_cache: Optional[List[Tool]] = Noneself.use_production_mode = Falseasync def list_tools(self, use_cache: bool = True) -> List[Tool]:"""14 unmodified linesif use_cache and self._tools_cache is not None:return self._tools_cache# Use production mode HTTP endpoint if enabledif self.use_production_mode:import requests# Convert ws:// URL to http:// URLurl = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")# Remove /ws suffix if present and add /mcpurl = url.rstrip("/ws").rstrip("/") + "/mcp"try:response = requests.post(url,json={"jsonrpc": "2.0","method": "tools/list","params": {},"id": 1,},)data = response.json()if "result" in data and "tools" in data["result"]:tools = [Tool(13 unmodified linesreturn []result = await self.step(ListToolsAction())self._tools_cache = result.observation.toolsreturn self._tools_cachedef _step_payload(self, action: Any) -> Dict[str, Any]:67 unmodified linesstep_count=payload.get("step_count", 0),)class MCPToolClient(MCPClientBase):"""59 unmodified lines>>> result = await env.call_tool("greet", name="Claude")>>> print(result) # "Hello, Claude!""""action = CallToolAction(tool_name=name, arguments=kwargs)result = await self.step(action)obs = result.observation51 unmodified lines5253545556575860 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318414 unmodified lines19920020120220320420520620720820921021121221321421521613 unmodified lines23023123223323423523623723823924024167 unmodified lines30931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234359 unmodified lines40340440540640740840941041141241341441541641741841942042142242342442542642742851 unmodified lines... result = env.call_tool("echo_message", message="Hello!")"""import asynciofrom typing import Any, Dict, List, Optionalfrom .client_types import StepResult60 unmodified lines)self._tools_cache: Optional[List[Tool]] = Noneself.use_production_mode = Falseself._production_session_id: Optional[str] = Noneself._production_session_lock = asyncio.Lock()self._jsonrpc_request_id = 0self._http_client: Optional[Any] = None # lazily-created httpx.AsyncClientdef _next_request_id(self) -> int:"""Generate a monotonically increasing JSON-RPC request id."""self._jsonrpc_request_id += 1return self._jsonrpc_request_iddef _production_mcp_url(self) -> str:"""Build HTTP MCP endpoint URL from the client's websocket URL."""url = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")if url.endswith("/ws"):url = url[: -len("/ws")]return url.rstrip("/") + "/mcp"async def _get_http_client(self) -> Any:"""Return a shared httpx.AsyncClient, creating one lazily."""if self._http_client is None:import httpxself._http_client = httpx.AsyncClient()return self._http_clientasync def _production_mcp_request(self, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Send a JSON-RPC request to HTTP /mcp and return parsed JSON response."""client = await self._get_http_client()response = await client.post(self._production_mcp_url(),json={"jsonrpc": "2.0","method": method,"params": params or {},"id": self._next_request_id(),},timeout=self._message_timeout,)response.raise_for_status()return response.json()async def _ensure_production_session(self) -> str:"""Create and cache a persistent HTTP MCP session id if needed."""async with self._production_session_lock:if self._production_session_id is not None:return self._production_session_iddata = await self._production_mcp_request("openenv/session/create")if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"Failed to create MCP session: {message}")session_id = data.get("result", {}).get("session_id")if not session_id:raise RuntimeError("Failed to create MCP session: missing session_id")self._production_session_id = session_idreturn session_idasync def list_tools(self, use_cache: bool = True) -> List[Tool]:"""14 unmodified linesif use_cache and self._tools_cache is not None:return self._tools_cache# Use production mode HTTP endpoint if enabled.# Some tests instantiate with __new__ and skip __init__, so default missing flag to False.if getattr(self, "use_production_mode", False):try:session_id = await self._ensure_production_session()data = await self._production_mcp_request("tools/list",{"session_id": session_id},)if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"list_tools failed: {message}")if "result" in data and "tools" in data["result"]:tools = [Tool(13 unmodified linesreturn []result = await self.step(ListToolsAction())if isinstance(result.observation, ListToolsObservation):self._tools_cache = result.observation.toolsreturn self._tools_cache# Unexpected observation type; keep API stable with an empty tool list.self._tools_cache = []return self._tools_cachedef _step_payload(self, action: Any) -> Dict[str, Any]:67 unmodified linesstep_count=payload.get("step_count", 0),)async def close(self) -> None:"""Close client resources.In production MCP mode, this also closes the server-side persistentMCP session (best effort) before closing websocket/provider resources."""if self._production_session_id is not None:try:await self._production_mcp_request("openenv/session/close",{"session_id": self._production_session_id},)except Exception:# Best effort cleanup - do not mask normal close behaviorpassfinally:self._production_session_id = Noneif self._http_client is not None:try:await self._http_client.aclose()except Exception:passfinally:self._http_client = Noneawait super().close()class MCPToolClient(MCPClientBase):"""59 unmodified lines>>> result = await env.call_tool("greet", name="Claude")>>> print(result) # "Hello, Claude!""""if getattr(self, "use_production_mode", False):session_id = await self._ensure_production_session()data = await self._production_mcp_request("tools/call",{"name": name,"arguments": kwargs,"session_id": session_id,},)if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"Tool '{name}' failed: {message}")result = data.get("result")if isinstance(result, dict) and "data" in result:return result["data"]return resultaction = CallToolAction(tool_name=name, arguments=kwargs)result = await self.step(action)obs = result.observation
13 unmodified lines1415161718192021222313 unmodified lines"SyncEnvClient",]try:__version__ = metadata.version("openenv") # type: ignore[arg-type]except metadata.PackageNotFoundError: # pragma: no cover - local dev__version__ = "0.0.0"_LAZY_MODULES = {13 unmodified lines14151617181920212223242526272829303113 unmodified lines"SyncEnvClient",]def _load_package_version() -> str:"""Resolve the installed distribution version for the OpenEnv package."""for distribution_name in ("openenv-core", "openenv"):try:return metadata.version(distribution_name)except metadata.PackageNotFoundError:continuereturn "0.0.0"__version__ = _load_package_version()_LAZY_MODULES = {
16 unmodified lines1718192021222316 unmodified lines# Core OpenEnv runtime (provides FastAPI server + HTTP client types)# install from github# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git","openenv-core[core]>=0.2.1",# Environment-specific dependencies# Add all dependencies needed for your environment here# Examples:16 unmodified lines1718192021222316 unmodified lines# Core OpenEnv runtime (provides FastAPI server + HTTP client types)# install from github# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git","openenv-core[core]>=0.2.2",# Environment-specific dependencies# Add all dependencies needed for your environment here# Examples:
15 unmodified lines1617181920212223242526177 unmodified lines2042052062072082092102111 unmodified line213214215216217218102 unmodified lines32132232332432532632732832933033133210 unmodified lines34334434534634734834935032 unmodified lines38338438538638738869 unmodified lines45845946046146246362 unmodified lines5265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775782 unmodified lines58158258358458558658758858959059159259359459518 unmodified lines61461561661761861917 unmodified lines637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678252 unmodified lines93193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105015 unmodified lines10661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120075 unmodified lines127612771278127912801281128215 unmodified linesimport asyncioimport inspectimport jsonimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Callable, Dict, Optional, Typefrom fastapi import (Body,177 unmodified linesself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Environment] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()1 unmodified line# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)def _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.102 unmodified lines)raise EnvironmentFactoryError(factory_name) from easync with self._session_lock:self._sessions[session_id] = envself._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=current_time,step_count=0,environment_type=type(env).__name__,)10 unmodified linesasync with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:32 unmodified linesif increment_step:self._session_info[session_id].step_count += 1def get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.69 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),62 unmodified lines# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest, session_env: Optional[Environment] = None) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format."""method = request.methodrequest_id = request.id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelse:_env = self._env_factory()should_close = Truetry:if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump() if hasattr(t, "model_dump") else dict(t)for t in tools]},request_id=request_id,)elif method == McpMethod.TOOLS_CALL:params = request.paramstool_name = params.get("name")arguments = params.get("arguments", {})if not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",2 unmodified linesif not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Missing 'name' in params",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)# Ensure result is JSON serializable18 unmodified linesrequest_id=request_id,)finally:if should_close:_env.close()17 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request, session_env=session_env)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass252 unmodified linesJsonRpcErrorCode.PARSE_ERROR).model_dump()method = request.methodparams = request.paramsrequest_id = request.id# Create a temporary environment for MCP access_env = self._env_factory()try:# Check if environment supports MCPif not hasattr(_env, "mcp_client") and not hasattr(_env, "mcp_server"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,).model_dump()if method == McpMethod.TOOLS_LIST:# List tools from MCP serverif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,).model_dump()elif hasattr(_env, "mcp_server") and _env.mcp_server:# Use server directlytools = []for tool_name, tool in get_server_tools(_env.mcp_server).items():tool_dict = {"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},}tools.append(tool_dict)return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'name' is required",request_id=request_id,).model_dump()# Call tool via MCPif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)elif hasattr(_env, "mcp_server") and _env.mcp_server:# Call tool directly on FastMCP serverserver_tools = get_server_tools(_env.mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()# Make result JSON serializableserializable_result = _make_json_serializable(result)return JsonRpcResponse.success(result=serializable_result,request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,f"Method not found: {method}",request_id=request_id,).model_dump()except Exception as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=request_id,).model_dump()finally:_env.close()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")15 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await self._run_in_session_executor(session_id, session_env.reset, **valid_kwargs)self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = await self._run_in_session_executor(session_id, session_env.step, action)self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass75 unmodified linesfrom .web_interface import create_web_interface_appreturn create_web_interface_app(env,action_cls,observation_cls,env_name,15 unmodified lines161718192021222324252627282930177 unmodified lines2082092102112122132142152161 unmodified line218219220221222223224225226227228229230231102 unmodified lines33433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937010 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240340440540640732 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949069 unmodified lines56056156256356456556656756856957057157257357457557657757857962 unmodified lines6426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548552 unmodified lines85885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790818 unmodified lines92792892993093193293393493593693717 unmodified lines95595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013252 unmodified lines1266126712681269127012711272127315 unmodified lines1289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145575 unmodified lines153115321533153415351536153715 unmodified linesimport asyncioimport inspectimport jsonimport loggingimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import AsyncExitStackfrom typing import Any, AsyncContextManager, Callable, cast, Dict, Optional, Type_MISSING = object()from fastapi import (Body,177 unmodified linesself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Optional[Environment]] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_stacks: Dict[str, AsyncExitStack] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()1 unmodified line# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)# Idle session reaper configuration.# Timeout is taken from ConcurrencyConfig.session_timeout;# None means no timeout (default — reaper is a no-op).self._session_idle_timeout_s: Optional[float] = (self._concurrency_config.session_timeout)self._reaper_task: Optional[asyncio.Task[None]] = Nonedef _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.102 unmodified lines)raise EnvironmentFactoryError(factory_name) from e# Hold the MCP session open for the lifetime of this session,# matching the WebSocket path's AsyncExitStack pattern. This# prevents per-request MCP transport teardown/reconnection and# preserves FastMCP session state (ctx.set_state / ctx.get_state)# across HTTP calls within the same OpenEnv session.stack = AsyncExitStack()try:mcp_session_factory = getattr(env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)except Exception:# MCP transport failed to start — clean up the reserved slot,# the env, and the executor so they don't leak permanently# against _max_concurrent_envs.await stack.aclose() # best-effortasync with self._session_lock:self._sessions.pop(session_id, None)self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor)raiseasync with self._session_lock:self._sessions[session_id] = envself._session_stacks[session_id] = stacknow = time.time()self._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=now,step_count=0,environment_type=type(env).__name__,)10 unmodified linesasync with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)stack = self._session_stacks.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor, stack)async def _cleanup_session_resources(self,env: Optional[Environment],executor: Optional[ThreadPoolExecutor],stack: Optional[AsyncExitStack] = None,) -> None:"""Close an environment and shut down its executor (best-effort)."""# Close the MCP session stack first — this gracefully exits the# mcp_session() context (and the underlying FastMCP Client session)# before we tear down the environment references.if stack is not None:try:await stack.aclose()except Exception:pass # Best effort cleanup# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:32 unmodified linesif increment_step:self._session_info[session_id].step_count += 1async def _reap_idle_sessions(self) -> None:"""Background task that periodically destroys sessions idle beyond the timeout."""timeout = self._session_idle_timeout_sif timeout is None:return # no timeout configured — noopinterval = max(timeout / 4, 5.0) # check frequently enoughwhile True:try:await asyncio.sleep(interval)now = time.time()stale_ids: list[str] = []async with self._session_lock:for sid, info in self._session_info.items():if now - info.last_activity_at > timeout:stale_ids.append(sid)for sid in stale_ids:# Re-check under lock: activity may have arrived since# the snapshot was taken, making this session active again.# Refresh `now` so slow _destroy_session calls don't cause# subsequent entries to be validated against a stale clock.now = time.time()async with self._session_lock:info = self._session_info.get(sid)if info is None or (now - info.last_activity_at) <= timeout:continueawait self._destroy_session(sid)except asyncio.CancelledError:breakexcept Exception as exc:logging.getLogger(__name__).warning("Idle-session reaper encountered an error (will retry): %s",exc,)def _start_reaper(self) -> None:"""Start the idle-session reaper if a timeout is configured."""if self._session_idle_timeout_s is not None and self._reaper_task is None:self._reaper_task = asyncio.create_task(self._reap_idle_sessions())def _stop_reaper(self) -> None:"""Cancel the reaper background task."""if self._reaper_task is not None:self._reaper_task.cancel()self._reaper_task = Nonedef get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.69 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Wire up idle-session reaper lifecycle via app eventsserver_ref = selfasync def _start_session_reaper() -> None:server_ref._start_reaper()async def _stop_session_reaper() -> None:server_ref._stop_reaper()if not getattr(app.router, "_openenv_reaper_registered", False):app.router.on_startup.append(_start_session_reaper)app.router.on_shutdown.append(_stop_session_reaper)app.router._openenv_reaper_registered = True # type: ignore[attr-defined]# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),62 unmodified lines# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest,session_env: Optional[Environment] = None,session_id: Optional[str] = None,) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format,plus OpenEnv session lifecycle methods for HTTP MCP:- openenv/session/create- openenv/session/close"""method = request.methodrequest_id = request.idparams = request.paramsif not isinstance(params, dict):return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Params must be an object",request_id=request_id,)# OpenEnv extension methods for explicit MCP session management.# This enables persistent MCP lifecycles over HTTP /mcp, matching WebSocket semantics.if method == "openenv/session/create":if session_env is not None and session_id is not None:return JsonRpcResponse.success(result={"session_id": session_id},request_id=request_id,)try:created_session_id, _ = await self._create_session()except SessionCapacityError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),request_id=request_id,data={"active_sessions": e.active_sessions,"max_sessions": e.max_sessions,},)except EnvironmentFactoryError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),request_id=request_id,data={"factory_name": e.factory_name},)return JsonRpcResponse.success(result={"session_id": created_session_id},request_id=request_id,)if method == "openenv/session/close":target_session_id = params.get("session_id")if not target_session_id:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'session_id' is required",request_id=request_id,)if session_id is not None and target_session_id == session_id:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Cannot close active WebSocket-managed session via MCP method",request_id=request_id,)async with self._session_lock:env = self._sessions.pop(target_session_id, _MISSING)if env is not _MISSING:executor = self._session_executors.pop(target_session_id, None)stack = self._session_stacks.pop(target_session_id, None)self._session_info.pop(target_session_id, None)else:executor = Nonestack = Noneif env is _MISSING:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Unknown session_id: {target_session_id}",request_id=request_id,)if env is None:# Session slot reserved but env factory still running;# re-insert the placeholder AND the executor so# _create_session can finish and the executor remains# tracked for eventual shutdown.async with self._session_lock:self._sessions[target_session_id] = Noneif executor is not None:self._session_executors[target_session_id] = executorreturn JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Session {target_session_id} is still initializing; retry shortly",request_id=request_id,)# env/executor/stack cleanup outside the lockawait self._cleanup_session_resources(env, executor, stack)return JsonRpcResponse.success(result={"session_id": target_session_id, "closed": True},request_id=request_id,)requested_session_id = params.get("session_id")managed_session_id = session_id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelif requested_session_id:async with self._session_lock:_env = self._sessions.get(requested_session_id, _MISSING)if _env is _MISSING:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Unknown session_id: {requested_session_id}",request_id=request_id,)if _env is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Session {requested_session_id} is still initializing; retry shortly",request_id=request_id,)should_close = Falsemanaged_session_id = requested_session_idelse:_env = self._env_factory()should_close = Truetry:mcp_client = getattr(_env, "mcp_client", None)mcp_server = getattr(_env, "mcp_server", None)mcp_session_factory = getattr(_env, "mcp_session", None)if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif mcp_client is None and mcp_server is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)if mcp_client:if managed_session_id and mcp_client.is_connected():# Session-managed with live transport — call# directly, no redundant re-entry.tools = await mcp_client.list_tools()elif callable(mcp_session_factory):# Stateless request, or session-managed but the# background transport was lost: (re-)open.mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())async with mcp_session_cm:tools = await mcp_client.list_tools()else:async with mcp_client:tools = await mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,)if mcp_server:tools = []for _tool_name, tool in get_server_tools(mcp_server).items():tools.append({"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},})return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,)elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if mcp_client is None and mcp_server is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",2 unmodified linesif not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Missing 'name' in params",request_id=request_id,)if mcp_client:if managed_session_id and mcp_client.is_connected():# Session-managed with live transport.result = await mcp_client.call_tool(name=tool_name, arguments=arguments)elif callable(mcp_session_factory):# Stateless request, or session-managed but the# background transport was lost: (re-)open.mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())async with mcp_session_cm:result = await mcp_client.call_tool(name=tool_name, arguments=arguments)else:async with mcp_client:result = await mcp_client.call_tool(name=tool_name, arguments=arguments)elif mcp_server:server_tools = get_server_tools(mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]if inspect.iscoroutinefunction(tool.fn):result = await tool.fn(**arguments)else:result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,)# Ensure result is JSON serializable18 unmodified linesrequest_id=request_id,)finally:if managed_session_id:self._update_session_activity(managed_session_id,increment_step=(method == McpMethod.TOOLS_CALL),)if should_close:_env.close()17 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for MCP websocket")# If environment has an mcp_session context manager, hold it open# for the lifetime of the websocket connectionasync with AsyncExitStack() as stack:mcp_session_factory = getattr(session_env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request,session_env=session_env,session_id=session_id,)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass252 unmodified linesJsonRpcErrorCode.PARSE_ERROR).model_dump()response = await mcp_handler(request)return response.model_dump()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")15 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for websocket")# Keep MCP session open for entire websocket lifetime# (avoids reconnect overhead on every message)async with AsyncExitStack() as stack:mcp_session_factory = getattr(session_env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = (await self._run_in_session_executor(session_id,session_env.reset,**valid_kwargs,))self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = (await self._run_in_session_executor(session_id, session_env.step, action))self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,session_id=session_id,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass75 unmodified linesfrom .web_interface import create_web_interface_appreturn create_web_interface_app(cast(Any, env),action_cls,observation_cls,env_name,
55 unmodified lines565758596061102 unmodified lines164165166167168169122 unmodified lines29229329429529629729873 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943955 unmodified lines4014024034044054064074084094104113 unmodified lines4154164174184194204212 unmodified lines4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874882 unmodified lines49149249349449549649749849950050150250350450550614 unmodified lines5215225235245255265275285295305315325335345355365375385395405415423 unmodified lines5465475485495505515525535545555566 unmodified lines56356456556656756856957057157257357457557657757857958058158258358458558658758858959059155 unmodified linesimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom typing import Any, Callable, Dict, Optionalfrom fastmcp import Client102 unmodified lines# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)@propertydef supports_code_mode(self) -> bool:"""Check if this environment supports code mode (execute_code)."""122 unmodified lines# If mode is None, register with FastMCP as usualif mode is None:decorated_func = self.mcp_server.tool()(func)self._mode_tools[tool_name][None] = funcreturn decorated_func73 unmodified linesreturn self._step_impl(action, timeout_s=timeout_s, **kwargs)def _handle_list_tools(self) -> ListToolsObservation:"""Handle a ListToolsAction by querying the MCP server.Returns:ListToolsObservation containing all available tools with theirnames, descriptions, and input schemas, filtered by current mode."""try:# Get current modecurrent_mode = getattr(self, "_mode", None)# Start with tools from FastMCP server (mode=None tools)tools_result = run_async_safely(self._async_list_tools())# Build list of Tool objectstools = []# Add FastMCP tools that are not mode-specificfor tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(5 unmodified lineselse {},))# Add mode-specific tools available in current modefor tool_name, mode_schemas in self._mode_tool_schemas.items():if None in mode_schemas:# Tool available in all modesschema = mode_schemas[None]tools.append(Tool(3 unmodified lines))elif current_mode in mode_schemas:# Tool available in current modeschema = mode_schemas[current_mode]tools.append(Tool(2 unmodified linesinput_schema=schema["input_schema"],))return ListToolsObservation(tools=tools)except Exception as e:# Return an observation with error in metadatareturn ListToolsObservation(tools=[],metadata={"error": str(e),"error_type": "list_tools_failed",},)async def _async_list_tools(self) -> list:"""Async helper to list tools from the MCP client.Returns:List of tool objects from the MCP server."""async with self.mcp_client:return await self.mcp_client.list_tools()def _handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Handle a CallToolAction by invoking the specified tool.Args:action: The CallToolAction containing tool_name and arguments.timeout_s: Timeout in seconds. Defaults to MCP_TOOL_CALL_TIMEOUT (30s).Returns:CallToolObservation with the tool's result or an error."""timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUT# Check if this is a mode-specific tooltool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]# Check if tool is available in current mode# Tool is available if:# 1. It has a None mode (available in all modes), OR# 2. It has an implementation for the current modeif None in mode_info:# Use the mode-agnostic versionfunc = mode_info[None]elif current_mode in mode_info:# Use the mode-specific versionfunc = mode_info[current_mode]else:# Tool not available in current modereturn CallToolObservation(tool_name=tool_name,result=None,2 unmodified linesmessage=f"Tool '{tool_name}' not available in {current_mode} mode",),)# Call the mode-specific function directlytry:# Check if function is async and await if necessaryif inspect.iscoroutinefunction(func):result = run_async_safely(func(**action.arguments))else:result = func(**action.arguments)# Wrap result in CallToolResult format to match FastMCP behaviorreturn CallToolObservation(tool_name=tool_name,result=CallToolResult(14 unmodified lines),)# Not a mode-specific tool, use FastMCPtry:# Run the async call_tool with timeout# Use run_async_safely to handle both sync and async contextsresult = run_async_safely(asyncio.wait_for(self._async_call_tool(action.tool_name, action.arguments),timeout=timeout,))return CallToolObservation(tool_name=action.tool_name,result=result,)except asyncio.TimeoutError:return CallToolObservation(tool_name=action.tool_name,3 unmodified linesmessage=f"Tool '{action.tool_name}' timed out after {timeout} seconds",),)except Exception as e:error_message = str(e)# Determine error type based on the exceptionif ("not found" in error_message.lower()or "unknown tool" in error_message.lower()6 unmodified lineserror_type = ToolErrorType.INVALID_ARGSelse:error_type = ToolErrorType.EXECUTION_ERRORreturn CallToolObservation(tool_name=action.tool_name,result=None,error=ToolError(error_type=error_type,message=error_message,),)async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:"""Async helper to call a tool on the MCP server.Args:tool_name: Name of the tool to invoke.arguments: Dictionary of arguments to pass to the tool.Returns:The result from the tool execution."""async with self.mcp_client:return await self.mcp_client.call_tool(tool_name, arguments)@abstractmethoddef _step_impl(55 unmodified lines56575859606162102 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216122 unmodified lines33934034134234334434534673 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674685 unmodified lines4744754764774784794804813 unmodified lines4854864874884894902 unmodified lines4934944954964974984995005015025035045055065075085095105115125135145155165175185195205215222 unmodified lines52552652752852953053153253353453514 unmodified lines5505515525535545555565575585595605613 unmodified lines5655665675685695705715726 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161255 unmodified linesimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom contextlib import asynccontextmanagerfrom typing import Any, Callable, Dict, Optionalfrom fastmcp import Client102 unmodified lines# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)def _require_mcp_client(self) -> Any:"""Return MCP client or raise if environment has been closed."""if self.mcp_client is None:raise RuntimeError("MCP client is not available; environment is closed")return self.mcp_clientdef _require_mcp_server(self) -> Any:"""Return MCP server or raise if environment has been closed."""if self.mcp_server is None:raise RuntimeError("MCP server is not available; environment is closed")return self.mcp_server@asynccontextmanagerasync def mcp_session(self):"""Context manager for MCP client sessions.This wrapper serves two purposes:1. **Null guard** — raises a clear error if ``close()`` has alreadybeen called (``mcp_client`` is ``None``).2. **AsyncExitStack adapter** — FastMCP's ``Client.__aenter__``creates a background ``asyncio.Task`` for session management.When entered directly via ``AsyncExitStack`` in the HTTP sessionpath (``_create_session``), this task can be cancelled by ASGIharnesses (e.g. Starlette ``TestClient``) between requests,corrupting session state. Wrapping in an ``asynccontextmanager``generator isolates the task lifecycle: the generator frame keeps``async with client:`` suspended at ``yield``, so cleanup onlyruns when the stack explicitly closes the generator — not whenthe event loop cancels orphaned tasks.Delegates to FastMCP's ``Client`` context manager which isreentrant: the first entry opens the transport and subsequent(nested) entries simply increment an internal reference counter.The transport is closed only when the outermost context exits.No external lock is needed because ``Client._connect`` /``Client._disconnect`` already serialise connection state changesthrough their own ``anyio.Lock``."""client = self._require_mcp_client()async with client:yield client@propertydef supports_code_mode(self) -> bool:"""Check if this environment supports code mode (execute_code)."""122 unmodified lines# If mode is None, register with FastMCP as usualif mode is None:mcp_server = self._require_mcp_server()decorated_func = mcp_server.tool()(func)self._mode_tools[tool_name][None] = funcreturn decorated_func73 unmodified linesreturn self._step_impl(action, timeout_s=timeout_s, **kwargs)def _handle_list_tools(self) -> ListToolsObservation:"""Sync wrapper — delegates to the canonical async implementation."""return run_async_safely(self._async_handle_list_tools())async def _async_list_tools(self) -> list:"""Async helper to list tools from the MCP client.Returns:List of tool objects from the MCP server."""async with self.mcp_session() as client:return await client.list_tools()def _handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Sync wrapper — delegates to the canonical async implementation."""return run_async_safely(self._async_handle_call_tool(action, timeout_s=timeout_s))async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:"""Async helper to call a tool on the MCP server.Args:tool_name: Name of the tool to invoke.arguments: Dictionary of arguments to pass to the tool.Returns:The result from the tool execution."""async with self.mcp_session() as client:return await client.call_tool(tool_name, arguments)async def _async_handle_list_tools(self) -> ListToolsObservation:"""Async version of _handle_list_tools — avoids run_async_safely."""try:current_mode = getattr(self, "_mode", None)tools_result = await self._async_list_tools()tools = []for tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(5 unmodified lineselse {},))for tool_name, mode_schemas in self._mode_tool_schemas.items():if None in mode_schemas:schema = mode_schemas[None]tools.append(Tool(3 unmodified lines))elif current_mode in mode_schemas:schema = mode_schemas[current_mode]tools.append(Tool(2 unmodified linesinput_schema=schema["input_schema"],))return ListToolsObservation(tools=tools)except Exception as e:return ListToolsObservation(tools=[],metadata={"error": str(e), "error_type": "list_tools_failed"},)async def _async_handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Async version of _handle_call_tool — avoids run_async_safely."""timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUTtool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]if None in mode_info:func = mode_info[None]elif current_mode in mode_info:func = mode_info[current_mode]else:return CallToolObservation(tool_name=tool_name,result=None,2 unmodified linesmessage=f"Tool '{tool_name}' not available in {current_mode} mode",),)try:if inspect.iscoroutinefunction(func):result = await func(**action.arguments)else:result = func(**action.arguments)return CallToolObservation(tool_name=tool_name,result=CallToolResult(14 unmodified lines),)try:result = await asyncio.wait_for(self._async_call_tool(action.tool_name, action.arguments),timeout=timeout,)return CallToolObservation(tool_name=action.tool_name, result=result)except asyncio.TimeoutError:return CallToolObservation(tool_name=action.tool_name,3 unmodified linesmessage=f"Tool '{action.tool_name}' timed out after {timeout} seconds",),)except Exception as e:error_message = str(e)if ("not found" in error_message.lower()or "unknown tool" in error_message.lower()6 unmodified lineserror_type = ToolErrorType.INVALID_ARGSelse:error_type = ToolErrorType.EXECUTION_ERRORreturn CallToolObservation(tool_name=action.tool_name,result=None,error=ToolError(error_type=error_type, message=error_message),)async def step_async(self,action: Action,timeout_s: Optional[float] = None,**kwargs: Any,) -> Observation:"""Async step that routes MCP actions without going through run_async_safely.The WebSocket handler calls this directly on the outer event loop, wherethe MCP session is already open, avoiding the thread/event-loop deadlockthat occurs when the sync step() path is used via run_in_executor."""if isinstance(action, ListToolsAction):return await self._async_handle_list_tools()elif isinstance(action, CallToolAction):return await self._async_handle_call_tool(action, timeout_s=timeout_s)else:loop = asyncio.get_event_loop()return await loop.run_in_executor(None, lambda: self._step_impl(action, timeout_s=timeout_s, **kwargs))@abstractmethoddef _step_impl(
13 unmodified lines141516171819202122232425262710 unmodified lines38394041424318 unmodified lines62636465666713 unmodified linesfrom typing import Any, Dict, Typefrom .types import Action, Observationdef deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:"""Convert JSON dict to Action instance using Pydantic validation.This is a basic deserialization that works for most environments.For special cases (e.g., tensor fields, custom type conversions),use deserialize_action_with_preprocessing().10 unmodified linesNote:This uses Pydantic's model_validate() for automatic validation."""return action_cls.model_validate(action_data)18 unmodified linesRaises:ValidationError: If action_data is invalid for the action class"""processed_data = {}for key, value in action_data.items():13 unmodified lines1415161718192021222324252627282930313233343536373839404110 unmodified lines525354555657585960616263646566676818 unmodified lines8788899091929394959697989910010113 unmodified linesfrom typing import Any, Dict, Typefrom .mcp_types import CallToolAction, ListToolsActionfrom .types import Action, Observation# MCP action types keyed by their "type" discriminator value.# These are checked before the environment's own action_cls so that# ListToolsAction / CallToolAction payloads are never rejected by an# unrelated Pydantic model._MCP_ACTION_TYPES: Dict[str, Type[Action]] = {"list_tools": ListToolsAction,"call_tool": CallToolAction,}def deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:"""Convert JSON dict to Action instance using Pydantic validation.MCP action types (``list_tools``, ``call_tool``) are recognisedautomatically via the ``"type"`` discriminator field, regardless ofthe environment's configured ``action_cls``. All other payloadsfall through to ``action_cls.model_validate()``.For special cases (e.g., tensor fields, custom type conversions),use deserialize_action_with_preprocessing().10 unmodified linesNote:This uses Pydantic's model_validate() for automatic validation."""# Route MCP action types before falling through to the env action_cls.# Only intercept when action_cls is the generic Action base or itself an# MCP type (i.e. the server hosts an MCP environment). This avoids# silently bypassing env-specific validation for non-MCP environments# that happen to use "call_tool" / "list_tools" as a type discriminator.action_type = action_data.get("type")if action_type in _MCP_ACTION_TYPES:mcp_cls = _MCP_ACTION_TYPES[action_type]if action_cls is Action or action_cls in _MCP_ACTION_TYPES.values():return mcp_cls.model_validate(action_data)return action_cls.model_validate(action_data)18 unmodified linesRaises:ValidationError: If action_data is invalid for the action class"""# Route MCP action types before preprocessing (they don't need it).# Same guard as deserialize_action: only intercept when action_cls is# the generic Action base or itself an MCP type.action_type = action_data.get("type")if action_type in _MCP_ACTION_TYPES:mcp_cls = _MCP_ACTION_TYPES[action_type]if action_cls is Action or action_cls in _MCP_ACTION_TYPES.values():return mcp_cls.model_validate(action_data)processed_data = {}for key, value in action_data.items():
14 unmodified lines15161718192021222324252627241 unmodified lines26927027127227327442 unmodified lines317318319320321322323324325326327100 unmodified lines42842943043143243315 unmodified lines44945045145245345445545645717 unmodified lines47547647747847948048123 unmodified lines50550650750850951051114 unmodified linesfrom __future__ import annotationsimport asyncioimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Typeimport gradio as grfrom fastapi import FastAPI, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel, ConfigDict, Fieldfrom .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME241 unmodified lines# Thread pool for running sync code (e.g., Playwright sync API) in async contextself._executor = ThreadPoolExecutor(max_workers=1)async def _run_sync_in_thread_pool(self, func, *args, **kwargs):"""Run a synchronous function in the thread pool executor.42 unmodified linesfor client in disconnected_clients:self.connected_clients.remove(client)async def reset_environment(self) -> Dict[str, Any]:"""Reset the environment and update state."""# Run sync reset in thread pool to avoid blocking event loop# and to support environments using sync libraries (e.g., Playwright)observation: Observation = await self._run_sync_in_thread_pool(self.env.reset)state: State = self.env.state# Serialize observation once using shared utility100 unmodified linesweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Web API routes first (so they take precedence over Gradio mount at /web)@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""15 unmodified linesawait web_manager.disconnect_websocket(websocket)@app.post("/web/reset")async def web_reset():"""Reset endpoint for web interface."""return await web_manager.reset_environment()@app.post("/web/step")async def web_step(request: Dict[str, Any]):17 unmodified lines@app.get("/web/state")async def web_state():"""State endpoint for web interface."""return web_manager.get_state()action_fields = _extract_action_fields(action_cls)is_chat_env = _is_chat_env(action_cls)23 unmodified lines)gradio_blocks = gr.TabbedInterface([default_blocks, custom_blocks],tab_names=["Playground", "Visualization"],title=get_gradio_display_title(metadata),)else:14 unmodified lines151617181920212223242526272829241 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729842 unmodified lines341342343344345346347348349350351352353354355356357358359360361362363364100 unmodified lines46546646746846947047147247347447547647747847948015 unmodified lines49649749849950050150250350417 unmodified lines52252352452552652752852953053153253353423 unmodified lines55855956056156256356414 unmodified linesfrom __future__ import annotationsimport asyncioimport inspectimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Typeimport gradio as grfrom fastapi import Body, FastAPI, HTTPException, status, WebSocket, WebSocketDisconnectfrom fastapi.responses import RedirectResponsefrom pydantic import BaseModel, ConfigDict, Fieldfrom .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME241 unmodified lines# Thread pool for running sync code (e.g., Playwright sync API) in async contextself._executor = ThreadPoolExecutor(max_workers=1)@staticmethoddef _get_valid_kwargs(sig: inspect.Signature,kwargs: Dict[str, Any],skip_params: Optional[set[str]] = None,) -> Dict[str, Any]:"""Filter kwargs to only those accepted by the target function."""skip_params = skip_params or set()valid_kwargs: Dict[str, Any] = {}has_var_kwargs = any(param.kind == inspect.Parameter.VAR_KEYWORDfor param in sig.parameters.values())for key, value in kwargs.items():if key in skip_params:continueif key in sig.parameters or has_var_kwargs:valid_kwargs[key] = valuereturn valid_kwargsasync def _run_sync_in_thread_pool(self, func, *args, **kwargs):"""Run a synchronous function in the thread pool executor.42 unmodified linesfor client in disconnected_clients:self.connected_clients.remove(client)async def reset_environment(self, reset_kwargs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Reset the environment and update state."""reset_kwargs = reset_kwargs or {}is_async = self.env.reset_async.__func__ is not Environment.reset_asyncsig = inspect.signature(self.env.reset_async if is_async else self.env.reset)valid_kwargs = self._get_valid_kwargs(sig, reset_kwargs)if is_async:observation = await self.env.reset_async(**valid_kwargs)else:# Run sync reset in thread pool to avoid blocking event loop# and to support environments using sync libraries (e.g., Playwright)observation = await self._run_sync_in_thread_pool(self.env.reset, **valid_kwargs)state: State = self.env.state# Serialize observation once using shared utility100 unmodified linesweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Web API routes first (so they take precedence over Gradio mount at /web)@app.get("/", include_in_schema=False)async def web_root():"""Redirect the app root to the Gradio interface."""return RedirectResponse(url="/web/")@app.get("/web", include_in_schema=False)async def web_root_no_slash():"""Redirect /web to /web/ for mounted Gradio deployments behind proxies."""return RedirectResponse(url="/web/")@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""15 unmodified linesawait web_manager.disconnect_websocket(websocket)@app.post("/web/reset")async def web_reset(request: Optional[Dict[str, Any]] = Body(default=None)):"""Reset endpoint for web interface."""return await web_manager.reset_environment(request)@app.post("/web/step")async def web_step(request: Dict[str, Any]):17 unmodified lines@app.get("/web/state")async def web_state():"""State endpoint for web interface."""try:return web_manager.get_state()except RuntimeError as exc:raise HTTPException(status_code=status.HTTP_409_CONFLICT,detail=str(exc),) from excaction_fields = _extract_action_fields(action_cls)is_chat_env = _is_chat_env(action_cls)23 unmodified lines)gradio_blocks = gr.TabbedInterface([default_blocks, custom_blocks],tab_names=["Playground", "Custom"],title=get_gradio_display_title(metadata),)else:
51 unmodified lines52535455565760 unmodified lines11811912012112212314 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216313 unmodified lines17717817918018118218367 unmodified lines25125225325425525659 unmodified lines31631731831932032151 unmodified lines... result = env.call_tool("echo_message", message="Hello!")"""from typing import Any, Dict, List, Optionalfrom .client_types import StepResult60 unmodified lines)self._tools_cache: Optional[List[Tool]] = Noneself.use_production_mode = Falseasync def list_tools(self, use_cache: bool = True) -> List[Tool]:"""14 unmodified linesif use_cache and self._tools_cache is not None:return self._tools_cache# Use production mode HTTP endpoint if enabledif self.use_production_mode:import requests# Convert ws:// URL to http:// URLurl = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")# Remove /ws suffix if present and add /mcpurl = url.rstrip("/ws").rstrip("/") + "/mcp"try:response = requests.post(url,json={"jsonrpc": "2.0","method": "tools/list","params": {},"id": 1,},)data = response.json()if "result" in data and "tools" in data["result"]:tools = [Tool(13 unmodified linesreturn []result = await self.step(ListToolsAction())self._tools_cache = result.observation.toolsreturn self._tools_cachedef _step_payload(self, action: Any) -> Dict[str, Any]:67 unmodified linesstep_count=payload.get("step_count", 0),)class MCPToolClient(MCPClientBase):"""59 unmodified lines>>> result = await env.call_tool("greet", name="Claude")>>> print(result) # "Hello, Claude!""""action = CallToolAction(tool_name=name, arguments=kwargs)result = await self.step(action)obs = result.observation51 unmodified lines5253545556575860 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318414 unmodified lines19920020120220320420520620720820921021121221321421521613 unmodified lines23023123223323423523623723823924024167 unmodified lines30931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234359 unmodified lines40340440540640740840941041141241341441541641741841942042142242342442542642742851 unmodified lines... result = env.call_tool("echo_message", message="Hello!")"""import asynciofrom typing import Any, Dict, List, Optionalfrom .client_types import StepResult60 unmodified lines)self._tools_cache: Optional[List[Tool]] = Noneself.use_production_mode = Falseself._production_session_id: Optional[str] = Noneself._production_session_lock = asyncio.Lock()self._jsonrpc_request_id = 0self._http_client: Optional[Any] = None # lazily-created httpx.AsyncClientdef _next_request_id(self) -> int:"""Generate a monotonically increasing JSON-RPC request id."""self._jsonrpc_request_id += 1return self._jsonrpc_request_iddef _production_mcp_url(self) -> str:"""Build HTTP MCP endpoint URL from the client's websocket URL."""url = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")if url.endswith("/ws"):url = url[: -len("/ws")]return url.rstrip("/") + "/mcp"async def _get_http_client(self) -> Any:"""Return a shared httpx.AsyncClient, creating one lazily."""if self._http_client is None:import httpxself._http_client = httpx.AsyncClient()return self._http_clientasync def _production_mcp_request(self, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Send a JSON-RPC request to HTTP /mcp and return parsed JSON response."""client = await self._get_http_client()response = await client.post(self._production_mcp_url(),json={"jsonrpc": "2.0","method": method,"params": params or {},"id": self._next_request_id(),},timeout=self._message_timeout,)response.raise_for_status()return response.json()async def _ensure_production_session(self) -> str:"""Create and cache a persistent HTTP MCP session id if needed."""async with self._production_session_lock:if self._production_session_id is not None:return self._production_session_iddata = await self._production_mcp_request("openenv/session/create")if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"Failed to create MCP session: {message}")session_id = data.get("result", {}).get("session_id")if not session_id:raise RuntimeError("Failed to create MCP session: missing session_id")self._production_session_id = session_idreturn session_idasync def list_tools(self, use_cache: bool = True) -> List[Tool]:"""14 unmodified linesif use_cache and self._tools_cache is not None:return self._tools_cache# Use production mode HTTP endpoint if enabled.# Some tests instantiate with __new__ and skip __init__, so default missing flag to False.if getattr(self, "use_production_mode", False):try:session_id = await self._ensure_production_session()data = await self._production_mcp_request("tools/list",{"session_id": session_id},)if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"list_tools failed: {message}")if "result" in data and "tools" in data["result"]:tools = [Tool(13 unmodified linesreturn []result = await self.step(ListToolsAction())if isinstance(result.observation, ListToolsObservation):self._tools_cache = result.observation.toolsreturn self._tools_cache# Unexpected observation type; keep API stable with an empty tool list.self._tools_cache = []return self._tools_cachedef _step_payload(self, action: Any) -> Dict[str, Any]:67 unmodified linesstep_count=payload.get("step_count", 0),)async def close(self) -> None:"""Close client resources.In production MCP mode, this also closes the server-side persistentMCP session (best effort) before closing websocket/provider resources."""if self._production_session_id is not None:try:await self._production_mcp_request("openenv/session/close",{"session_id": self._production_session_id},)except Exception:# Best effort cleanup - do not mask normal close behaviorpassfinally:self._production_session_id = Noneif self._http_client is not None:try:await self._http_client.aclose()except Exception:passfinally:self._http_client = Noneawait super().close()class MCPToolClient(MCPClientBase):"""59 unmodified lines>>> result = await env.call_tool("greet", name="Claude")>>> print(result) # "Hello, Claude!""""if getattr(self, "use_production_mode", False):session_id = await self._ensure_production_session()data = await self._production_mcp_request("tools/call",{"name": name,"arguments": kwargs,"session_id": session_id,},)if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"Tool '{name}' failed: {message}")result = data.get("result")if isinstance(result, dict) and "data" in result:return result["data"]return resultaction = CallToolAction(tool_name=name, arguments=kwargs)result = await self.step(action)obs = result.observation
13 unmodified lines1415161718192021222313 unmodified lines"SyncEnvClient",]try:__version__ = metadata.version("openenv") # type: ignore[arg-type]except metadata.PackageNotFoundError: # pragma: no cover - local dev__version__ = "0.0.0"_LAZY_MODULES = {13 unmodified lines14151617181920212223242526272829303113 unmodified lines"SyncEnvClient",]def _load_package_version() -> str:"""Resolve the installed distribution version for the OpenEnv package."""for distribution_name in ("openenv-core", "openenv"):try:return metadata.version(distribution_name)except metadata.PackageNotFoundError:continuereturn "0.0.0"__version__ = _load_package_version()_LAZY_MODULES = {
16 unmodified lines1718192021222316 unmodified lines# Core OpenEnv runtime (provides FastAPI server + HTTP client types)# install from github# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git","openenv-core[core]>=0.2.1",# Environment-specific dependencies# Add all dependencies needed for your environment here# Examples:16 unmodified lines1718192021222316 unmodified lines# Core OpenEnv runtime (provides FastAPI server + HTTP client types)# install from github# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git","openenv-core[core]>=0.2.2",# Environment-specific dependencies# Add all dependencies needed for your environment here# Examples:
15 unmodified lines1617181920212223242526177 unmodified lines2042052062072082092102111 unmodified line213214215216217218102 unmodified lines32132232332432532632732832933033133210 unmodified lines34334434534634734834935032 unmodified lines38338438538638738869 unmodified lines45845946046146246362 unmodified lines5265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775782 unmodified lines58158258358458558658758858959059159259359459518 unmodified lines61461561661761861917 unmodified lines637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678252 unmodified lines93193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105015 unmodified lines10661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120075 unmodified lines127612771278127912801281128215 unmodified linesimport asyncioimport inspectimport jsonimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Callable, Dict, Optional, Typefrom fastapi import (Body,177 unmodified linesself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Environment] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()1 unmodified line# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)def _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.102 unmodified lines)raise EnvironmentFactoryError(factory_name) from easync with self._session_lock:self._sessions[session_id] = envself._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=current_time,step_count=0,environment_type=type(env).__name__,)10 unmodified linesasync with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:32 unmodified linesif increment_step:self._session_info[session_id].step_count += 1def get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.69 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),62 unmodified lines# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest, session_env: Optional[Environment] = None) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format."""method = request.methodrequest_id = request.id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelse:_env = self._env_factory()should_close = Truetry:if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump() if hasattr(t, "model_dump") else dict(t)for t in tools]},request_id=request_id,)elif method == McpMethod.TOOLS_CALL:params = request.paramstool_name = params.get("name")arguments = params.get("arguments", {})if not hasattr(_env, "mcp_client"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",2 unmodified linesif not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Missing 'name' in params",request_id=request_id,)# Use async context manager for MCP clientasync with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)# Ensure result is JSON serializable18 unmodified linesrequest_id=request_id,)finally:if should_close:_env.close()17 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request, session_env=session_env)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass252 unmodified linesJsonRpcErrorCode.PARSE_ERROR).model_dump()method = request.methodparams = request.paramsrequest_id = request.id# Create a temporary environment for MCP access_env = self._env_factory()try:# Check if environment supports MCPif not hasattr(_env, "mcp_client") and not hasattr(_env, "mcp_server"):return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,).model_dump()if method == McpMethod.TOOLS_LIST:# List tools from MCP serverif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:tools = await _env.mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,).model_dump()elif hasattr(_env, "mcp_server") and _env.mcp_server:# Use server directlytools = []for tool_name, tool in get_server_tools(_env.mcp_server).items():tool_dict = {"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},}tools.append(tool_dict)return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'name' is required",request_id=request_id,).model_dump()# Call tool via MCPif hasattr(_env, "mcp_client") and _env.mcp_client:async with _env.mcp_client:result = await _env.mcp_client.call_tool(name=tool_name, arguments=arguments)elif hasattr(_env, "mcp_server") and _env.mcp_server:# Call tool directly on FastMCP serverserver_tools = get_server_tools(_env.mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,).model_dump()# Make result JSON serializableserializable_result = _make_json_serializable(result)return JsonRpcResponse.success(result=serializable_result,request_id=request_id,).model_dump()else:return JsonRpcResponse.error_response(JsonRpcErrorCode.METHOD_NOT_FOUND,f"Method not found: {method}",request_id=request_id,).model_dump()except Exception as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=request_id,).model_dump()finally:_env.close()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")15 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await self._run_in_session_executor(session_id, session_env.reset, **valid_kwargs)self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = await self._run_in_session_executor(session_id, session_env.step, action)self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass75 unmodified linesfrom .web_interface import create_web_interface_appreturn create_web_interface_app(env,action_cls,observation_cls,env_name,15 unmodified lines161718192021222324252627282930177 unmodified lines2082092102112122132142152161 unmodified line218219220221222223224225226227228229230231102 unmodified lines33433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937010 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240340440540640732 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949069 unmodified lines56056156256356456556656756856957057157257357457557657757857962 unmodified lines6426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548552 unmodified lines85885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790818 unmodified lines92792892993093193293393493593693717 unmodified lines95595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013252 unmodified lines1266126712681269127012711272127315 unmodified lines1289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145575 unmodified lines153115321533153415351536153715 unmodified linesimport asyncioimport inspectimport jsonimport loggingimport osimport timeimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import AsyncExitStackfrom typing import Any, AsyncContextManager, Callable, cast, Dict, Optional, Type_MISSING = object()from fastapi import (Body,177 unmodified linesself.observation_cls = observation_cls# Session management for WebSocket connectionsself._sessions: Dict[str, Optional[Environment]] = {}self._session_executors: Dict[str, ThreadPoolExecutor] = {}self._session_stacks: Dict[str, AsyncExitStack] = {}self._session_info: Dict[str, SessionInfo] = {}self._session_lock = asyncio.Lock()1 unmodified line# This is needed for environments using sync libraries (e.g., Playwright)self._executor = ThreadPoolExecutor(max_workers=32)# Idle session reaper configuration.# Timeout is taken from ConcurrencyConfig.session_timeout;# None means no timeout (default — reaper is a no-op).self._session_idle_timeout_s: Optional[float] = (self._concurrency_config.session_timeout)self._reaper_task: Optional[asyncio.Task[None]] = Nonedef _validate_concurrency_safety(self) -> None:"""Validate that the environment supports the configured concurrency level.102 unmodified lines)raise EnvironmentFactoryError(factory_name) from e# Hold the MCP session open for the lifetime of this session,# matching the WebSocket path's AsyncExitStack pattern. This# prevents per-request MCP transport teardown/reconnection and# preserves FastMCP session state (ctx.set_state / ctx.get_state)# across HTTP calls within the same OpenEnv session.stack = AsyncExitStack()try:mcp_session_factory = getattr(env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)except Exception:# MCP transport failed to start — clean up the reserved slot,# the env, and the executor so they don't leak permanently# against _max_concurrent_envs.await stack.aclose() # best-effortasync with self._session_lock:self._sessions.pop(session_id, None)self._session_executors.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor)raiseasync with self._session_lock:self._sessions[session_id] = envself._session_stacks[session_id] = stacknow = time.time()self._session_info[session_id] = SessionInfo(session_id=session_id,created_at=current_time,last_activity_at=now,step_count=0,environment_type=type(env).__name__,)10 unmodified linesasync with self._session_lock:env = self._sessions.pop(session_id, None)executor = self._session_executors.pop(session_id, None)stack = self._session_stacks.pop(session_id, None)self._session_info.pop(session_id, None)await self._cleanup_session_resources(env, executor, stack)async def _cleanup_session_resources(self,env: Optional[Environment],executor: Optional[ThreadPoolExecutor],stack: Optional[AsyncExitStack] = None,) -> None:"""Close an environment and shut down its executor (best-effort)."""# Close the MCP session stack first — this gracefully exits the# mcp_session() context (and the underlying FastMCP Client session)# before we tear down the environment references.if stack is not None:try:await stack.aclose()except Exception:pass # Best effort cleanup# Run close() in the same executor where the env was created# This is required for thread-sensitive libraries like Playwright/greenletif env is not None:32 unmodified linesif increment_step:self._session_info[session_id].step_count += 1async def _reap_idle_sessions(self) -> None:"""Background task that periodically destroys sessions idle beyond the timeout."""timeout = self._session_idle_timeout_sif timeout is None:return # no timeout configured — noopinterval = max(timeout / 4, 5.0) # check frequently enoughwhile True:try:await asyncio.sleep(interval)now = time.time()stale_ids: list[str] = []async with self._session_lock:for sid, info in self._session_info.items():if now - info.last_activity_at > timeout:stale_ids.append(sid)for sid in stale_ids:# Re-check under lock: activity may have arrived since# the snapshot was taken, making this session active again.# Refresh `now` so slow _destroy_session calls don't cause# subsequent entries to be validated against a stale clock.now = time.time()async with self._session_lock:info = self._session_info.get(sid)if info is None or (now - info.last_activity_at) <= timeout:continueawait self._destroy_session(sid)except asyncio.CancelledError:breakexcept Exception as exc:logging.getLogger(__name__).warning("Idle-session reaper encountered an error (will retry): %s",exc,)def _start_reaper(self) -> None:"""Start the idle-session reaper if a timeout is configured."""if self._session_idle_timeout_s is not None and self._reaper_task is None:self._reaper_task = asyncio.create_task(self._reap_idle_sessions())def _stop_reaper(self) -> None:"""Cancel the reaper background task."""if self._reaper_task is not None:self._reaper_task.cancel()self._reaper_task = Nonedef get_session_info(self, session_id: str) -> Optional[SessionInfo]:"""Get information about a specific session.69 unmodified linesf"Invalid mode: '{mode}'. Must be one of: {valid_modes}")# Wire up idle-session reaper lifecycle via app eventsserver_ref = selfasync def _start_session_reaper() -> None:server_ref._start_reaper()async def _stop_session_reaper() -> None:server_ref._stop_reaper()if not getattr(app.router, "_openenv_reaper_registered", False):app.router.on_startup.append(_start_session_reaper)app.router.on_shutdown.append(_stop_session_reaper)app.router._openenv_reaper_registered = True # type: ignore[attr-defined]# Helper function to handle reset endpointasync def reset_handler(request: ResetRequest = Body(default_factory=ResetRequest),62 unmodified lines# Helper function to handle MCP endpointasync def mcp_handler(request: JsonRpcRequest,session_env: Optional[Environment] = None,session_id: Optional[str] = None,) -> JsonRpcResponse:"""Handle MCP JSON-RPC requests.Supports tools/list and tools/call methods in JSON-RPC 2.0 format,plus OpenEnv session lifecycle methods for HTTP MCP:- openenv/session/create- openenv/session/close"""method = request.methodrequest_id = request.idparams = request.paramsif not isinstance(params, dict):return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Params must be an object",request_id=request_id,)# OpenEnv extension methods for explicit MCP session management.# This enables persistent MCP lifecycles over HTTP /mcp, matching WebSocket semantics.if method == "openenv/session/create":if session_env is not None and session_id is not None:return JsonRpcResponse.success(result={"session_id": session_id},request_id=request_id,)try:created_session_id, _ = await self._create_session()except SessionCapacityError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),request_id=request_id,data={"active_sessions": e.active_sessions,"max_sessions": e.max_sessions,},)except EnvironmentFactoryError as e:return JsonRpcResponse.error_response(JsonRpcErrorCode.SERVER_ERROR,str(e),request_id=request_id,data={"factory_name": e.factory_name},)return JsonRpcResponse.success(result={"session_id": created_session_id},request_id=request_id,)if method == "openenv/session/close":target_session_id = params.get("session_id")if not target_session_id:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Invalid params - 'session_id' is required",request_id=request_id,)if session_id is not None and target_session_id == session_id:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,"Cannot close active WebSocket-managed session via MCP method",request_id=request_id,)async with self._session_lock:env = self._sessions.pop(target_session_id, _MISSING)if env is not _MISSING:executor = self._session_executors.pop(target_session_id, None)stack = self._session_stacks.pop(target_session_id, None)self._session_info.pop(target_session_id, None)else:executor = Nonestack = Noneif env is _MISSING:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Unknown session_id: {target_session_id}",request_id=request_id,)if env is None:# Session slot reserved but env factory still running;# re-insert the placeholder AND the executor so# _create_session can finish and the executor remains# tracked for eventual shutdown.async with self._session_lock:self._sessions[target_session_id] = Noneif executor is not None:self._session_executors[target_session_id] = executorreturn JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Session {target_session_id} is still initializing; retry shortly",request_id=request_id,)# env/executor/stack cleanup outside the lockawait self._cleanup_session_resources(env, executor, stack)return JsonRpcResponse.success(result={"session_id": target_session_id, "closed": True},request_id=request_id,)requested_session_id = params.get("session_id")managed_session_id = session_id# Use provided session environment or create temporary oneif session_env is not None:_env = session_envshould_close = Falseelif requested_session_id:async with self._session_lock:_env = self._sessions.get(requested_session_id, _MISSING)if _env is _MISSING:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Unknown session_id: {requested_session_id}",request_id=request_id,)if _env is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Session {requested_session_id} is still initializing; retry shortly",request_id=request_id,)should_close = Falsemanaged_session_id = requested_session_idelse:_env = self._env_factory()should_close = Truetry:mcp_client = getattr(_env, "mcp_client", None)mcp_server = getattr(_env, "mcp_server", None)mcp_session_factory = getattr(_env, "mcp_session", None)if method == McpMethod.TOOLS_LIST:# Check if environment is MCP-enabledif mcp_client is None and mcp_server is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",request_id=request_id,)if mcp_client:if managed_session_id and mcp_client.is_connected():# Session-managed with live transport — call# directly, no redundant re-entry.tools = await mcp_client.list_tools()elif callable(mcp_session_factory):# Stateless request, or session-managed but the# background transport was lost: (re-)open.mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())async with mcp_session_cm:tools = await mcp_client.list_tools()else:async with mcp_client:tools = await mcp_client.list_tools()return JsonRpcResponse.success(result={"tools": [t.model_dump()if hasattr(t, "model_dump")else dict(t)for t in tools]},request_id=request_id,)if mcp_server:tools = []for _tool_name, tool in get_server_tools(mcp_server).items():tools.append({"name": tool.name,"description": tool.description or "","inputSchema": tool.parameters or {},})return JsonRpcResponse.success(result={"tools": tools},request_id=request_id,)return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,)elif method == McpMethod.TOOLS_CALL:tool_name = params.get("name")arguments = params.get("arguments", {})if mcp_client is None and mcp_server is None:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"Environment does not support MCP",2 unmodified linesif not tool_name:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,"Missing 'name' in params",request_id=request_id,)if mcp_client:if managed_session_id and mcp_client.is_connected():# Session-managed with live transport.result = await mcp_client.call_tool(name=tool_name, arguments=arguments)elif callable(mcp_session_factory):# Stateless request, or session-managed but the# background transport was lost: (re-)open.mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())async with mcp_session_cm:result = await mcp_client.call_tool(name=tool_name, arguments=arguments)else:async with mcp_client:result = await mcp_client.call_tool(name=tool_name, arguments=arguments)elif mcp_server:server_tools = get_server_tools(mcp_server)if tool_name in server_tools:tool = server_tools[tool_name]if inspect.iscoroutinefunction(tool.fn):result = await tool.fn(**arguments)else:result = tool.fn(**arguments)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_PARAMS,f"Tool not found: {tool_name}",request_id=request_id,)else:return JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,"MCP server not available",request_id=request_id,)# Ensure result is JSON serializable18 unmodified linesrequest_id=request_id,)finally:if managed_session_id:self._update_session_activity(managed_session_id,increment_step=(method == McpMethod.TOOLS_CALL),)if should_close:_env.close()17 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for MCP websocket")# If environment has an mcp_session context manager, hold it open# for the lifetime of the websocket connectionasync with AsyncExitStack() as stack:mcp_session_factory = getattr(session_env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)while True:# Receive message from clientraw_message = await websocket.receive_text()try:jsonrpc_dict = json.loads(raw_message)jsonrpc_request = JsonRpcRequest(**jsonrpc_dict)except json.JSONDecodeError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.PARSE_ERROR,f"Parse error: {e}",)await websocket.send_text(error_resp.model_dump_json())continueexcept ValidationError as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)await websocket.send_text(error_resp.model_dump_json())continuetry:# Call mcp_handler with session environmentresponse = await mcp_handler(jsonrpc_request,session_env=session_env,session_id=session_id,)await websocket.send_text(response.model_dump_json())except Exception as e:error_resp = JsonRpcResponse.error_response(JsonRpcErrorCode.INTERNAL_ERROR,str(e),request_id=jsonrpc_request.id,)await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass252 unmodified linesJsonRpcErrorCode.PARSE_ERROR).model_dump()response = await mcp_handler(request)return response.model_dump()# Register WebSocket endpoint for persistent sessions@app.websocket("/ws")15 unmodified linestry:# Create session with dedicated environmentsession_id, session_env = await self._create_session()if session_env is None:raise RuntimeError("Session environment not initialized for websocket")# Keep MCP session open for entire websocket lifetime# (avoids reconnect overhead on every message)async with AsyncExitStack() as stack:mcp_session_factory = getattr(session_env, "mcp_session", None)if callable(mcp_session_factory):mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory())await stack.enter_async_context(mcp_session_cm)while True:# Receive message from clientraw_message = await websocket.receive_text()try:message_dict = json.loads(raw_message)except json.JSONDecodeError as e:error_resp = WSErrorResponse(data={"message": f"Invalid JSON: {e}","code": WSErrorCode.INVALID_JSON,})await websocket.send_text(error_resp.model_dump_json())continuemsg_type = message_dict.get("type", "")try:match msg_type:case "reset":msg = WSResetMessage(**message_dict)is_async = (session_env.reset_async.__func__is not Environment.reset_async)if is_async:sig = inspect.signature(session_env.reset_async)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = await session_env.reset_async(**valid_kwargs)else:sig = inspect.signature(session_env.reset)valid_kwargs = self._get_valid_kwargs(sig, msg.data)observation = (await self._run_in_session_executor(session_id,session_env.reset,**valid_kwargs,))self._update_session_activity(session_id)response = WSObservationResponse(data=serialize_observation(observation),)case "step":msg = WSStepMessage(**message_dict)action = deserialize_action(msg.data, self.action_cls)is_async = (session_env.step_async.__func__is not Environment.step_async)if is_async:observation = await session_env.step_async(action)else:observation = (await self._run_in_session_executor(session_id, session_env.step, action))self._update_session_activity(session_id, increment_step=True)response = WSObservationResponse(data=serialize_observation(observation))case "state":msg = WSStateMessage(**message_dict)state = session_env.stateif hasattr(state, "model_dump"):state_data = state.model_dump()else:state_data = dict(state) if state else {}response = WSStateResponse(data=state_data)case "close":msg = WSCloseMessage(**message_dict)breakcase "mcp":msg = WSMCPMessage(**message_dict)try:rpc_request = JsonRpcRequest(**msg.data)except (ValidationError, Exception) as e:rpc_response = JsonRpcResponse.error_response(JsonRpcErrorCode.INVALID_REQUEST,f"Invalid request: {e}",)else:rpc_response = await mcp_handler(rpc_request,session_env=session_env,session_id=session_id,)response = WSMCPResponse(data=rpc_response.model_dump())case _:response = WSErrorResponse(data={"message": f"Unknown message type: {msg_type}","code": WSErrorCode.UNKNOWN_TYPE,})await websocket.send_text(response.model_dump_json())except ValidationError as e:error_resp = WSErrorResponse(data={"message": "Invalid message","code": WSErrorCode.VALIDATION_ERROR,"errors": e.errors(),})await websocket.send_text(error_resp.model_dump_json())except Exception as e:error_resp = WSErrorResponse(data={"message": str(e),"code": WSErrorCode.EXECUTION_ERROR,})await websocket.send_text(error_resp.model_dump_json())except WebSocketDisconnect:pass75 unmodified linesfrom .web_interface import create_web_interface_appreturn create_web_interface_app(cast(Any, env),action_cls,observation_cls,env_name,
55 unmodified lines565758596061102 unmodified lines164165166167168169122 unmodified lines29229329429529629729873 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943955 unmodified lines4014024034044054064074084094104113 unmodified lines4154164174184194204212 unmodified lines4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874882 unmodified lines49149249349449549649749849950050150250350450550614 unmodified lines5215225235245255265275285295305315325335345355365375385395405415423 unmodified lines5465475485495505515525535545555566 unmodified lines56356456556656756856957057157257357457557657757857958058158258358458558658758858959059155 unmodified linesimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom typing import Any, Callable, Dict, Optionalfrom fastmcp import Client102 unmodified lines# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)@propertydef supports_code_mode(self) -> bool:"""Check if this environment supports code mode (execute_code)."""122 unmodified lines# If mode is None, register with FastMCP as usualif mode is None:decorated_func = self.mcp_server.tool()(func)self._mode_tools[tool_name][None] = funcreturn decorated_func73 unmodified linesreturn self._step_impl(action, timeout_s=timeout_s, **kwargs)def _handle_list_tools(self) -> ListToolsObservation:"""Handle a ListToolsAction by querying the MCP server.Returns:ListToolsObservation containing all available tools with theirnames, descriptions, and input schemas, filtered by current mode."""try:# Get current modecurrent_mode = getattr(self, "_mode", None)# Start with tools from FastMCP server (mode=None tools)tools_result = run_async_safely(self._async_list_tools())# Build list of Tool objectstools = []# Add FastMCP tools that are not mode-specificfor tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(5 unmodified lineselse {},))# Add mode-specific tools available in current modefor tool_name, mode_schemas in self._mode_tool_schemas.items():if None in mode_schemas:# Tool available in all modesschema = mode_schemas[None]tools.append(Tool(3 unmodified lines))elif current_mode in mode_schemas:# Tool available in current modeschema = mode_schemas[current_mode]tools.append(Tool(2 unmodified linesinput_schema=schema["input_schema"],))return ListToolsObservation(tools=tools)except Exception as e:# Return an observation with error in metadatareturn ListToolsObservation(tools=[],metadata={"error": str(e),"error_type": "list_tools_failed",},)async def _async_list_tools(self) -> list:"""Async helper to list tools from the MCP client.Returns:List of tool objects from the MCP server."""async with self.mcp_client:return await self.mcp_client.list_tools()def _handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Handle a CallToolAction by invoking the specified tool.Args:action: The CallToolAction containing tool_name and arguments.timeout_s: Timeout in seconds. Defaults to MCP_TOOL_CALL_TIMEOUT (30s).Returns:CallToolObservation with the tool's result or an error."""timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUT# Check if this is a mode-specific tooltool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]# Check if tool is available in current mode# Tool is available if:# 1. It has a None mode (available in all modes), OR# 2. It has an implementation for the current modeif None in mode_info:# Use the mode-agnostic versionfunc = mode_info[None]elif current_mode in mode_info:# Use the mode-specific versionfunc = mode_info[current_mode]else:# Tool not available in current modereturn CallToolObservation(tool_name=tool_name,result=None,2 unmodified linesmessage=f"Tool '{tool_name}' not available in {current_mode} mode",),)# Call the mode-specific function directlytry:# Check if function is async and await if necessaryif inspect.iscoroutinefunction(func):result = run_async_safely(func(**action.arguments))else:result = func(**action.arguments)# Wrap result in CallToolResult format to match FastMCP behaviorreturn CallToolObservation(tool_name=tool_name,result=CallToolResult(14 unmodified lines),)# Not a mode-specific tool, use FastMCPtry:# Run the async call_tool with timeout# Use run_async_safely to handle both sync and async contextsresult = run_async_safely(asyncio.wait_for(self._async_call_tool(action.tool_name, action.arguments),timeout=timeout,))return CallToolObservation(tool_name=action.tool_name,result=result,)except asyncio.TimeoutError:return CallToolObservation(tool_name=action.tool_name,3 unmodified linesmessage=f"Tool '{action.tool_name}' timed out after {timeout} seconds",),)except Exception as e:error_message = str(e)# Determine error type based on the exceptionif ("not found" in error_message.lower()or "unknown tool" in error_message.lower()6 unmodified lineserror_type = ToolErrorType.INVALID_ARGSelse:error_type = ToolErrorType.EXECUTION_ERRORreturn CallToolObservation(tool_name=action.tool_name,result=None,error=ToolError(error_type=error_type,message=error_message,),)async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:"""Async helper to call a tool on the MCP server.Args:tool_name: Name of the tool to invoke.arguments: Dictionary of arguments to pass to the tool.Returns:The result from the tool execution."""async with self.mcp_client:return await self.mcp_client.call_tool(tool_name, arguments)@abstractmethoddef _step_impl(55 unmodified lines56575859606162102 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216122 unmodified lines33934034134234334434534673 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674685 unmodified lines4744754764774784794804813 unmodified lines4854864874884894902 unmodified lines4934944954964974984995005015025035045055065075085095105115125135145155165175185195205215222 unmodified lines52552652752852953053153253353453514 unmodified lines5505515525535545555565575585595605613 unmodified lines5655665675685695705715726 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161255 unmodified linesimport inspectfrom abc import abstractmethodfrom collections import defaultdictfrom contextlib import asynccontextmanagerfrom typing import Any, Callable, Dict, Optionalfrom fastmcp import Client102 unmodified lines# Track tool schemas for list_tools: {tool_name: {mode: schema}}self._mode_tool_schemas = defaultdict(dict)def _require_mcp_client(self) -> Any:"""Return MCP client or raise if environment has been closed."""if self.mcp_client is None:raise RuntimeError("MCP client is not available; environment is closed")return self.mcp_clientdef _require_mcp_server(self) -> Any:"""Return MCP server or raise if environment has been closed."""if self.mcp_server is None:raise RuntimeError("MCP server is not available; environment is closed")return self.mcp_server@asynccontextmanagerasync def mcp_session(self):"""Context manager for MCP client sessions.This wrapper serves two purposes:1. **Null guard** — raises a clear error if ``close()`` has alreadybeen called (``mcp_client`` is ``None``).2. **AsyncExitStack adapter** — FastMCP's ``Client.__aenter__``creates a background ``asyncio.Task`` for session management.When entered directly via ``AsyncExitStack`` in the HTTP sessionpath (``_create_session``), this task can be cancelled by ASGIharnesses (e.g. Starlette ``TestClient``) between requests,corrupting session state. Wrapping in an ``asynccontextmanager``generator isolates the task lifecycle: the generator frame keeps``async with client:`` suspended at ``yield``, so cleanup onlyruns when the stack explicitly closes the generator — not whenthe event loop cancels orphaned tasks.Delegates to FastMCP's ``Client`` context manager which isreentrant: the first entry opens the transport and subsequent(nested) entries simply increment an internal reference counter.The transport is closed only when the outermost context exits.No external lock is needed because ``Client._connect`` /``Client._disconnect`` already serialise connection state changesthrough their own ``anyio.Lock``."""client = self._require_mcp_client()async with client:yield client@propertydef supports_code_mode(self) -> bool:"""Check if this environment supports code mode (execute_code)."""122 unmodified lines# If mode is None, register with FastMCP as usualif mode is None:mcp_server = self._require_mcp_server()decorated_func = mcp_server.tool()(func)self._mode_tools[tool_name][None] = funcreturn decorated_func73 unmodified linesreturn self._step_impl(action, timeout_s=timeout_s, **kwargs)def _handle_list_tools(self) -> ListToolsObservation:"""Sync wrapper — delegates to the canonical async implementation."""return run_async_safely(self._async_handle_list_tools())async def _async_list_tools(self) -> list:"""Async helper to list tools from the MCP client.Returns:List of tool objects from the MCP server."""async with self.mcp_session() as client:return await client.list_tools()def _handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Sync wrapper — delegates to the canonical async implementation."""return run_async_safely(self._async_handle_call_tool(action, timeout_s=timeout_s))async def _async_call_tool(self, tool_name: str, arguments: dict) -> Any:"""Async helper to call a tool on the MCP server.Args:tool_name: Name of the tool to invoke.arguments: Dictionary of arguments to pass to the tool.Returns:The result from the tool execution."""async with self.mcp_session() as client:return await client.call_tool(tool_name, arguments)async def _async_handle_list_tools(self) -> ListToolsObservation:"""Async version of _handle_list_tools — avoids run_async_safely."""try:current_mode = getattr(self, "_mode", None)tools_result = await self._async_list_tools()tools = []for tool in tools_result:if tool.name not in self._mode_tool_schemas:tools.append(5 unmodified lineselse {},))for tool_name, mode_schemas in self._mode_tool_schemas.items():if None in mode_schemas:schema = mode_schemas[None]tools.append(Tool(3 unmodified lines))elif current_mode in mode_schemas:schema = mode_schemas[current_mode]tools.append(Tool(2 unmodified linesinput_schema=schema["input_schema"],))return ListToolsObservation(tools=tools)except Exception as e:return ListToolsObservation(tools=[],metadata={"error": str(e), "error_type": "list_tools_failed"},)async def _async_handle_call_tool(self,action: CallToolAction,timeout_s: Optional[float] = None,) -> CallToolObservation:"""Async version of _handle_call_tool — avoids run_async_safely."""timeout = timeout_s if timeout_s is not None else MCP_TOOL_CALL_TIMEOUTtool_name = action.tool_namecurrent_mode = getattr(self, "_mode", None)if tool_name in self._mode_tools:mode_info = self._mode_tools[tool_name]if None in mode_info:func = mode_info[None]elif current_mode in mode_info:func = mode_info[current_mode]else:return CallToolObservation(tool_name=tool_name,result=None,2 unmodified linesmessage=f"Tool '{tool_name}' not available in {current_mode} mode",),)try:if inspect.iscoroutinefunction(func):result = await func(**action.arguments)else:result = func(**action.arguments)return CallToolObservation(tool_name=tool_name,result=CallToolResult(14 unmodified lines),)try:result = await asyncio.wait_for(self._async_call_tool(action.tool_name, action.arguments),timeout=timeout,)return CallToolObservation(tool_name=action.tool_name, result=result)except asyncio.TimeoutError:return CallToolObservation(tool_name=action.tool_name,3 unmodified linesmessage=f"Tool '{action.tool_name}' timed out after {timeout} seconds",),)except Exception as e:error_message = str(e)if ("not found" in error_message.lower()or "unknown tool" in error_message.lower()6 unmodified lineserror_type = ToolErrorType.INVALID_ARGSelse:error_type = ToolErrorType.EXECUTION_ERRORreturn CallToolObservation(tool_name=action.tool_name,result=None,error=ToolError(error_type=error_type, message=error_message),)async def step_async(self,action: Action,timeout_s: Optional[float] = None,**kwargs: Any,) -> Observation:"""Async step that routes MCP actions without going through run_async_safely.The WebSocket handler calls this directly on the outer event loop, wherethe MCP session is already open, avoiding the thread/event-loop deadlockthat occurs when the sync step() path is used via run_in_executor."""if isinstance(action, ListToolsAction):return await self._async_handle_list_tools()elif isinstance(action, CallToolAction):return await self._async_handle_call_tool(action, timeout_s=timeout_s)else:loop = asyncio.get_event_loop()return await loop.run_in_executor(None, lambda: self._step_impl(action, timeout_s=timeout_s, **kwargs))@abstractmethoddef _step_impl(
13 unmodified lines141516171819202122232425262710 unmodified lines38394041424318 unmodified lines62636465666713 unmodified linesfrom typing import Any, Dict, Typefrom .types import Action, Observationdef deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:"""Convert JSON dict to Action instance using Pydantic validation.This is a basic deserialization that works for most environments.For special cases (e.g., tensor fields, custom type conversions),use deserialize_action_with_preprocessing().10 unmodified linesNote:This uses Pydantic's model_validate() for automatic validation."""return action_cls.model_validate(action_data)18 unmodified linesRaises:ValidationError: If action_data is invalid for the action class"""processed_data = {}for key, value in action_data.items():13 unmodified lines1415161718192021222324252627282930313233343536373839404110 unmodified lines525354555657585960616263646566676818 unmodified lines8788899091929394959697989910010113 unmodified linesfrom typing import Any, Dict, Typefrom .mcp_types import CallToolAction, ListToolsActionfrom .types import Action, Observation# MCP action types keyed by their "type" discriminator value.# These are checked before the environment's own action_cls so that# ListToolsAction / CallToolAction payloads are never rejected by an# unrelated Pydantic model._MCP_ACTION_TYPES: Dict[str, Type[Action]] = {"list_tools": ListToolsAction,"call_tool": CallToolAction,}def deserialize_action(action_data: Dict[str, Any], action_cls: Type[Action]) -> Action:"""Convert JSON dict to Action instance using Pydantic validation.MCP action types (``list_tools``, ``call_tool``) are recognisedautomatically via the ``"type"`` discriminator field, regardless ofthe environment's configured ``action_cls``. All other payloadsfall through to ``action_cls.model_validate()``.For special cases (e.g., tensor fields, custom type conversions),use deserialize_action_with_preprocessing().10 unmodified linesNote:This uses Pydantic's model_validate() for automatic validation."""# Route MCP action types before falling through to the env action_cls.# Only intercept when action_cls is the generic Action base or itself an# MCP type (i.e. the server hosts an MCP environment). This avoids# silently bypassing env-specific validation for non-MCP environments# that happen to use "call_tool" / "list_tools" as a type discriminator.action_type = action_data.get("type")if action_type in _MCP_ACTION_TYPES:mcp_cls = _MCP_ACTION_TYPES[action_type]if action_cls is Action or action_cls in _MCP_ACTION_TYPES.values():return mcp_cls.model_validate(action_data)return action_cls.model_validate(action_data)18 unmodified linesRaises:ValidationError: If action_data is invalid for the action class"""# Route MCP action types before preprocessing (they don't need it).# Same guard as deserialize_action: only intercept when action_cls is# the generic Action base or itself an MCP type.action_type = action_data.get("type")if action_type in _MCP_ACTION_TYPES:mcp_cls = _MCP_ACTION_TYPES[action_type]if action_cls is Action or action_cls in _MCP_ACTION_TYPES.values():return mcp_cls.model_validate(action_data)processed_data = {}for key, value in action_data.items():
14 unmodified lines15161718192021222324252627241 unmodified lines26927027127227327442 unmodified lines317318319320321322323324325326327100 unmodified lines42842943043143243315 unmodified lines44945045145245345445545645717 unmodified lines47547647747847948048123 unmodified lines50550650750850951051114 unmodified linesfrom __future__ import annotationsimport asyncioimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Typeimport gradio as grfrom fastapi import FastAPI, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel, ConfigDict, Fieldfrom .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME241 unmodified lines# Thread pool for running sync code (e.g., Playwright sync API) in async contextself._executor = ThreadPoolExecutor(max_workers=1)async def _run_sync_in_thread_pool(self, func, *args, **kwargs):"""Run a synchronous function in the thread pool executor.42 unmodified linesfor client in disconnected_clients:self.connected_clients.remove(client)async def reset_environment(self) -> Dict[str, Any]:"""Reset the environment and update state."""# Run sync reset in thread pool to avoid blocking event loop# and to support environments using sync libraries (e.g., Playwright)observation: Observation = await self._run_sync_in_thread_pool(self.env.reset)state: State = self.env.state# Serialize observation once using shared utility100 unmodified linesweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Web API routes first (so they take precedence over Gradio mount at /web)@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""15 unmodified linesawait web_manager.disconnect_websocket(websocket)@app.post("/web/reset")async def web_reset():"""Reset endpoint for web interface."""return await web_manager.reset_environment()@app.post("/web/step")async def web_step(request: Dict[str, Any]):17 unmodified lines@app.get("/web/state")async def web_state():"""State endpoint for web interface."""return web_manager.get_state()action_fields = _extract_action_fields(action_cls)is_chat_env = _is_chat_env(action_cls)23 unmodified lines)gradio_blocks = gr.TabbedInterface([default_blocks, custom_blocks],tab_names=["Playground", "Visualization"],title=get_gradio_display_title(metadata),)else:14 unmodified lines151617181920212223242526272829241 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729842 unmodified lines341342343344345346347348349350351352353354355356357358359360361362363364100 unmodified lines46546646746846947047147247347447547647747847948015 unmodified lines49649749849950050150250350417 unmodified lines52252352452552652752852953053153253353423 unmodified lines55855956056156256356414 unmodified linesfrom __future__ import annotationsimport asyncioimport inspectimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Typeimport gradio as grfrom fastapi import Body, FastAPI, HTTPException, status, WebSocket, WebSocketDisconnectfrom fastapi.responses import RedirectResponsefrom pydantic import BaseModel, ConfigDict, Fieldfrom .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME241 unmodified lines# Thread pool for running sync code (e.g., Playwright sync API) in async contextself._executor = ThreadPoolExecutor(max_workers=1)@staticmethoddef _get_valid_kwargs(sig: inspect.Signature,kwargs: Dict[str, Any],skip_params: Optional[set[str]] = None,) -> Dict[str, Any]:"""Filter kwargs to only those accepted by the target function."""skip_params = skip_params or set()valid_kwargs: Dict[str, Any] = {}has_var_kwargs = any(param.kind == inspect.Parameter.VAR_KEYWORDfor param in sig.parameters.values())for key, value in kwargs.items():if key in skip_params:continueif key in sig.parameters or has_var_kwargs:valid_kwargs[key] = valuereturn valid_kwargsasync def _run_sync_in_thread_pool(self, func, *args, **kwargs):"""Run a synchronous function in the thread pool executor.42 unmodified linesfor client in disconnected_clients:self.connected_clients.remove(client)async def reset_environment(self, reset_kwargs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Reset the environment and update state."""reset_kwargs = reset_kwargs or {}is_async = self.env.reset_async.__func__ is not Environment.reset_asyncsig = inspect.signature(self.env.reset_async if is_async else self.env.reset)valid_kwargs = self._get_valid_kwargs(sig, reset_kwargs)if is_async:observation = await self.env.reset_async(**valid_kwargs)else:# Run sync reset in thread pool to avoid blocking event loop# and to support environments using sync libraries (e.g., Playwright)observation = await self._run_sync_in_thread_pool(self.env.reset, **valid_kwargs)state: State = self.env.state# Serialize observation once using shared utility100 unmodified linesweb_manager = WebInterfaceManager(env, action_cls, observation_cls, metadata)# Web API routes first (so they take precedence over Gradio mount at /web)@app.get("/", include_in_schema=False)async def web_root():"""Redirect the app root to the Gradio interface."""return RedirectResponse(url="/web/")@app.get("/web", include_in_schema=False)async def web_root_no_slash():"""Redirect /web to /web/ for mounted Gradio deployments behind proxies."""return RedirectResponse(url="/web/")@app.get("/web/metadata")async def web_metadata():"""Get environment metadata."""15 unmodified linesawait web_manager.disconnect_websocket(websocket)@app.post("/web/reset")async def web_reset(request: Optional[Dict[str, Any]] = Body(default=None)):"""Reset endpoint for web interface."""return await web_manager.reset_environment(request)@app.post("/web/step")async def web_step(request: Dict[str, Any]):17 unmodified lines@app.get("/web/state")async def web_state():"""State endpoint for web interface."""try:return web_manager.get_state()except RuntimeError as exc:raise HTTPException(status_code=status.HTTP_409_CONFLICT,detail=str(exc),) from excaction_fields = _extract_action_fields(action_cls)is_chat_env = _is_chat_env(action_cls)23 unmodified lines)gradio_blocks = gr.TabbedInterface([default_blocks, custom_blocks],tab_names=["Playground", "Custom"],title=get_gradio_display_title(metadata),)else:
51 unmodified lines52535455565760 unmodified lines11811912012112212314 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216313 unmodified lines17717817918018118218367 unmodified lines25125225325425525659 unmodified lines31631731831932032151 unmodified lines... result = env.call_tool("echo_message", message="Hello!")"""from typing import Any, Dict, List, Optionalfrom .client_types import StepResult60 unmodified lines)self._tools_cache: Optional[List[Tool]] = Noneself.use_production_mode = Falseasync def list_tools(self, use_cache: bool = True) -> List[Tool]:"""14 unmodified linesif use_cache and self._tools_cache is not None:return self._tools_cache# Use production mode HTTP endpoint if enabledif self.use_production_mode:import requests# Convert ws:// URL to http:// URLurl = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")# Remove /ws suffix if present and add /mcpurl = url.rstrip("/ws").rstrip("/") + "/mcp"try:response = requests.post(url,json={"jsonrpc": "2.0","method": "tools/list","params": {},"id": 1,},)data = response.json()if "result" in data and "tools" in data["result"]:tools = [Tool(13 unmodified linesreturn []result = await self.step(ListToolsAction())self._tools_cache = result.observation.toolsreturn self._tools_cachedef _step_payload(self, action: Any) -> Dict[str, Any]:67 unmodified linesstep_count=payload.get("step_count", 0),)class MCPToolClient(MCPClientBase):"""59 unmodified lines>>> result = await env.call_tool("greet", name="Claude")>>> print(result) # "Hello, Claude!""""action = CallToolAction(tool_name=name, arguments=kwargs)result = await self.step(action)obs = result.observation51 unmodified lines5253545556575860 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318414 unmodified lines19920020120220320420520620720820921021121221321421521613 unmodified lines23023123223323423523623723823924024167 unmodified lines30931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234359 unmodified lines40340440540640740840941041141241341441541641741841942042142242342442542642742851 unmodified lines... result = env.call_tool("echo_message", message="Hello!")"""import asynciofrom typing import Any, Dict, List, Optionalfrom .client_types import StepResult60 unmodified lines)self._tools_cache: Optional[List[Tool]] = Noneself.use_production_mode = Falseself._production_session_id: Optional[str] = Noneself._production_session_lock = asyncio.Lock()self._jsonrpc_request_id = 0self._http_client: Optional[Any] = None # lazily-created httpx.AsyncClientdef _next_request_id(self) -> int:"""Generate a monotonically increasing JSON-RPC request id."""self._jsonrpc_request_id += 1return self._jsonrpc_request_iddef _production_mcp_url(self) -> str:"""Build HTTP MCP endpoint URL from the client's websocket URL."""url = self._ws_url.replace("ws://", "http://").replace("wss://", "https://")if url.endswith("/ws"):url = url[: -len("/ws")]return url.rstrip("/") + "/mcp"async def _get_http_client(self) -> Any:"""Return a shared httpx.AsyncClient, creating one lazily."""if self._http_client is None:import httpxself._http_client = httpx.AsyncClient()return self._http_clientasync def _production_mcp_request(self, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Send a JSON-RPC request to HTTP /mcp and return parsed JSON response."""client = await self._get_http_client()response = await client.post(self._production_mcp_url(),json={"jsonrpc": "2.0","method": method,"params": params or {},"id": self._next_request_id(),},timeout=self._message_timeout,)response.raise_for_status()return response.json()async def _ensure_production_session(self) -> str:"""Create and cache a persistent HTTP MCP session id if needed."""async with self._production_session_lock:if self._production_session_id is not None:return self._production_session_iddata = await self._production_mcp_request("openenv/session/create")if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"Failed to create MCP session: {message}")session_id = data.get("result", {}).get("session_id")if not session_id:raise RuntimeError("Failed to create MCP session: missing session_id")self._production_session_id = session_idreturn session_idasync def list_tools(self, use_cache: bool = True) -> List[Tool]:"""14 unmodified linesif use_cache and self._tools_cache is not None:return self._tools_cache# Use production mode HTTP endpoint if enabled.# Some tests instantiate with __new__ and skip __init__, so default missing flag to False.if getattr(self, "use_production_mode", False):try:session_id = await self._ensure_production_session()data = await self._production_mcp_request("tools/list",{"session_id": session_id},)if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"list_tools failed: {message}")if "result" in data and "tools" in data["result"]:tools = [Tool(13 unmodified linesreturn []result = await self.step(ListToolsAction())if isinstance(result.observation, ListToolsObservation):self._tools_cache = result.observation.toolsreturn self._tools_cache# Unexpected observation type; keep API stable with an empty tool list.self._tools_cache = []return self._tools_cachedef _step_payload(self, action: Any) -> Dict[str, Any]:67 unmodified linesstep_count=payload.get("step_count", 0),)async def close(self) -> None:"""Close client resources.In production MCP mode, this also closes the server-side persistentMCP session (best effort) before closing websocket/provider resources."""if self._production_session_id is not None:try:await self._production_mcp_request("openenv/session/close",{"session_id": self._production_session_id},)except Exception:# Best effort cleanup - do not mask normal close behaviorpassfinally:self._production_session_id = Noneif self._http_client is not None:try:await self._http_client.aclose()except Exception:passfinally:self._http_client = Noneawait super().close()class MCPToolClient(MCPClientBase):"""59 unmodified lines>>> result = await env.call_tool("greet", name="Claude")>>> print(result) # "Hello, Claude!""""if getattr(self, "use_production_mode", False):session_id = await self._ensure_production_session()data = await self._production_mcp_request("tools/call",{"name": name,"arguments": kwargs,"session_id": session_id,},)if "error" in data:message = data.get("error", {}).get("message", "unknown error")raise RuntimeError(f"Tool '{name}' failed: {message}")result = data.get("result")if isinstance(result, dict) and "data" in result:return result["data"]return resultaction = CallToolAction(tool_name=name, arguments=kwargs)result = await self.step(action)obs = result.observation
12345612 unmodified lines19202122232436 unmodified lines61626364656667Metadata-Version: 2.4Name: openenv-coreVersion: 0.2.2.dev0Summary: A unified framework for reinforcement learning environmentsRequires-Python: >=3.10Description-Content-Type: text/markdown12 unmodified linesRequires-Dist: websockets>=15.0.1Requires-Dist: fastmcp>=3.0.0Requires-Dist: gradio>=4.0.0Provides-Extra: coreRequires-Dist: fastapi>=0.104.0; extra == "core"Requires-Dist: pydantic>=2.0.0; extra == "core"36 unmodified linesAn e2e framework for creating, deploying and using isolated execution environments for agentic RL training, built using Gymnasium style simple APIs.[](https://pypi.org/project/openenv/)[](https://discord.gg/YsTYBh6PD9)[](https://colab.research.google.com/github/meta-pytorch/OpenEnv/blob/main/examples/OpenEnv_Tutorial.ipynb)[](https://meta-pytorch.org/OpenEnv/)12345612 unmodified lines1920212223242536 unmodified lines62636465666768Metadata-Version: 2.4Name: openenv-coreVersion: 0.2.3Summary: A unified framework for reinforcement learning environmentsRequires-Python: >=3.10Description-Content-Type: text/markdown12 unmodified linesRequires-Dist: websockets>=15.0.1Requires-Dist: fastmcp>=3.0.0Requires-Dist: gradio>=4.0.0Requires-Dist: httpx>=0.28.1Provides-Extra: coreRequires-Dist: fastapi>=0.104.0; extra == "core"Requires-Dist: pydantic>=2.0.0; extra == "core"36 unmodified linesAn e2e framework for creating, deploying and using isolated execution environments for agentic RL training, built using Gymnasium style simple APIs.[](https://pypi.org/project/openenv-core/)[](https://discord.gg/YsTYBh6PD9)[](https://colab.research.google.com/github/meta-pytorch/OpenEnv/blob/main/examples/OpenEnv_Tutorial.ipynb)[](https://meta-pytorch.org/OpenEnv/)
Dockerfile+52-25
README.md+2-2
client.py+8-32
envs/chat_env/client.py+8-32
envs/chat_env/models.py+33-14
envs/chat_env/openenv_chat_env.egg-info/PKG-INFOAdded+14
envs/chat_env/openenv_chat_env.egg-info/SOURCES.txtAdded+18
envs/chat_env/openenv_chat_env.egg-info/dependency_links.txtAdded+1
envs/chat_env/openenv_chat_env.egg-info/entry_points.txtAdded+2
envs/chat_env/openenv_chat_env.egg-info/requires.txtAdded+10
envs/chat_env/openenv_chat_env.egg-info/top_level.txtAdded+1
envs/chat_env/pyproject.tomlAdded+37
envs/chat_env/server/Dockerfile+49-25
envs/chat_env/server/app.py+16-3
envs/chat_env/server/chat_environment.py+40-29
envs/chat_env/server/requirements.txt-1
envs/chat_env/server/test_chat_env.py+17-16
models.py+33-14
openenv_chat_env.egg-info/PKG-INFOAdded+14
openenv_chat_env.egg-info/SOURCES.txtAdded+18
openenv_chat_env.egg-info/dependency_links.txtAdded+1
openenv_chat_env.egg-info/entry_points.txtAdded+2
openenv_chat_env.egg-info/requires.txtAdded+10
openenv_chat_env.egg-info/top_level.txtAdded+1
pyproject.toml+19-129
server/Dockerfile+49-25
server/app.py+16-3
server/chat_environment.py+40-29
server/requirements.txt-1
server/test_chat_env.py+17-16
src/core/env_server/http_server.py+537-282
src/core/env_server/mcp_environment.py+113-92
src/core/env_server/serialization.py+35-1
src/core/env_server/web_interface.py+62-9
src/core/mcp_client.py+126-19
src/core/openenv/__init__.py+12-4
src/core/openenv/cli/templates/openenv_env/pyproject.toml+1-1
src/core/openenv/core/env_server/http_server.py+537-282
src/core/openenv/core/env_server/mcp_environment.py+113-92
src/core/openenv/core/env_server/serialization.py+35-1
src/core/openenv/core/env_server/web_interface.py+62-9
src/core/openenv/core/mcp_client.py+126-19
src/openenv/__init__.py+12-4
src/openenv/cli/templates/openenv_env/pyproject.toml+1-1
src/openenv/core/env_server/http_server.py+537-282
src/openenv/core/env_server/mcp_environment.py+113-92
src/openenv/core/env_server/serialization.py+35-1
src/openenv/core/env_server/web_interface.py+62-9
src/openenv/core/mcp_client.py+126-19
src/openenv_core.egg-info/PKG-INFO+3-2