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
 
 
 
 
 
 
9fd90c1
 
 
 
4ccc966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
from __future__ import annotations

from abc import ABC, abstractmethod
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Generic, Optional, TypeVar

import httpx
from fastapi import Body, FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, ConfigDict, Field


class Action(BaseModel):
    model_config = ConfigDict(
        extra="forbid",
        validate_assignment=True,
        arbitrary_types_allowed=True,
    )

    metadata: Dict[str, Any] = Field(default_factory=dict)


class Observation(BaseModel):
    model_config = ConfigDict(
        extra="forbid",
        validate_assignment=True,
        arbitrary_types_allowed=True,
    )

    done: bool = Field(default=False)
    reward: float | None = Field(default=None)
    metadata: Dict[str, Any] = Field(default_factory=dict)


class State(BaseModel):
    model_config = ConfigDict(
        extra="allow",
        validate_assignment=True,
        arbitrary_types_allowed=True,
    )

    episode_id: Optional[str] = Field(default=None)
    step_count: int = Field(default=0, ge=0)


ActT = TypeVar("ActT", bound=BaseModel)
ObsT = TypeVar("ObsT", bound=Observation)
StateT = TypeVar("StateT", bound=State)


@dataclass
class StepResult(Generic[ObsT]):
    observation: ObsT
    reward: float | None = None
    done: bool = False
    info: Dict[str, Any] = field(default_factory=dict)


class Environment(ABC, Generic[ActT, ObsT, StateT]):
    def __init__(self) -> None:
        super().__init__()

    @abstractmethod
    def reset(
        self,
        seed: Optional[int] = None,
        episode_id: Optional[str] = None,
        **kwargs: Any,
    ) -> ObsT:
        raise NotImplementedError

    @abstractmethod
    def step(
        self,
        action: ActT,
        timeout_s: Optional[float] = None,
        **kwargs: Any,
    ) -> ObsT:
        raise NotImplementedError

    @property
    @abstractmethod
    def state(self) -> StateT:
        raise NotImplementedError

    def close(self) -> None:
        return None


