File size: 7,652 Bytes
49aa045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""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