File size: 5,565 Bytes
a73eb17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""

FastAPI application for the Emailtriage Environment.



Endpoints:

    - POST /reset: Reset the environment (accepts optional task_id)

    - POST /step: Execute an action

    - GET /state: Get current environment state

    - GET /schema: Get action/observation schemas

    - GET /health: Health check

    - WS /ws: WebSocket endpoint for persistent sessions

"""

import argparse
from pathlib import Path
from typing import Any

import uvicorn
from fastapi import APIRouter

try:
    from openenv.core.env_server.http_server import create_app
except Exception as e:  # pragma: no cover
    raise ImportError(
        "openenv is required for the web interface. "
        "Install dependencies with '\n    uv sync\n'"
    ) from e

try:
    from ..models import EmailtriageAction, EmailtriageObservation
    from .EmailTriage_environment import EmailtriageEnvironment
except ImportError:
    from models import EmailtriageAction, EmailtriageObservation
    from server.EmailTriage_environment import EmailtriageEnvironment


# Create the app with web interface and README integration
app = create_app(
    EmailtriageEnvironment,
    EmailtriageAction,
    EmailtriageObservation,
    env_name="EmailTriage",
    max_concurrent_envs=1,
)

# Keep docs metadata explicit to avoid generic duplicate naming in Swagger UI.
app.title = "EmailTriage Environment API"
app.description = (
    "HTTP API for the dynamic EmailTriage OpenEnv environment "
    "with 3 difficulty-graded tasks (easy, medium, hard)."
)


def _load_readme_content() -> str:
    """Load environment README markdown for metadata endpoint."""
    readme_path = Path(__file__).resolve().parents[1] / "README.md"
    try:
        return readme_path.read_text(encoding="utf-8")
    except Exception:
        return "EmailTriage environment documentation is unavailable."


def _replace_route(

    path: str,

    method: str,

    endpoint,

    *,

    summary: str,

) -> None:
    """Replace an existing route path+method with a custom handler."""
    method_upper = method.upper()
    app.router.routes = [
        route
        for route in app.router.routes
        if not (
            getattr(route, "path", None) == path
            and method_upper in getattr(route, "methods", set())
        )
    ]

    router = APIRouter()
    router.add_api_route(
        path,
        endpoint,
        methods=[method_upper],
        summary=summary,
    )
    app.include_router(router)


def _metadata_payload() -> dict[str, Any]:
    """Build non-null metadata for /metadata."""
    return {
        "name": "EmailTriage",
        "description": (
            "Dynamic multi-turn email triage environment for OpenEnv "
            "post-training and evaluation with 3 difficulty-graded tasks"
        ),
        "readme_content": _load_readme_content(),
        "version": "1.0.0",
        "author": "Galcogens",
        "documentation_url": "/docs",
        "tasks": [
            {
                "id": "easy",
                "name": "Quick Sort",
                "description": "Archive 3 spam/newsletter emails",
                "difficulty": "easy",
            },
            {
                "id": "medium",
                "name": "Priority Triage",
                "description": (
                    "Triage 5 mixed-priority emails with "
                    "calendar scheduling"
                ),
                "difficulty": "medium",
            },
            {
                "id": "hard",
                "name": "Dynamic Crisis",
                "description": (
                    "Handle 7-10 emails with dynamic events "
                    "and escalations"
                ),
                "difficulty": "hard",
            },
        ],
    }


def _root_payload() -> dict[str, Any]:
    """Return a simple JSON index for localhost:8000."""
    return {
        "service": "EmailTriage OpenEnv API",
        "status": "ok",
        "docs": "/docs",
        "metadata": "/metadata",
        "endpoints": [
            "/reset",
            "/step",
            "/state",
            "/schema",
            "/metadata",
            "/health",
            "/web",
            "/ws",
        ],
    }


def _health_payload() -> dict[str, Any]:
    """Health check endpoint for Docker and load balancers."""
    return {"status": "ok"}


_replace_route(
    "/metadata",
    "GET",
    _metadata_payload,
    summary="Get environment metadata",
)
_replace_route(
    "/",
    "GET",
    _root_payload,
    summary="Get API index",
)
_replace_route(
    "/health",
    "GET",
    _health_payload,
    summary="Health check",
)


def run_server(host: str = "0.0.0.0", port: int = 8000) -> None:
    """Entry point for direct execution via uv run or python -m."""
    uvicorn.run(app, host=host, port=port)


def main() -> None:
    """CLI-compatible entrypoint expected by OpenEnv validator."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", type=str, default="0.0.0.0")
    parser.add_argument("--port", type=int, default=8000)
    args = parser.parse_args()
    run_server(host=args.host, port=args.port)


if __name__ == "__main__":
    main()