Download runtime/hera_environment/base.py from sxcn/HERA-Bench: direct link, hf CLI and curl.
- Browser
- Download file 5 kB
-
https://huggingface.co/datasets/sxcn/HERA-Bench/resolve/main/runtime/hera_environment/base.py
- Command line
-
hf download hf://datasets/sxcn/HERA-Bench/runtime/hera_environment/base.py
-
curl -L -o base.py https://huggingface.co/datasets/sxcn/HERA-Bench/resolve/main/runtime/hera_environment/base.py
5 kB
| """Stateful HERA environments with FastMCP tool registration.""" | |
| from __future__ import annotations | |
| from abc import ABC, abstractmethod | |
| import asyncio | |
| from copy import deepcopy | |
| from queue import Queue | |
| from threading import Thread | |
| from fastmcp import FastMCP | |
| from fastmcp.exceptions import ToolError as MCPCallError | |
| from pydantic import ValidationError | |
| class ToolError(Exception): | |
| """An environment tool could not complete its request.""" | |
| def complete(coroutine): | |
| """Provide synchronous environment access from either calling context.""" | |
| try: | |
| asyncio.get_running_loop() | |
| except RuntimeError: | |
| loop = None | |
| else: | |
| loop = True | |
| if loop is None: | |
| return asyncio.run(coroutine) | |
| completion = Queue(maxsize=1) | |
| def worker(): | |
| try: | |
| completion.put((True, asyncio.run(coroutine))) | |
| except BaseException as error: | |
| completion.put((False, error)) | |
| thread = Thread(target=worker) | |
| thread.start() | |
| thread.join() | |
| succeeded, value = completion.get() | |
| if not succeeded: | |
| raise value | |
| return value | |
| class BaseEnvironment(ABC): | |
| """Shared tool interface; domain classes own state transitions and schemas.""" | |
| env_name: str | |
| short_name = '' | |
| always_skip_fields = {'read'} | |
| mutation_tools = set() | |
| mutation_id_fields = set() | |
| tool_kinds = {} | |
| def __init__(self, initial_state): | |
| self.execution_log = [] | |
| self._broken_tools = {} | |
| self.state = self._load_state(initial_state) | |
| self._initial_state_snapshot = deepcopy(self.state) | |
| self.mcp = FastMCP(self.env_name) | |
| self._register_tools() | |
| def _load_state(self, initial_state): | |
| """Construct domain state from a JSON-compatible input.""" | |
| def _register_tools(self): | |
| """Expose domain callables on this instance's MCP server.""" | |
| def get_empty_state(cls): | |
| """Return a valid empty state.""" | |
| def get_state_schema(cls): | |
| """Describe serialized domain state.""" | |
| def get_example_state(cls): | |
| """Return a representative valid state.""" | |
| def _log_tool_call(self, tool_name, params, result, success=True, error=None): | |
| entry = dict(tool=tool_name, params=params, result=result, success=success, error=error) | |
| self.execution_log.append(entry) | |
| def get_execution_log(self): | |
| return self.execution_log | |
| def get_tool_callable(self, tool_name): | |
| registered = complete(self.mcp.get_tool(tool_name)) | |
| return getattr(registered, 'fn', registered) | |
| def call_tool(self, tool_name, **params): | |
| if tool_name in self._broken_tools: | |
| reason = self._broken_tools[tool_name] | |
| self._log_tool_call(tool_name, params, None, success=False, error=reason) | |
| raise ToolError(reason) | |
| try: | |
| reply = complete(self.mcp.call_tool(tool_name, params)) | |
| except (MCPCallError, ValidationError) as error: | |
| raise ToolError(str(error)) from error | |
| if not hasattr(reply, 'structured_content'): | |
| return reply | |
| payload = reply.structured_content | |
| if isinstance(payload, dict) and list(payload) == ['result']: | |
| return payload['result'] | |
| return payload | |
| async def abreak_tool(self, tool_name, error_message='Service unavailable'): | |
| self._broken_tools[tool_name] = error_message | |
| registered = await self.mcp.get_tool(tool_name) | |
| if registered is not None: | |
| self._replace_tool_fn(tool_name, registered, error_message) | |
| def break_tool(self, tool_name, error_message='Service unavailable'): | |
| complete(self.abreak_tool(tool_name, error_message)) | |
| def _replace_tool_fn(self, tool_name, registered, error_message): | |
| def unavailable(**arguments): | |
| self._log_tool_call(tool_name, arguments, None, False, error_message) | |
| raise ToolError(error_message) | |
| registered.fn = unavailable | |
| def hide_tool(self, tool_name): | |
| provider = getattr(self.mcp, 'local_provider', self.mcp) | |
| provider.remove_tool(tool_name) | |
| def get_tool_schemas(cls): | |
| instance = cls(cls.get_empty_state()) | |
| catalog = complete(instance.mcp.list_tools()) | |
| return list(map(cls._normalize_tool_schema, catalog)) | |
| def _normalize_tool_schema(cls, tool): | |
| descriptor = tool.model_dump() if hasattr(tool, 'model_dump') else tool | |
| name = descriptor.get('name') | |
| inputs = descriptor.get('parameters') or descriptor.get('input_schema') or {} | |
| outputs = descriptor.get('output_schema') or descriptor.get('outputSchema') | |
| return dict(name=name, description=descriptor.get('description') or '', | |
| input_schema=inputs, output_schema=outputs, kind=cls.tool_kinds.get(name, '')) | |