sxcn's picture
Prepare HERA-Bench executable dataset release
e6dec2c verified
Raw History Blame Contribute Delete
11.4 kB
"""Official tool adapter to the exact sealed transaction runtime."""
from __future__ import annotations
import copy
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import threading
from typing import Any, Callable
from fastmcp.tools import Tool
from fastmcp.tools.tool import ToolResult
from pydantic import Field
from abstention_factory.runtime.base import BaseEnvironment, ToolError
ROOT = Path(__file__).resolve().parent
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
support = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(support)
STATE_SCHEMA = json.loads('{"type": "object"}')
class _DomainTool(Tool):
fn: Callable[..., Any] = Field(exclude=True)
async def run(self, arguments: dict[str, Any]) -> ToolResult:
envelope = self.fn(**arguments)
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
structured_content=envelope,is_error=envelope['ok'] is False)
class Environment(BaseEnvironment):
env_name = 'eval60_gitlab'
short_name = 'GitLab'
always_skip_fields = set()
mutation_tools = set()
mutation_id_fields = set()
tool_kinds = json.loads('{"get_merge_request_approval_state": "lookup", "get_project": "lookup", "list_merge_request_discussions": "lookup", "list_merge_request_pipelines": "lookup", "list_project_merge_requests": "lookup"}')
_descriptors = json.loads('[{"description": "Retrieve one complete synthetic local project record by its full path. This offline simulation models documented GitLab project identifiers but is not an API-compatible clone.", "input_schema": {"additionalProperties": false, "properties": {"path": {"minLength": 1, "type": "string"}}, "required": ["path"], "type": "object"}, "name": "get_project", "output_schema": {"additionalProperties": false, "properties": {"project": {"additionalProperties": false, "properties": {"default_branch": {"type": "string"}, "id": {"type": "integer"}, "name": {"type": "string"}, "path": {"type": "string"}, "visibility": {"enum": ["private", "internal", "public"], "type": "string"}}, "required": ["id", "path", "name", "default_branch", "visibility"], "type": "object"}}, "required": ["project"], "type": "object"}, "read_only": true}, {"description": "List complete synthetic local merge-request records for a project, with optional exact state and target-branch filters. An empty filtered match is reported as NO_MATCH. Fields include both legacy merge_status and detailed_merge_status so callers can apply the documented preference.", "input_schema": {"additionalProperties": false, "properties": {"project_id": {"type": "integer"}, "state": {"enum": ["opened", "closed", "merged", "all"], "type": "string"}, "target_branch": {"type": ["string", "null"]}}, "required": ["project_id", "state", "target_branch"], "type": "object"}, "name": "list_project_merge_requests", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 0, "type": "integer"}, "merge_requests": {"items": {"additionalProperties": false, "properties": {"author_username": {"type": "string"}, "blocking_discussions_resolved": {"type": "boolean"}, "created_at": {"type": "string"}, "description": {"type": "string"}, "detailed_merge_status": {"type": "string"}, "draft": {"type": "boolean"}, "has_conflicts": {"type": "boolean"}, "id": {"type": "integer"}, "iid": {"type": "integer"}, "merge_status": {"type": "string"}, "project_id": {"type": "integer"}, "source_branch": {"type": "string"}, "state": {"enum": ["opened", "closed", "merged"], "type": "string"}, "target_branch": {"type": "string"}, "title": {"type": "string"}, "web_url": {"type": "string"}}, "required": ["id", "iid", "project_id", "title", "description", "state", "draft", "target_branch", "source_branch", "author_username", "created_at", "merge_status", "detailed_merge_status", "has_conflicts", "blocking_discussions_resolved", "web_url"], "type": "object"}, "type": "array"}}, "required": ["merge_requests", "count"], "type": "object"}, "read_only": true}, {"description": "List all synthetic local pipeline records linked to one merge request. The collection may legitimately be empty. This operation does not choose a latest pipeline.", "input_schema": {"additionalProperties": false, "properties": {"merge_request_iid": {"type": "integer"}, "project_id": {"type": "integer"}}, "required": ["project_id", "merge_request_iid"], "type": "object"}, "name": "list_merge_request_pipelines", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 0, "type": "integer"}, "pipelines": {"items": {"additionalProperties": false, "properties": {"created_at": {"type": "string"}, "id": {"type": "integer"}, "merge_request_id": {"type": "integer"}, "project_id": {"type": "integer"}, "sha": {"type": "string"}, "status": {"enum": ["created", "pending", "running", "success", "failed", "canceled", "skipped"], "type": "string"}, "web_url": {"type": "string"}}, "required": ["id", "project_id", "merge_request_id", "sha", "status", "created_at", "web_url"], "type": "object"}, "type": "array"}}, "required": ["pipelines", "count"], "type": "object"}, "read_only": true}, {"description": "List all synthetic local discussion summaries linked to one merge request. The collection may legitimately be empty; blocking and resolved are local summary fields.", "input_schema": {"additionalProperties": false, "properties": {"merge_request_iid": {"type": "integer"}, "project_id": {"type": "integer"}}, "required": ["project_id", "merge_request_iid"], "type": "object"}, "name": "list_merge_request_discussions", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 0, "type": "integer"}, "discussions": {"items": {"additionalProperties": false, "properties": {"author_username": {"type": "string"}, "blocking": {"type": "boolean"}, "created_at": {"type": "string"}, "id": {"type": "string"}, "merge_request_id": {"type": "integer"}, "resolved": {"type": "boolean"}}, "required": ["id", "merge_request_id", "blocking", "resolved", "created_at", "author_username"], "type": "object"}, "type": "array"}}, "required": ["discussions", "count"], "type": "object"}, "read_only": true}, {"description": "Retrieve the complete synthetic local approval-state record for one merge request. Approval requirements are local policy records, separate from deprecated merge-request approval-count fields.", "input_schema": {"additionalProperties": false, "properties": {"merge_request_iid": {"type": "integer"}, "project_id": {"type": "integer"}}, "required": ["project_id", "merge_request_iid"], "type": "object"}, "name": "get_merge_request_approval_state", "output_schema": {"additionalProperties": false, "properties": {"approval_state": {"additionalProperties": false, "properties": {"approvals_obtained": {"minimum": 0, "type": "integer"}, "approvals_required": {"minimum": 0, "type": "integer"}, "approved_by_usernames": {"items": {"type": "string"}, "type": "array"}, "merge_request_id": {"type": "integer"}, "rules_satisfied": {"type": "boolean"}, "updated_at": {"type": "string"}}, "required": ["merge_request_id", "approvals_required", "approvals_obtained", "approved_by_usernames", "rules_satisfied", "updated_at"], "type": "object"}}, "required": ["approval_state"], "type": "object"}, "read_only": true}]')
def _load_state(self, initial_state):
support.validator(STATE_SCHEMA).validate(initial_state)
return copy.deepcopy(initial_state)
@classmethod
def get_empty_state(cls):return {}
@classmethod
def get_example_state(cls):return {}
@classmethod
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
def _register_tools(self):
self._transaction_lock = threading.Lock()
self._transport_attempts = []
_, actual = support.load_domain(ROOT/'domain')
if support.canonical(actual) != support.canonical(self._descriptors):
raise ValueError('Public tool descriptors differ from the sealed domain')
for item in self._descriptors:
def bind(name):
def call(**arguments):return self._invoke_domain(name,arguments)
return call
output = None
if 'output_schema' in item:
output={'type':'object','oneOf':[
{'type':'object','required':['ok','result'],'additionalProperties':False,
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
{'type':'object','required':['ok','error'],'additionalProperties':False,
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
def _invoke_domain(self, name, arguments):
with self._transaction_lock:
before = copy.deepcopy(self.state)
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
raise ToolError('PUBLIC_REQUEST_LIMIT')
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
try:
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
input=support.canonical(request),capture_output=True,timeout=120,
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
result = support.strict(process.stdout)
if process.returncode or set(result) != {'state','observation','dispatched'}:
raise ValueError('Transaction worker failed')
observation = result['observation']
support.canonical(observation)
self.state = copy.deepcopy(result['state'])
except Exception as exc:
self.state = before
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
# Keep the semantic event stream identical to controller.public.
# Rejected pre-dispatch requests remain attempts but cannot count
# as observed domain evidence. MCP may itself reject extra keys
# before this adapter; that is a transport error, not a domain event.
if result['dispatched']:
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
success=observation['ok'],error=error)
return observation