File size: 8,507 Bytes
80a5932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a84728
 
 
 
 
 
 
 
 
80a5932
3a84728
 
 
 
80a5932
 
 
 
 
 
 
 
 
 
 
3a84728
 
 
 
 
 
 
 
 
 
 
 
80a5932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from typing import Optional, Dict, Any, List

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import uvicorn

from .environment import TrainingEnv
from .scenarios import list_scenarios, detail_scenario, SCENARIO_CATALOG

app = FastAPI(
    title="Linux SRE Environment API",
    description=(
        "OpenEnv-compliant API for the Linux SRE training environment. "
        "Supports legacy difficulty-based tasks and composable scenarios "
        "with cascading fault injection."
    ),
    version="2.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

backends: Dict[str, TrainingEnv] = {}
counter = 0


# ======================================================================
#  REQUEST / RESPONSE MODELS
# ======================================================================

class ResetPayload(BaseModel):
    scenario: str = Field(
        default="log_analysis", description="Scenario key to load")
    seed: Optional[int] = Field(
        default=None, description="Random seed for reproducibility")


class StepPayload(BaseModel):
    action: str = Field(description="Shell command to execute")


class ResetOut(BaseModel):
    env_id: str
    observation: Dict[str, Any]
    info: Dict[str, Any]


class StepOut(BaseModel):
    observation: Dict[str, Any]
    reward: float
    done: bool
    info: Dict[str, Any]


# ======================================================================
#  HEALTH + TASKS
# ======================================================================

@app.get("/")
async def root():
    return {"status": "ok", "service": "linux-sre-env", "version": "2.0.0", "docs": "/docs"}


@app.get("/health")
async def health_check():
    return {"status": "healthy", "service": "linux-sre-env", "version": "2.0.0"}


@app.get("/metadata")
async def metadata():
    return {
        "name": "linux-sre-env",
        "description": (
            "Linux System Reliability Engineer Training Environment. "
            "A simulated Linux server where AI agents practice diagnosing and fixing "
            "real infrastructure problems via shell commands."
        ),
        "version": "2.0.0",
        "author": "SRE Team",
        "domain": "system_administration",
        "tags": ["sre", "linux", "troubleshooting", "agentic"],
    }


@app.get("/schema")
async def schema():
    return {
        "action": {
            "type": "string",
            "description": "Shell command to execute in the virtual environment",
        },
        "observation": {
            "type": "object",
            "properties": {
                "current_directory": {"type": "string"},
                "processes": {"type": "string"},
                "filesystem": {"type": "string"},
                "task_name": {"type": "string"},
                "task_description": {"type": "string"},
            },
        },
        "state": {
            "type": "object",
            "properties": {
                "episode_step": {"type": "integer"},
                "max_steps": {"type": "integer"},
                "task_score": {"type": "number"},
                "task_difficulty": {"type": "string"},
                "scenario_key": {"type": "string"},
            },
        },
    }


@app.get("/api/v1/tasks")
async def list_tasks():
    task_keys = TrainingEnv.avail_tasks()
    task_details = {
        key: TrainingEnv.task_details(key)
        for key in task_keys
    }
    task_objects = [
        {"key": key, **task_details[key]}
        for key in task_keys
    ]
    return {
        "count": len(task_keys),
        "tasks": task_objects,
        "task_keys": task_keys,
        "details": task_details,
    }


@app.get("/api/v1/tasks/{key}")
async def get_task(key: str):
    info = TrainingEnv.task_details(key)
    if not info:
        raise HTTPException(status_code=404, detail=f"Task '{key}' not found")
    return info


@app.get("/tasks")
async def list_tasks_alias():
    """Top-level alias for validators that call /tasks."""
    return await list_tasks()


@app.get("/tasks/{key}")
async def get_task_alias(key: str):
    """Top-level alias for validators that call /tasks/{key}."""
    return await get_task(key)


# ======================================================================
#  SCENARIOS
# ======================================================================

@app.get("/api/v1/scenarios")
async def get_scenarios():
    """List all available scenarios with metadata."""
    return {"scenarios": list_scenarios()}


@app.get("/api/v1/scenarios/{key}")
async def get_scenario(key: str):
    """Get detailed info for a single scenario."""
    if key not in SCENARIO_CATALOG:
        raise HTTPException(
            status_code=404, detail=f"Scenario '{key}' not found")
    return detail_scenario(key)


# ======================================================================
# ======================================================================
#  ENVIRONMENT LIFECYCLE
# ======================================================================

@app.post("/api/v1/env/reset")
async def reset(req: Optional[ResetPayload] = None):
    global counter
    if req is None:
        req = ResetPayload()
    try:
        env = TrainingEnv(scenario=req.scenario)
        eid = f"env_{counter}"
        counter += 1
        backends[eid] = env
        res = env.reset()
        return ResetOut(env_id=eid, observation=res["observation"], info=res["info"])
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.post("/api/v1/env/{env_id}/step")
async def step(env_id: str, req: StepPayload):
    if env_id not in backends:
        raise HTTPException(
            status_code=404, detail=f"Environment '{env_id}' not found")
    env = backends[env_id]
    res = env.step(req.action)
    return StepOut(
        observation=res["observation"],
        reward=res["reward"],
        done=res["done"],
        info=res["info"],
    )


@app.get("/api/v1/env/{env_id}/state")
async def get_state(env_id: str):
    if env_id not in backends:
        raise HTTPException(
            status_code=404, detail=f"Environment '{env_id}' not found")
    return backends[env_id].dump()


@app.delete("/api/v1/env/{env_id}")
async def delete_env(env_id: str):
    if env_id not in backends:
        raise HTTPException(
            status_code=404, detail=f"Environment '{env_id}' not found")
    del backends[env_id]
    return {"status": "deleted", "env_id": env_id}


# ======================================================================
#  TOP-LEVEL OpenEnv ALIASES  (validators may hit /reset, /step, /state)
# ======================================================================

@app.post("/reset")
async def reset_alias(req: Optional[ResetPayload] = None):
    return await reset(req)


@app.post("/step")
async def step_alias(req: StepPayload, env_id: Optional[str] = None):
    """Top-level /step — uses the most recently created env if env_id is omitted."""
    if env_id is None and backends:
        env_id = list(backends.keys())[-1]
    if not env_id or env_id not in backends:
        raise HTTPException(
            status_code=404, detail="No active environment. Call /reset first.")
    return await step(env_id, req)


@app.post("/step/{env_id}")
async def step_alias_with_id(env_id: str, req: StepPayload):
    return await step(env_id, req)


@app.get("/state")
async def state_alias(env_id: Optional[str] = None):
    """Top-level /state — uses the most recently created env if env_id is omitted."""
    if env_id is None and backends:
        env_id = list(backends.keys())[-1]
    if not env_id or env_id not in backends:
        raise HTTPException(
            status_code=404, detail="No active environment. Call /reset first.")
    return await get_state(env_id)


@app.get("/state/{env_id}")
async def state_alias_with_id(env_id: str):
    return await get_state(env_id)


@app.get("/api/v1/env")
async def list_envs():
    return {
        "count": len(backends),
        "environments": {
            eid: {
                "task": env.task.nm,
                "difficulty": env.difficulty,
                "score": env.score,
                "step": env.step_count,
                "done": env.finished,
            }
            for eid, env in backends.items()
        },
    }