"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" import hashlib import json import logging import os import sys import threading import urllib.request import uuid from pathlib import Path from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse from pydantic import BaseModel, ConfigDict sys.path.insert(0, str(Path(__file__).parent / "upstream")) import server as upstream # noqa: E402 log = logging.getLogger(__name__) def public(value): """Keep upstream agent-internal template hints out of the public response.""" if isinstance(value, dict): return {k: public(v) for k, v in value.items() if not k.startswith("_")} if isinstance(value, list): return [public(v) for v in value] return value class Action(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) action: str node_id: str | None = None arguments: dict | None = None answer: str | None = None class Episode: def __init__( self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None ): if max_actions < 1: raise ValueError("max_actions must be positive") self.lock = threading.Lock() self.max_actions = max_actions self.count = 0 self.won = False self.reason = None self.evidence_dir = Path(evidence_dir) if evidence_dir else None self.scenario_hash = hashlib.sha256( Path(scenario_path).read_bytes() ).hexdigest() self.initial = upstream.reset_case( case_file_path=str(scenario_path), session_id=uuid.uuid4().hex ) self.case_id = self.initial["case_id"] # Hide source file paths; no upstream reset/stats/routes are mounted. self.initial.pop("message", None) simulator = upstream.SIMULATORS[self.case_id] if worker_url is None: def no_worker(_inputs): self.reason = "infrastructure_error" raise RuntimeError("isolated Python worker is not configured") simulator.tool_map["code_py_exec"] = no_worker else: def execute_python(inputs): request = urllib.request.Request( worker_url + "/execute", data=json.dumps({"code": inputs.get("code", "")}).encode(), headers={"Content-Type": "application/json"}, ) try: with urllib.request.urlopen(request, timeout=12) as response: result = json.load(response) if not isinstance(result.get("stdout"), str): raise RuntimeError("Invalid Python worker response") return result except Exception: self.reason = "infrastructure_error" raise simulator.tool_map["code_py_exec"] = execute_python self.save() if self.evidence_dir is not None: (self.evidence_dir / "trace.jsonl").touch() def state(self): return { "scenario_sha256": self.scenario_hash, "action_count": self.count, "max_actions": self.max_actions, "won": self.won, "termination_reason": self.reason, } def save(self, action=None, result=None): if self.evidence_dir is None: return self.evidence_dir.mkdir(parents=True, exist_ok=True) target = self.evidence_dir / "outcome.json" temp = target.with_suffix(".tmp") temp.write_text(json.dumps(self.state())) temp.replace(target) if action is not None: with (self.evidence_dir / "trace.jsonl").open("a") as handle: handle.write( json.dumps( {"index": self.count, "action": action, "result": result} ) + "\n" ) def dispatch(self, payload): with self.lock: if self.reason is not None: return { "ok": False, "error": "Episode has ended", "episode": self.state(), } self.count += 1 try: action = Action.model_validate(payload) if action.action == "submit_answer" and action.answer is not None: result = upstream.submit_answer( self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) ) if result.get("is_win"): self.won = True self.reason = "success" elif action.action == "investigate" and action.node_id is not None: result = upstream.investigate( self.case_id, upstream.InvestigateRequest(node_id=action.node_id), ) elif ( action.action in ("tool_call", "use_item") and action.node_id is not None ): request_type, handler = ( (upstream.ToolCallRequest, upstream.tool_call) if action.action == "tool_call" else (upstream.UseItemRequest, upstream.use_item) ) result = handler( self.case_id, request_type( node_id=action.node_id, arguments=action.arguments or {} ), ) else: result = { "ok": False, "error": "Unknown action or missing action parameter", } except HTTPException as exc: result = {"ok": False, "error": exc.detail} except ValueError: result = {"ok": False, "error": "Malformed action"} except Exception: log.exception("Puzzle service failure") self.reason = "infrastructure_error" self.save() raise if self.reason is None and self.count >= self.max_actions: self.reason = "action_budget_exhausted" result = public(result) result["episode"] = self.state() self.save(payload, result) return result def create_app( scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None ): episode = Episode( scenario_path or os.environ["SCENARIO_PATH"], max_actions or int(os.environ.get("MAX_ACTIONS", "500")), evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), worker_url if worker_url is not None else os.environ.get("WORKER_URL"), ) app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) app.state.episode = episode @app.get("/health") def health(): return {"ok": True} @app.get("/observation") def observation(): return {**public(episode.initial), "episode": episode.state()} @app.get("/state") def state(): return episode.state() @app.post("/action") def action(payload: dict): try: return episode.dispatch(payload) except Exception: return JSONResponse( status_code=503, content={"ok": False, "error": "Puzzle infrastructure failure"}, ) return app