class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
    def __init__(
        self,
        base_url: str,
        *,
        timeout_s: float = 30.0,
        async_client: httpx.AsyncClient | None = None,
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self._owns_client = async_client is None
        self._client = async_client or httpx.AsyncClient(
            base_url=self.base_url,
            timeout=timeout_s,
        )

    async def __aenter__(self) -> "EnvClient[ActT, ObsT, StateT]":
        return self

    async def __aexit__(self, exc_type, exc, tb) -> None:
        await self.aclose()

    async def aclose(self) -> None:
        if self._owns_client:
            await self._client.aclose()

    async def close(self) -> None:
        await self.aclose()

    async def reset(
        self,
        seed: int | None = None,
        episode_id: str | None = None,
        **kwargs: Any,
    ) -> StepResult[ObsT]:
        payload: Dict[str, Any] = {}
        if seed is not None:
            payload["seed"] = seed
        if episode_id is not None:
            payload["episode_id"] = episode_id
        payload.update(kwargs)
        response = await self._client.post("/reset", json=payload)
        response.raise_for_status()
        return self._parse_result(response.json())

    async def step(self, action: ActT, **kwargs: Any) -> StepResult[ObsT]:
        payload: Dict[str, Any] = {"action": self._step_payload(action)}
        payload.update(kwargs)
        response = await self._client.post("/step", json=payload)
        response.raise_for_status()
        return self._parse_result(response.json())

    async def state(self) -> StateT:
        response = await self._client.get("/state")
        response.raise_for_status()
        return self._parse_state(response.json())

    @abstractmethod
    def _step_payload(self, action: ActT) -> Dict[str, Any]:
        raise NotImplementedError

    @abstractmethod
    def _parse_result(self, data: Dict[str, Any]) -> StepResult[ObsT]:
        raise NotImplementedError

    @abstractmethod
    def _parse_state(self, data: Dict[str, Any]) -> StateT:
        raise NotImplementedError


def _serialize_observation(observation: Observation) -> Dict[str, Any]:
    return {
        "observation": observation.model_dump(
            exclude={"reward", "done", "metadata"},
            mode="json",
        ),
        "reward": observation.reward,
        "done": observation.done,
    }


def _root_page_html(env_name: str) -> str:
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{env_name}</title>
  <style>
    :root {{
      color-scheme: light;
      --bg: #f6f4ef;
      --panel: #fffdf8;
      --ink: #18222d;
      --muted: #556270;
      --accent: #0f766e;
      --accent-strong: #115e59;
      --line: #d7d1c7;
      --warn: #9a3412;
      --code: #f2efe8;
    }}
    * {{ box-sizing: border-box; }}
    body {{
      margin: 0;
      font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      background:
        radial-gradient(circle at top right, rgba(15, 118, 110, 0.16), transparent 26%),
        linear-gradient(180deg, #faf8f2 0%, var(--bg) 100%);
      color: var(--ink);
    }}
    main {{
      max-width: 1120px;
      margin: 0 auto;
      padding: 32px 20px 48px;
    }}
    .hero {{
      display: grid;
      gap: 14px;
      margin-bottom: 24px;
    }}
    h1 {{
      margin: 0;
      font-size: clamp(2rem, 4vw, 3.4rem);
      line-height: 1.05;
    }}
    p {{
      margin: 0;
      color: var(--muted);
      max-width: 74ch;
    }}
    .grid {{
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 16px;
    }}
    .panel {{
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: 18px;
      padding: 18px;
      box-shadow: 0 10px 30px rgba(24, 34, 45, 0.06);
    }}
    .panel h2 {{
      margin: 0 0 12px;
      font-size: 1.05rem;
    }}
    .row {{
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 12px;
    }}
    label {{
      display: grid;
      gap: 6px;
      font-size: 0.92rem;
      color: var(--muted);
      width: 100%;
    }}
    select, button, textarea {{
      font: inherit;
    }}
    select, textarea {{
      width: 100%;
      border: 1px solid var(--line);
      border-radius: 12px;
      background: white;
      padding: 12px 14px;
      color: var(--ink);
    }}
    textarea {{
      min-height: 220px;
      resize: vertical;
      font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
      background: var(--code);
    }}
    button {{
      border: 0;
      border-radius: 999px;
      padding: 11px 16px;
      background: var(--accent);
      color: white;
      cursor: pointer;
      font-weight: 600;
    }}
    button:hover {{
      background: var(--accent-strong);
    }}
    .secondary {{
      background: #dbe9e7;
      color: var(--accent-strong);
    }}
    .stats {{
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
      gap: 10px;
    }}
    .stat {{
      border: 1px solid var(--line);
      border-radius: 14px;
      padding: 12px;
      background: rgba(255, 255, 255, 0.75);
    }}
    .stat strong {{
      display: block;
      font-size: 1.15rem;
      margin-top: 4px;
    }}
    .muted {{
      color: var(--muted);
    }}
    .warning {{
      color: var(--warn);
    }}
    code {{
      background: var(--code);
      padding: 2px 6px;
      border-radius: 8px;
    }}
  </style>
</head>
<body>
  <main>
    <section class="hero">
      <h1>Enterprise Finance OpenEnv</h1>
      <p>
        Interactive console for testing <code>/reset</code>, <code>/step</code>, <code>/state</code>,
        and score outputs directly from the deployed environment.
      </p>
      <p class="muted">
        Use the API endpoints for agent evaluation. This page is a manual playground for humans.
      </p>
    </section>

    <section class="grid">
      <div class="panel">
        <h2>Episode Controls</h2>
        <div class="row">
          <label>
            Difficulty
            <select id="difficulty">
              <option value="easy">easy</option>
              <option value="medium">medium</option>
              <option value="hard">hard</option>
            </select>
          </label>
        </div>
        <div class="row">
          <button id="reset-btn" type="button">Reset Episode</button>
          <button id="state-btn" class="secondary" type="button">Refresh State</button>
        </div>
        <div class="stats">
          <div class="stat"><span class="muted">Difficulty</span><strong id="stat-difficulty">-</strong></div>
          <div class="stat"><span class="muted">Step Count</span><strong id="stat-step-count">-</strong></div>
          <div class="stat"><span class="muted">Open Balance</span><strong id="stat-open-balance">-</strong></div>
          <div class="stat"><span class="muted">Score</span><strong id="stat-score">-</strong></div>
          <div class="stat"><span class="muted">Total Reward</span><strong id="stat-total-reward">-</strong></div>
          <div class="stat"><span class="muted">Unmatched</span><strong id="stat-unmatched">-</strong></div>
        </div>
      </div>

      <div class="panel">
        <h2>Submit Action</h2>
        <p class="muted">
          Paste a JSON action body matching the environment schema.
        </p>
        <label>
          Action JSON
          <textarea id="action-json">{{
  "type": "query_subledger",
  "entity": "PARENT_US",
  "account_code": "IC_AR",
  "date_range": ["2026-01-01", "2026-01-31"]
}}</textarea>
        </label>
        <div class="row">
          <button id="step-btn" type="button">POST /step</button>
        </div>
        <p id="step-error" class="warning"></p>
      </div>
    </section>

    <section class="grid" style="margin-top: 16px;">
      <div class="panel">
        <h2>Latest API Response</h2>
        <label>
          Response JSON
          <textarea id="response-json" readonly></textarea>
        </label>
      </div>
      <div class="panel">
        <h2>Current State</h2>
        <label>
          State JSON
          <textarea id="state-json" readonly></textarea>
        </label>
      </div>
    </section>
  </main>

  <script>
    const responseBox = document.getElementById("response-json");
    const stateBox = document.getElementById("state-json");
    const errorBox = document.getElementById("step-error");

    function setJson(target, payload) {{
      target.value = JSON.stringify(payload, null, 2);
    }}

    function setStat(id, value) {{
      document.getElementById(id).textContent = value ?? "-";
    }}

    function updateScoreboard(state) {{
      setStat("stat-difficulty", state.difficulty);
      setStat("stat-step-count", state.step_count);
      setStat("stat-open-balance", state.open_abs_balance);
      setStat("stat-score", state.final_score ?? "in progress");
      setStat("stat-total-reward", state.total_reward);
      setStat("stat-unmatched", state.unmatched_valid_count);
      setJson(stateBox, state);
    }}

    async function fetchJson(path, options = undefined) {{
      const response = await fetch(path, options);
      const payload = await response.json();
      if (!response.ok) {{
        throw new Error(JSON.stringify(payload));
      }}
      return payload;
    }}

    async function refreshState() {{
      const state = await fetchJson("/state");
      updateScoreboard(state);
      return state;
    }}

    async function resetEpisode() {{
      errorBox.textContent = "";
      const difficulty = document.getElementById("difficulty").value;
      const payload = await fetchJson("/reset", {{
        method: "POST",
        headers: {{ "Content-Type": "application/json" }},
        body: JSON.stringify({{ difficulty }})
      }});
      setJson(responseBox, payload);
      await refreshState();
    }}

    async function postAction() {{
      errorBox.textContent = "";
      let action;
      try {{
        action = JSON.parse(document.getElementById("action-json").value);
      }} catch (error) {{
        errorBox.textContent = "Action JSON is invalid: " + error.message;
        return;
      }}

      try {{
        const payload = await fetchJson("/step", {{
          method: "POST",
          headers: {{ "Content-Type": "application/json" }},
          body: JSON.stringify({{ action }})
        }});
        setJson(responseBox, payload);
        await refreshState();
      }} catch (error) {{
        errorBox.textContent = String(error.message || error);
      }}
    }}

    document.getElementById("reset-btn").addEventListener("click", resetEpisode);
    document.getElementById("state-btn").addEventListener("click", refreshState);
    document.getElementById("step-btn").addEventListener("click", postAction);
    refreshState().catch((error) => {{
      errorBox.textContent = String(error.message || error);
    }});
  </script>
</body>
</html>"""


def create_app(
    env_factory: Callable[[], Environment[Any, Observation, State]]
    | type[Environment[Any, Observation, State]],
    action_cls: type[BaseModel],
    observation_cls: type[Observation],
    env_name: str = "environment",
) -> FastAPI:
    env = env_factory() if callable(env_factory) else env_factory

    @asynccontextmanager
    async def lifespan(_: FastAPI):
        yield
        env.close()

    app = FastAPI(title=env_name, lifespan=lifespan)

    class ResetRequest(BaseModel):
        model_config = ConfigDict(extra="allow")

        seed: int | None = None
        episode_id: str | None = None

    class StepRequest(BaseModel):
        model_config = ConfigDict(extra="allow")

        action: Dict[str, Any]
        timeout_s: float | None = None

    @app.get("/", response_class=HTMLResponse)
    async def home() -> HTMLResponse:
        return HTMLResponse(_root_page_html(env_name))

    @app.get("/health")
    async def health() -> Dict[str, str]:
        return {"status": "healthy"}

    @app.get("/schema")
    async def schema() -> Dict[str, Any]:
        state_cls = env.state.__class__
        return {
            "action": action_cls.model_json_schema(),
            "observation": observation_cls.model_json_schema(),
            "state": state_cls.model_json_schema(),
        }

    @app.get("/state")
    async def state() -> Dict[str, Any]:
        return env.state.model_dump(mode="json")

    @app.post("/reset")
    async def reset(request: Dict[str, Any] = Body(default_factory=dict)) -> Dict[str, Any]:
        validated = ResetRequest.model_validate(request)
        payload = validated.model_dump(exclude_none=True)
        seed = payload.pop("seed", None)
        episode_id = payload.pop("episode_id", None)
        observation = env.reset(seed=seed, episode_id=episode_id, **payload)
        return _serialize_observation(observation)

    @app.post("/step")
    async def step(request: Dict[str, Any] = Body(...)) -> Dict[str, Any]:
        validated = StepRequest.model_validate(request)
        try:
            action = action_cls.model_validate(validated.action)
        except Exception as exc:  # pragma: no cover - FastAPI will surface this in real path.
            raise HTTPException(status_code=422, detail=str(exc)) from exc

        payload = validated.model_dump(exclude_none=True)
        timeout_s = payload.pop("timeout_s", None)
        payload.pop("action", None)
        observation = env.step(action, timeout_s=timeout_s, **payload)
        return _serialize_observation(observation)

    return app