Spaces:
Sleeping
Sleeping
Download server/app.py from yaswanth169/APISHIFT: direct link, hf CLI and curl.
- Browser
- Download file 57.6 kB
-
https://huggingface.co/spaces/yaswanth169/APISHIFT/resolve/main/server/app.py
- Command line
-
hf download hf://spaces/yaswanth169/APISHIFT/server/app.py
-
curl -L -o app.py https://huggingface.co/spaces/yaswanth169/APISHIFT/resolve/main/server/app.py
57.6 kB
"""APIShift FastAPI app β the OpenEnv server entry point.
Built on top of openenv-core's create_fastapi_app, which provides the
official OpenEnv contract:
HTTP endpoints (stateless β one env instance per request):
POST /reset POST /step GET /state GET /schema
GET /metadata GET /health GET /docs
WebSocket endpoint (stateful β one env instance per connection):
/ws with messages {"type": "reset"|"step"|"state"|"close", "data": {...}}
Because APIShift's Manager runs multi-step episodes (Diff β Patch β Test
β Rollback β Submit), the canonical transport is the WebSocket /ws
endpoint, where one connection == one episode. The HTTP /reset and /step
remain available for stateless one-shot calls.
In addition to the openenv-core endpoints we mount three GET routes that
expose the inspectable artifacts (program, lessons, curriculum) so judges
and reviewers can fetch them directly without cloning the repo.
"""
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse
from models import APIShiftAction, APIShiftObservation
from server.environment import APIShiftEnvironment, list_tasks
# ---------------------------------------------------------------------
# Build the OpenEnv-standard FastAPI app
# ---------------------------------------------------------------------
# create_fastapi_app expects a *factory* (callable returning a fresh env
# per call). Our env constructor takes no required arguments, so passing
# the class itself works. Each new HTTP request gets its own instance;
# each WebSocket connection gets its own dedicated session env.
try:
from openenv.core.env_server import create_fastapi_app
app: FastAPI = create_fastapi_app(
APIShiftEnvironment,
APIShiftAction,
APIShiftObservation,
)
_OPENENV_AVAILABLE = True
except ImportError:
# Fallback for local dev without openenv-core installed.
_OPENENV_AVAILABLE = False
app = FastAPI(title="APIShift", version="0.1.0")
_env = APIShiftEnvironment()
@app.post("/reset")
async def reset_endpoint(req):
body = await req.json()
obs = _env.reset(**(body or {}))
return JSONResponse(content={
"observation": obs.model_dump(),
"reward": obs.reward,
"done": obs.done,
})
@app.post("/step")
async def step_endpoint(req):
body = await req.json()
action_body = body.get("action", body) if isinstance(body, dict) else body
action = APIShiftAction.model_validate(action_body)
obs = _env.step(action)
return JSONResponse(content={
"observation": obs.model_dump(),
"reward": obs.reward,
"done": obs.done,
})
@app.get("/state")
async def state_endpoint():
return JSONResponse(content=_env.state.model_dump())
@app.get("/health")
async def health():
return {"status": "healthy"}
# ---------------------------------------------------------------------
# Cross-origin support so the env is browseable from anywhere
# ---------------------------------------------------------------------
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------
# APIShift-specific endpoints (additive, do not override OpenEnv routes)
# ---------------------------------------------------------------------
@app.get("/tasks", tags=["APIShift"])
async def tasks():
"""List available scenarios (real + synthetic). Phase 2 deep validator
expects this endpoint."""
return {"tasks": list_tasks()}
@app.get("/program", tags=["APIShift"])
async def program():
"""Read the Manager's operating manual (apishift_program.md)."""
path = "apishift_program.md"
if not os.path.exists(path):
return JSONResponse(status_code=404, content={"error": "program file not found"})
with open(path, "r", encoding="utf-8") as f:
return {"path": path, "content": f.read()}
@app.get("/lessons", tags=["APIShift"])
async def lessons():
"""Read the markdown memory artifact (lessons.md)."""
path = "lessons.md"
if not os.path.exists(path):
return {"path": path, "content": ""}
with open(path, "r", encoding="utf-8") as f:
return {"path": path, "content": f.read()}
@app.get("/curriculum", tags=["APIShift"])
async def curriculum():
"""Read the adaptive curriculum config (curriculum.md)."""
path = "curriculum.md"
if not os.path.exists(path):
return {"path": path, "content": ""}
with open(path, "r", encoding="utf-8") as f:
return {"path": path, "content": f.read()}
def _annotate_step(command: str, obs) -> str:
"""Build a short human readable annotation for one step from the
current observation. Used by the episode transcript panel so each
step shows what the specialist actually did."""
if command == "dispatch_diff":
n = len(obs.detected_changes) if obs.detected_changes else 0
if n == 0:
return "DiffSpecialist found no breaking changes"
ctype = obs.detected_changes[0].change_type if obs.detected_changes else ""
return f"DiffSpecialist found {n} breaking change{'s' if n != 1 else ''}{f', first: {ctype}' if ctype else ''}"
if command == "classify_impact":
return "Manager classified blocking vs non blocking changes"
if command == "dispatch_patch":
n = len(obs.generated_patches) if obs.generated_patches else 0
last = obs.generated_patches[-1] if obs.generated_patches else None
if last is not None:
cid = getattr(last, "targets_change_id", "")
return f"PatchSpecialist generated patch {n} for {cid}"
return f"PatchSpecialist generated {n} patches"
if command == "dispatch_test":
tr = obs.last_test_result
if tr is None:
return "TestSpecialist returned no result"
return f"TestSpecialist {tr.passed} of {tr.total} tests pass"
if command == "dispatch_rollback":
rb = obs.rollback_plan
if rb is None:
return "RollbackPlan not produced"
n = len(rb.reversal_steps) if hasattr(rb, "reversal_steps") and rb.reversal_steps else 0
return f"RollbackPlan with {n} reversal step{'s' if n != 1 else ''}"
if command == "submit":
if obs.quality_score >= 0.85:
return f"FIXED, judge verification RESOLVED, final score {obs.quality_score:.2f}"
return f"Episode submitted, final score {obs.quality_score:.2f}"
if command == "inspect":
return "Manager inspected scenario or file"
if command == "read_memory":
n = len(obs.memory_hits) if obs.memory_hits else 0
return f"Retrieved {n} relevant lesson{'s' if n != 1 else ''} from lessons.md"
return ""
@app.post("/run_demo", tags=["APIShift"])
async def run_demo(req: dict):
"""Run an optimal-plan episode in one HTTP call and return the trace.
Used by the web UI to demo a full migration without juggling WebSocket
state in the browser. Returns the per-step reward, an annotation per
step explaining what the specialist did, and the final component
breakdown so the UI can render the bars and the transcript.
"""
task_id = (req or {}).get("task_id")
env = APIShiftEnvironment()
obs0 = env.reset(task_id=task_id)
plan = [
{"command": "dispatch_diff", "rationale": "detect breaking changes"},
{"command": "dispatch_patch", "payload": {"change_id": "ch_001"},
"rationale": "patch ch_001"},
{"command": "dispatch_test", "rationale": "verify backward compat"},
{"command": "dispatch_rollback", "rationale": "produce rollback plan"},
{"command": "submit", "rationale": "finalize migration"},
]
steps = []
last_obs = obs0
for i, action_dict in enumerate(plan, 1):
action = APIShiftAction.model_validate(action_dict)
last_obs = env.step(action)
steps.append({
"step": i,
"command": action.command,
"reward": float(last_obs.reward) if last_obs.reward is not None else 0.0,
"quality_score": float(last_obs.quality_score),
"done": bool(last_obs.done),
"annotation": _annotate_step(action.command, last_obs),
})
if last_obs.done:
break
n_changes = len(obs0.detected_changes) if obs0.detected_changes else 0
if last_obs.quality_score >= 0.85:
verdict = "RESOLVED"
elif last_obs.quality_score >= 0.5:
verdict = "PARTIAL"
else:
verdict = "FAILED"
return {
"scenario": {
"scenario_id": obs0.scenario_id,
"task_description": obs0.task_description,
"framework": obs0.framework,
"language": obs0.language,
"v1_spec_summary": obs0.v1_spec_summary,
"v2_spec_summary": obs0.v2_spec_summary,
"n_breaking_changes": n_changes,
},
"steps": steps,
"final_score": steps[-1]["quality_score"] if steps else 0.0,
"component_rewards": dict(env.state.component_rewards) if env.state.component_rewards else {},
"verdict": verdict,
"n_steps": len(steps),
}
# ---------------------------------------------------------------------
# Stateful HumanAgent sessions, used by the playable HumanAgent panel
# ---------------------------------------------------------------------
# The OpenEnv contract makes /reset and /step stateless (one env per request).
# The HumanAgent UI needs a multi step session, so we maintain an in memory
# dict keyed by session_id with a 15 minute TTL. Capped at 50 sessions.
import time
import secrets
_SESSIONS: dict = {} # session_id -> {"env": APIShiftEnvironment, "history": [...], "last_obs": ..., "ts": float}
_SESSION_TTL = 15 * 60 # 15 minutes
_SESSION_CAP = 50
def _gc_sessions():
"""Drop sessions older than TTL, and enforce the cap."""
now = time.time()
stale = [sid for sid, s in _SESSIONS.items() if now - s["ts"] > _SESSION_TTL]
for sid in stale:
_SESSIONS.pop(sid, None)
if len(_SESSIONS) > _SESSION_CAP:
# drop oldest
oldest = sorted(_SESSIONS.items(), key=lambda kv: kv[1]["ts"])[: len(_SESSIONS) - _SESSION_CAP]
for sid, _ in oldest:
_SESSIONS.pop(sid, None)
def _serialize_obs(obs) -> dict:
"""Trim observation to UI friendly fields."""
if obs is None:
return {}
return {
"scenario_id": obs.scenario_id,
"task_description": obs.task_description,
"framework": obs.framework,
"language": obs.language,
"v1_spec_summary": obs.v1_spec_summary,
"v2_spec_summary": obs.v2_spec_summary,
"n_detected_changes": len(obs.detected_changes) if obs.detected_changes else 0,
"n_generated_patches": len(obs.generated_patches) if obs.generated_patches else 0,
"test_passed": (obs.last_test_result.passed if obs.last_test_result else None),
"test_total": (obs.last_test_result.total if obs.last_test_result else None),
"rollback_present": obs.rollback_plan is not None,
"quality_score": float(obs.quality_score),
"steps_taken": int(obs.steps_taken),
"max_steps": int(obs.max_steps),
"available_commands": list(obs.available_commands) if obs.available_commands else [],
"message": obs.message or "",
"last_action_error": obs.last_action_error,
"reward": float(obs.reward) if obs.reward is not None else 0.0,
"done": bool(obs.done),
}
@app.post("/session/reset", tags=["APIShift"])
async def session_reset(req: dict):
"""Begin or restart a HumanAgent session.
Body:
task_id optional, scenario id to load
session_id optional, reuse an existing session (else a fresh one is created)
Returns the session_id, the initial observation, and the action history (empty).
"""
_gc_sessions()
body = req or {}
sid = body.get("session_id") or secrets.token_urlsafe(12)
task_id = body.get("task_id")
env = APIShiftEnvironment()
obs = env.reset(task_id=task_id)
_SESSIONS[sid] = {
"env": env,
"history": [],
"last_obs": obs,
"ts": time.time(),
"task_id": obs.scenario_id,
}
return {
"session_id": sid,
"task_id": obs.scenario_id,
"observation": _serialize_obs(obs),
"history": [],
"step_count": 0,
"status": "Reset",
}
@app.post("/session/step", tags=["APIShift"])
async def session_step(req: dict):
"""Execute one action against a HumanAgent session.
Body:
session_id required
action APIShiftAction body, or just {"command": "...", "rationale": "..."}
Returns the resulting observation, the updated history, and step count.
"""
body = req or {}
sid = body.get("session_id")
if not sid or sid not in _SESSIONS:
return JSONResponse(status_code=404, content={"error": "session not found, call /session/reset first"})
sess = _SESSIONS[sid]
sess["ts"] = time.time()
action_dict = body.get("action") or body
if "command" not in action_dict:
return JSONResponse(status_code=400, content={"error": "action must include a command"})
try:
action = APIShiftAction.model_validate(action_dict)
except Exception as e:
return JSONResponse(status_code=400, content={"error": f"invalid action: {e}"})
obs = sess["env"].step(action)
sess["last_obs"] = obs
entry = {
"step": len(sess["history"]) + 1,
"command": action.command,
"rationale": action.rationale,
"reward": float(obs.reward) if obs.reward is not None else 0.0,
"quality_score": float(obs.quality_score),
"done": bool(obs.done),
"annotation": _annotate_step(action.command, obs),
}
sess["history"].append(entry)
return {
"session_id": sid,
"observation": _serialize_obs(obs),
"step_entry": entry,
"history": sess["history"],
"step_count": len(sess["history"]),
"status": "Done" if obs.done else "Stepping",
}
@app.get("/session/state", tags=["APIShift"])
async def session_state(session_id: str):
"""Return the current state of a HumanAgent session."""
sid = session_id
if not sid or sid not in _SESSIONS:
return JSONResponse(status_code=404, content={"error": "session not found"})
sess = _SESSIONS[sid]
sess["ts"] = time.time()
obs = sess["last_obs"]
return {
"session_id": sid,
"task_id": sess.get("task_id"),
"observation": _serialize_obs(obs),
"history": sess["history"],
"step_count": len(sess["history"]),
"status": "Done" if (obs and obs.done) else ("Stepping" if sess["history"] else "Reset"),
}
# ---------------------------------------------------------------------
# Web UI at "/" and "/web"
# ---------------------------------------------------------------------
_DASHBOARD_HTML = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>APIShift, the AI co pilot for API migrations</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
.pill { display:inline-block; padding:2px 10px; border-radius:9999px; font-size:0.75rem; font-weight:600; }
pre.codebox { background:#0f172a; color:#e2e8f0; padding:12px; border-radius:8px; font-size:0.78rem; line-height:1.4; overflow:auto; max-height:280px; }
.step-row { animation: fadein 0.25s ease-out; }
@keyframes fadein { from { opacity:0; transform: translateY(4px); } to { opacity:1; transform: translateY(0); } }
.reward-bar { transition: width 0.4s ease; }
</style>
</head>
<body class="bg-slate-50 text-slate-800">
<!-- Hero -->
<header class="bg-gradient-to-br from-slate-900 via-slate-800 to-indigo-900 text-white">
<div class="max-w-6xl mx-auto px-6 py-10">
<div class="flex items-center gap-2 mb-3 flex-wrap">
<span class="pill bg-indigo-500/30 text-indigo-200">OpenEnv Hackathon, India 2026</span>
<a href="/docs" class="pill bg-cyan-500/20 text-cyan-200 hover:bg-cyan-500/30">OpenEnv compatible, spec_version 1</a>
<span class="pill bg-emerald-500/20 text-emerald-200">Team Byte Me</span>
</div>
<h1 class="text-4xl md:text-5xl font-bold tracking-tight">APIShift</h1>
<p class="mt-3 text-lg md:text-xl text-slate-200 max-w-3xl">
An OpenEnv environment where LLM agents learn to migrate code across breaking API contract changes. We trained a Manager on real Stripe, GitHub, Twilio, Slack, and OpenAI version diffs and watched it improve through GRPO.
</p>
<p class="mt-3 text-base text-amber-200 max-w-3xl font-medium">
Can a 7B model learn to migrate 415 real API breaking changes? Run the demo below to see what we trained, or skip to <a href="#story" class="underline">The Story</a> to see the journey from cold start to first light.
</p>
<p class="mt-2 text-sm text-slate-300 max-w-3xl">
Standard OpenEnv contract: <code class="bg-white/10 px-1 rounded">reset</code>, <code class="bg-white/10 px-1 rounded">step</code>, <code class="bg-white/10 px-1 rounded">state</code> over HTTP, plus a stateful WebSocket session at <code class="bg-white/10 px-1 rounded">/ws</code> for multi step episodes. Browse the full <a href="/docs" class="underline text-cyan-200">OpenEnv API contract</a>.
</p>
<div class="mt-6 flex flex-wrap gap-3">
<a href="https://www.youtube.com/watch?v=V7Jtx1KNqx4" target="_blank" class="bg-rose-500 hover:bg-rose-400 text-white font-semibold px-5 py-2 rounded-lg shadow">Watch 60s demo</a>
<a href="#demo" class="bg-emerald-500 hover:bg-emerald-400 text-white font-semibold px-5 py-2 rounded-lg shadow">Try a demo</a>
<a href="/docs" class="bg-white/10 hover:bg-white/20 text-white font-semibold px-5 py-2 rounded-lg backdrop-blur">OpenEnv API docs</a>
<a href="https://huggingface.co/spaces/yaswanth169/apishift-env" class="bg-white/10 hover:bg-white/20 text-white font-semibold px-5 py-2 rounded-lg backdrop-blur" target="_blank">Source on Hugging Face</a>
</div>
</div>
</header>
<!-- Problem and Impact -->
<section class="max-w-6xl mx-auto px-6 py-10">
<div class="grid md:grid-cols-3 gap-5">
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-rose-600 font-semibold text-sm uppercase tracking-wide">The Problem</div>
<p class="mt-2 text-slate-700">API vendors ship breaking changes every quarter. There is no shared training ground for an LLM to learn the recurring skill of safe migration.</p>
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-amber-600 font-semibold text-sm uppercase tracking-wide">The Impact</div>
<p class="mt-2 text-slate-700">One to three weeks of senior engineer time per migration. Same teams hit the same class of problem 18 months later, because nobody captured the lessons.</p>
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-emerald-600 font-semibold text-sm uppercase tracking-wide">Our Solution</div>
<p class="mt-2 text-slate-700">An OpenEnv environment with multi agent dispatch, persistent memory, adaptive curriculum, and a five component anti hacking reward. The trained Manager you see in the demo is proof the environment works.</p>
</div>
</div>
</section>
<!-- Stats strip -->
<section class="max-w-6xl mx-auto px-6">
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div class="bg-indigo-50 rounded-xl p-4 text-center border border-indigo-100">
<div class="text-2xl font-bold text-indigo-700" id="stat-tasks">...</div>
<div class="text-xs text-slate-600 uppercase tracking-wide mt-1">Demo Scenarios</div>
</div>
<div class="bg-indigo-50 rounded-xl p-4 text-center border border-indigo-100">
<div class="text-2xl font-bold text-indigo-700">5</div>
<div class="text-xs text-slate-600 uppercase tracking-wide mt-1">API Providers</div>
</div>
<div class="bg-indigo-50 rounded-xl p-4 text-center border border-indigo-100">
<div class="text-2xl font-bold text-indigo-700">Qwen2.5-7B</div>
<div class="text-xs text-slate-600 uppercase tracking-wide mt-1">Base Model + LoRA</div>
</div>
<div class="bg-indigo-50 rounded-xl p-4 text-center border border-indigo-100">
<div class="text-2xl font-bold text-indigo-700">GRPO</div>
<div class="text-xs text-slate-600 uppercase tracking-wide mt-1">RL Method</div>
</div>
</div>
</section>
<!-- Live Demo -->
<section id="demo" class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-4">Try a live episode</h2>
<p class="text-slate-600 mb-6">Pick a scenario, hit run, and watch the Manager call its specialists in real time. Each step shows the per component reward breakdown.</p>
<div class="grid md:grid-cols-2 gap-6">
<!-- LEFT, scenario picker + diff preview -->
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<h3 class="font-semibold text-slate-900 mb-3">Pick a scenario</h3>
<select id="task-select" class="w-full border border-slate-300 rounded-lg px-3 py-2 mb-4 bg-white">
<option value="">Loading...</option>
</select>
<div id="task-meta" class="text-sm text-slate-700 mb-3"></div>
<div class="text-xs uppercase tracking-wide text-slate-500 font-semibold mb-2">v1 spec, abridged</div>
<pre class="codebox" id="v1-preview">select a task to see v1</pre>
<div class="text-xs uppercase tracking-wide text-slate-500 font-semibold mt-3 mb-2">v2 spec, abridged</div>
<pre class="codebox" id="v2-preview">select a task to see v2</pre>
</div>
<!-- RIGHT, live episode -->
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="flex items-center justify-between mb-3">
<h3 class="font-semibold text-slate-900">Live episode</h3>
<button id="run-btn" class="bg-emerald-500 hover:bg-emerald-400 disabled:bg-slate-300 text-white font-semibold px-4 py-2 rounded-lg text-sm">
Run optimal plan
</button>
</div>
<div id="episode-log" class="space-y-2 mb-4 min-h-[120px]">
<div class="text-sm text-slate-500 italic">No episode running. Pick a scenario above and hit run.</div>
</div>
<div class="border-t border-slate-100 pt-3">
<div class="text-xs uppercase tracking-wide text-slate-500 font-semibold mb-2">Reward breakdown, per component</div>
<div id="reward-bars" class="space-y-2">
<div data-comp="breaking_change_detection" class="text-xs">
<div class="flex justify-between"><span>Breaking change detection (33%)</span><span class="comp-val font-mono">0.00</span></div>
<div class="bg-slate-100 rounded-full h-2 mt-0.5"><div class="reward-bar bg-indigo-500 h-2 rounded-full" style="width:0%"></div></div>
</div>
<div data-comp="migration_patch_correctness" class="text-xs">
<div class="flex justify-between"><span>Migration patch correctness (28%)</span><span class="comp-val font-mono">0.00</span></div>
<div class="bg-slate-100 rounded-full h-2 mt-0.5"><div class="reward-bar bg-indigo-500 h-2 rounded-full" style="width:0%"></div></div>
</div>
<div data-comp="backward_compat_preservation" class="text-xs">
<div class="flex justify-between"><span>Backward compat preservation (24%)</span><span class="comp-val font-mono">0.00</span></div>
<div class="bg-slate-100 rounded-full h-2 mt-0.5"><div class="reward-bar bg-indigo-500 h-2 rounded-full" style="width:0%"></div></div>
</div>
<div data-comp="rollback_plan_completeness" class="text-xs">
<div class="flex justify-between"><span>Rollback plan completeness (10%)</span><span class="comp-val font-mono">0.00</span></div>
<div class="bg-slate-100 rounded-full h-2 mt-0.5"><div class="reward-bar bg-indigo-500 h-2 rounded-full" style="width:0%"></div></div>
</div>
<div data-comp="simplicity_bonus" class="text-xs">
<div class="flex justify-between"><span>Simplicity bonus (5%)</span><span class="comp-val font-mono">0.00</span></div>
<div class="bg-slate-100 rounded-full h-2 mt-0.5"><div class="reward-bar bg-indigo-500 h-2 rounded-full" style="width:0%"></div></div>
</div>
</div>
<div class="mt-3 text-sm">
Final score: <span id="final-score" class="font-bold text-indigo-700">--</span>
</div>
</div>
</div>
</div>
<!-- Episode transcript with findings -->
<div class="bg-slate-900 text-slate-100 rounded-xl p-5 shadow-sm mt-6 font-mono text-sm">
<div class="flex justify-between items-center mb-3 pb-2 border-b border-slate-700">
<div class="text-emerald-300 font-semibold">Episode transcript with findings</div>
<div id="transcript-verdict" class="text-xs text-slate-400">No episode run yet</div>
</div>
<div id="transcript-body" class="space-y-1.5">
<div class="text-slate-500 italic">Run the optimal plan above to see a step by step transcript with what each specialist did.</div>
</div>
<div class="mt-4 pt-3 border-t border-slate-700">
<div class="text-amber-300 font-semibold mb-2 text-xs uppercase tracking-wide">Key findings (this session)</div>
<div id="key-findings" class="text-xs text-slate-300 space-y-1">
<div>Episodes run: <span id="kf-episodes" class="text-white font-semibold">0</span></div>
<div>Success rate: <span id="kf-success" class="text-white font-semibold">--</span></div>
<div>Average score: <span id="kf-avg" class="text-white font-semibold">--</span></div>
<div>Average steps to fix: <span id="kf-steps" class="text-white font-semibold">--</span></div>
</div>
</div>
</div>
</section>
<!-- HumanAgent Interface -->
<section id="humanagent" class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-2">Human Agent mode</h2>
<p class="text-slate-600 mb-6 max-w-3xl">
Take the Manager's seat. Reset the env to a scenario, type one action at a time as JSON, click Step, and watch the observation update on the right. This is the same OpenEnv contract that programmatic agents call.
</p>
<div class="grid md:grid-cols-2 gap-6">
<!-- LEFT, Take Action -->
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="flex items-center gap-2 mb-3">
<span class="w-2 h-2 rounded-full bg-emerald-500"></span>
<h3 class="font-semibold text-slate-900">HumanAgent Interface</h3>
</div>
<div class="bg-slate-50 rounded-lg p-4 mb-3 border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Take Action</div>
<label class="text-xs text-slate-600 mb-1 block">Scenario</label>
<select id="ha-task-select" class="w-full border border-slate-300 rounded-lg px-2 py-1.5 mb-3 bg-white text-sm">
<option value="">Reset first to load options</option>
</select>
<label class="text-xs text-slate-600 mb-1 block">Action JSON <span class="text-rose-500">*</span></label>
<textarea id="ha-action" rows="4" class="w-full border border-slate-300 rounded-lg px-2 py-1.5 font-mono text-xs bg-white" placeholder='{"command":"dispatch_diff","rationale":"detect changes"}'>{"command":"dispatch_diff","rationale":"detect changes"}</textarea>
<div class="text-xs text-slate-500 mt-1">commands: dispatch_diff, classify_impact, dispatch_patch, dispatch_test, dispatch_rollback, read_memory, inspect, submit</div>
<div class="mt-3 flex gap-2 flex-wrap">
<button id="ha-step-btn" class="bg-blue-600 hover:bg-blue-500 text-white font-semibold px-4 py-1.5 rounded text-sm">Step</button>
<button id="ha-reset-btn" class="bg-slate-500 hover:bg-slate-400 text-white font-semibold px-4 py-1.5 rounded text-sm">Reset Environment</button>
<button id="ha-state-btn" class="bg-slate-500 hover:bg-slate-400 text-white font-semibold px-4 py-1.5 rounded text-sm">Get State</button>
</div>
</div>
<div class="bg-slate-50 rounded-lg p-4 border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Current State</div>
<div class="text-xs space-y-1 text-slate-700">
<div>Status: <code id="ha-status" class="bg-white px-1 rounded">Reset</code></div>
<div>Episode ID: <code id="ha-sid" class="bg-white px-1 rounded">-</code></div>
<div>Step Count: <code id="ha-stepcount" class="bg-white px-1 rounded">0</code></div>
<div>Last reward: <code id="ha-lastreward" class="bg-white px-1 rounded">--</code></div>
</div>
</div>
</div>
<!-- RIGHT, State Observer -->
<div class="space-y-3">
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<h3 class="font-semibold text-slate-900 mb-2">State Observer</h3>
<div class="text-sm font-semibold text-slate-700 mb-2">Current Observation</div>
<div id="ha-obs" class="bg-slate-50 rounded p-3 text-xs font-mono text-slate-700 max-h-72 overflow-auto whitespace-pre-wrap">No observation yet. Click Reset Environment to start.</div>
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Action History</div>
<div id="ha-history" class="text-xs text-slate-700 max-h-48 overflow-auto space-y-1">
<div class="italic text-slate-500">No actions taken yet</div>
</div>
</div>
</div>
</div>
</section>
<!-- Architecture -->
<section class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-4">How it works</h2>
<p class="text-slate-600 mb-6 max-w-3xl">
The Manager agent receives one scenario per episode. It calls four specialist agents in sequence, gets scored on five
independent reward components, and writes a markdown lesson at the end so the next episode starts smarter.
</p>
<div class="bg-white rounded-xl p-4 md:p-6 shadow-sm border border-slate-200 overflow-x-auto">
<img src="/assets/architecture.png" alt="APIShift architecture, Manager dispatches to four specialists, scored by a 5 component reward, lesson written, curriculum picks next scenario" class="w-full max-w-4xl mx-auto rounded" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'text-sm italic text-slate-500 py-12 text-center bg-slate-50 rounded',innerText:'Architecture diagram is loading.'}));">
<div class="text-xs text-slate-500 italic text-center mt-3 max-w-3xl mx-auto">
The Manager dispatches to DiffSpecialist, PatchSpecialist, TestSpecialist and RollbackSpecialist. Their outputs are scored by five independent reward components. The MemoryAgent writes a structured lesson, the CurriculumAgent picks the next scenario, and the loop continues.
</div>
</div>
<p class="text-sm text-slate-500 mt-4 max-w-3xl">
Every action above flows through the OpenEnv contract. The web demo above is just a thin wrapper around the same <code class="bg-slate-100 px-1 rounded">/run_demo</code> endpoint that judges and external clients call programmatically.
</p>
</section>
<!-- Reward Design -->
<section class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-4">Reward design, made hard to game</h2>
<p class="text-slate-600 mb-6 max-w-3xl">
Five independent verifiers. The Manager cannot read its own reward. Skipping rollback triggers a hard penalty.
Repeated dispatches do not stack. Memory is write protected from the Manager. Anti hacking story is documented in detail in
<a class="text-indigo-600 underline" href="https://huggingface.co/spaces/yaswanth169/apishift-env/blob/main/docs/REWARD_DESIGN.md">REWARD_DESIGN.md</a>.
</p>
<div class="bg-slate-900 text-emerald-200 font-mono text-sm rounded-xl p-5 overflow-x-auto">
total_reward =
0.33 * breaking_change_detection_score # F1 over labeled breaking changes
+ 0.28 * migration_patch_correctness # template match per change_type
+ 0.24 * backward_compat_preservation # TestSpecialist pass rate
+ 0.10 * rollback_plan_completeness # rollback verifier
+ 0.05 * simplicity_bonus # fewer steps wins
- 0.10 if dispatch_rollback was never called
clamped to (0.01, 0.99)
</div>
</section>
<!-- The Story -->
<section id="story" class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-2">The Story, how the environment and the agent improved together</h2>
<p class="text-slate-600 mb-6 max-w-3xl">
We trained two runs. The journey from the first to the second is the most useful thing about this submission. The environment is what came out of it.
</p>
<div class="grid md:grid-cols-2 gap-5">
<div class="bg-white rounded-xl p-5 shadow-sm border-l-4 border-rose-400">
<div class="text-rose-600 font-semibold text-sm uppercase tracking-wide mb-2">Act 1, the cold start</div>
<p class="text-slate-700 text-sm">First GRPO run with the obvious config. <code class="bg-slate-100 px-1 rounded">num_generations=4</code>, temperature 1.0, single tier reward. Within ten steps the reward locked at 0.01. Model output prose instead of JSON. Reward variance was zero. Gradient norm was zero. The model was not learning.</p>
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border-l-4 border-amber-400">
<div class="text-amber-600 font-semibold text-sm uppercase tracking-wide mb-2">Act 2, the diagnosis</div>
<p class="text-slate-700 text-sm">Reward had no gradation between "no JSON at all" and "some JSON but wrong format". All four completions in a batch landed at the same minimum. GRPO needs variance within the batch to compute advantages. We had none.</p>
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border-l-4 border-cyan-400">
<div class="text-cyan-600 font-semibold text-sm uppercase tracking-wide mb-2">Act 3, the reward fights back</div>
<p class="text-slate-700 text-sm">Three changes. Added a partial credit layer (0.02 per valid JSON command, 0.02 for ending with submit). Bumped <code class="bg-slate-100 px-1 rounded">num_generations</code> from 4 to 8. Bumped temperature 1.0 to 1.2. Dry run reward standard deviation jumped from 0.0 to 0.12.</p>
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border-l-4 border-emerald-400">
<div class="text-emerald-600 font-semibold text-sm uppercase tracking-wide mb-2">Act 4, first light</div>
<p class="text-slate-700 text-sm">By step 100, reward average 0.175. By step 200, 0.20. Peak phase around step 900, averaging 0.245 with a single batch peak of 0.434. Forty four percent of the steps in the early phase fired real gradient updates. The Manager had learned the JSON workflow.</p>
</div>
</div>
<div class="grid md:grid-cols-2 gap-5 mt-5">
<div class="bg-emerald-50 rounded-xl p-5 border border-emerald-200">
<div class="text-emerald-700 font-semibold text-sm uppercase tracking-wide mb-2">What the Manager learned</div>
<ul class="text-sm text-slate-700 space-y-1 list-disc pl-5">
<li>Output JSON action blobs, never prose</li>
<li>Always call <code class="bg-white px-1 rounded">dispatch_diff</code> before any patch</li>
<li>Patch each detected breaking change by its real <code class="bg-white px-1 rounded">change_id</code>, not a placeholder</li>
<li>Always call <code class="bg-white px-1 rounded">dispatch_rollback</code> before submit (the hard penalty taught it this)</li>
<li>End with <code class="bg-white px-1 rounded">submit</code>, never leave the episode hanging</li>
</ul>
</div>
<div class="bg-indigo-50 rounded-xl p-5 border border-indigo-200">
<div class="text-indigo-700 font-semibold text-sm uppercase tracking-wide mb-2">What we learned, from the Manager's failures</div>
<ul class="text-sm text-slate-700 space-y-1 list-disc pl-5">
<li>Cold start GRPO needs partial credit, otherwise gradient is zero forever</li>
<li><code class="bg-white px-1 rounded">num_generations=4</code> is the floor for structured output, eight is safer</li>
<li>Temperature 1.0 collapses output diversity, 1.2 keeps it</li>
<li>Per component reward decomposition belongs in the trainer state, not just the summary</li>
<li>Environment must reward intermediate format compliance, not just final correctness</li>
</ul>
</div>
</div>
<p class="text-sm text-slate-500 italic mt-5 max-w-3xl">
The training infrastructure co-evolved with the agent. The reward function we ship today is the one the agent's failures forced us to design.
</p>
</section>
<!-- Failure types -->
<section class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-4">Breaking change types the environment can inject</h2>
<p class="text-slate-600 mb-6 max-w-3xl">
The mutator in <code class="bg-slate-100 px-1 rounded">scenarios/layer2_synthetic/mutator.py</code> can apply any of these to a real spec from <code class="bg-slate-100 px-1 rounded">scenarios/layer1_real/</code>, producing infinite novel scenarios for training.
</p>
<div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-x-auto">
<table class="w-full text-sm">
<thead class="bg-slate-50 text-slate-700">
<tr>
<th class="text-left px-4 py-3 font-semibold">Change type</th>
<th class="text-left px-4 py-3 font-semibold">Real example</th>
<th class="text-left px-4 py-3 font-semibold">What the agent must produce</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 text-slate-700">
<tr><td class="px-4 py-3"><code>field_renamed</code></td><td class="px-4 py-3">Stripe <code>customer_email</code> to <code>customer_contact_email</code></td><td class="px-4 py-3">Replace field references in request body and response handler</td></tr>
<tr><td class="px-4 py-3"><code>endpoint_removed</code></td><td class="px-4 py-3"><code>/v1/old_endpoint</code> deleted in v2</td><td class="px-4 py-3">Update URL and migrate request shape to the replacement endpoint</td></tr>
<tr><td class="px-4 py-3"><code>parameter_added_required</code></td><td class="px-4 py-3">New required <code>idempotency_key</code></td><td class="px-4 py-3">Add the parameter at every call site</td></tr>
<tr><td class="px-4 py-3"><code>parameter_removed</code></td><td class="px-4 py-3">Removed <code>legacy_format</code></td><td class="px-4 py-3">Drop the parameter from every call site</td></tr>
<tr><td class="px-4 py-3"><code>type_changed</code></td><td class="px-4 py-3"><code>amount</code> int to string</td><td class="px-4 py-3">Wrap calls in str / int conversion at boundary</td></tr>
<tr><td class="px-4 py-3"><code>auth_scheme_changed</code></td><td class="px-4 py-3">GitHub PAT to Bearer</td><td class="px-4 py-3">Swap the Authorization header construction</td></tr>
<tr><td class="px-4 py-3"><code>response_field_renamed</code></td><td class="px-4 py-3">Twilio <code>from</code> to <code>from_phone</code></td><td class="px-4 py-3">Update response field accessors</td></tr>
<tr><td class="px-4 py-3"><code>enum_value_removed</code></td><td class="px-4 py-3">Slack <code>presence=auto</code> removed</td><td class="px-4 py-3">Map old values to new ones in client wrapper</td></tr>
<tr><td class="px-4 py-3"><code>multi_change</code></td><td class="px-4 py-3">Two or three of the above in one episode</td><td class="px-4 py-3">Diff first, classify all, patch each by id</td></tr>
</tbody>
</table>
</div>
</section>
<!-- Plots placeholder, filled after Phase B -->
<section id="plots" class="max-w-6xl mx-auto px-6 py-10">
<h2 class="text-2xl font-bold text-slate-900 mb-4">Training results</h2>
<p class="text-slate-600 mb-6 max-w-3xl">
Trained on a single A40 GPU with TRL GRPO and LoRA on Qwen2.5-7B. Plots below summarize the run.
</p>
<div class="grid md:grid-cols-2 gap-5">
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Reward curve over training</div>
<img src="/assets/reward_curve.png" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'text-sm italic text-slate-500 py-12 text-center bg-slate-50 rounded',innerText:'Plot will appear here once training run completes.'}));" class="w-full rounded">
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Reward by training phase (early / mid / late)</div>
<img src="/assets/baseline_vs_trained.png" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'text-sm italic text-slate-500 py-12 text-center bg-slate-50 rounded',innerText:'Plot will appear here once baseline and trained eval run.'}));" class="w-full rounded">
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Reward components stacked over training</div>
<img src="/assets/reward_components.png" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'text-sm italic text-slate-500 py-12 text-center bg-slate-50 rounded',innerText:'Plot will appear here once training run completes.'}));" class="w-full rounded">
</div>
<div class="bg-white rounded-xl p-5 shadow-sm border border-slate-200">
<div class="text-sm font-semibold text-slate-700 mb-2">Reward density: early training vs late training</div>
<img src="/assets/reward_distribution.png" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'text-sm italic text-slate-500 py-12 text-center bg-slate-50 rounded',innerText:'Plot will appear here once both eval runs complete.'}));" class="w-full rounded">
</div>
</div>
</section>
<!-- Footer -->
<footer class="bg-slate-900 text-slate-400 py-8 mt-10">
<div class="max-w-6xl mx-auto px-6 grid md:grid-cols-3 gap-6 text-sm">
<div>
<div class="text-white font-semibold mb-2">APIShift</div>
<div>Open source under MIT License. Built for the OpenEnv Hackathon, India 2026.</div>
</div>
<div>
<div class="text-white font-semibold mb-2">Materials</div>
<ul class="space-y-1">
<li><a class="hover:text-white" href="https://www.youtube.com/watch?v=V7Jtx1KNqx4" target="_blank">60s demo video</a></li>
<li><a class="hover:text-white" href="/docs">OpenEnv API docs</a></li>
<li><a class="hover:text-white" href="/tasks">List scenarios</a></li>
<li><a class="hover:text-white" href="/program">Operating manual</a></li>
<li><a class="hover:text-white" href="/lessons">Memory artifact</a></li>
</ul>
</div>
<div>
<div class="text-white font-semibold mb-2">Team Byte Me</div>
<div>Ireddi Rakshitha</div>
<div>Devavarapu Yashwanth</div>
</div>
</div>
</footer>
<script>
const COMMANDS = ['dispatch_diff','dispatch_patch','dispatch_test','dispatch_rollback','submit'];
let currentTasks = [];
async function loadTasks() {
try {
const res = await fetch('/tasks');
const data = await res.json();
currentTasks = data.tasks || [];
const sel = document.getElementById('task-select');
sel.innerHTML = '';
document.getElementById('stat-tasks').textContent = currentTasks.length;
if (currentTasks.length === 0) {
sel.innerHTML = '<option value="">No tasks available</option>';
return;
}
currentTasks.slice(0, 12).forEach(t => {
const opt = document.createElement('option');
opt.value = typeof t === 'string' ? t : (t.task_id || t.scenario_id || '');
opt.textContent = opt.value;
sel.appendChild(opt);
});
sel.dispatchEvent(new Event('change'));
} catch (e) {
document.getElementById('task-select').innerHTML = '<option value="">Failed to load</option>';
}
}
async function showTaskMeta(tid) {
if (!tid) return;
try {
const res = await fetch('/reset', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({task_id: tid})
});
const data = await res.json();
const obs = data.observation || {};
document.getElementById('task-meta').innerHTML = `
<div><span class="font-semibold">${obs.scenario_id || tid}</span></div>
<div class="text-slate-600">${obs.task_description || ''}</div>
<div class="text-xs text-slate-500 mt-1">framework: ${obs.framework || '?'}, language: ${obs.language || '?'}</div>
`;
document.getElementById('v1-preview').textContent = (obs.v1_spec_summary || '').slice(0, 1000);
document.getElementById('v2-preview').textContent = (obs.v2_spec_summary || '').slice(0, 1000);
} catch (e) {
document.getElementById('task-meta').innerHTML = `<div class="text-rose-600">Could not load task: ${e.message}</div>`;
}
}
document.getElementById('task-select').addEventListener('change', e => showTaskMeta(e.target.value));
async function runEpisode() {
const tid = document.getElementById('task-select').value;
if (!tid) return;
const btn = document.getElementById('run-btn');
btn.disabled = true; btn.textContent = 'Running...';
const log = document.getElementById('episode-log');
log.innerHTML = '';
document.getElementById('final-score').textContent = '...';
// reset bars
document.querySelectorAll('#reward-bars .reward-bar').forEach(b => b.style.width = '0%');
document.querySelectorAll('#reward-bars .comp-val').forEach(c => c.textContent = '0.00');
try {
const res = await fetch('/run_demo', {
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({task_id: tid})
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const steps = data.steps || [];
for (const s of steps) {
const row = document.createElement('div');
row.className = 'step-row text-sm bg-slate-50 rounded-lg p-2 flex justify-between items-center';
row.innerHTML = `
<div><span class="text-xs text-slate-500 mr-2">step ${s.step}</span><span class="font-mono text-indigo-700">${s.command}</span></div>
<div class="font-mono text-emerald-700">+${(s.reward||0).toFixed(3)} <span class="text-slate-400 ml-2">cum ${(s.quality_score||0).toFixed(3)}</span></div>
`;
log.appendChild(row);
await new Promise(r => setTimeout(r, 350));
}
const components = data.component_rewards || {};
Object.entries(components).forEach(([k, v]) => {
const row = document.querySelector(`#reward-bars [data-comp="${k}"]`);
if (row) {
row.querySelector('.reward-bar').style.width = `${Math.min(100, v * 100)}%`;
row.querySelector('.comp-val').textContent = (v || 0).toFixed(2);
}
});
document.getElementById('final-score').textContent = (data.final_score || 0).toFixed(3);
// Episode transcript with findings
renderTranscript(data);
recordKeyFindings(data);
} catch (e) {
log.innerHTML = `<div class="text-rose-600 text-sm">Episode failed: ${e.message}</div>`;
} finally {
btn.disabled = false; btn.textContent = 'Run optimal plan';
}
}
function renderTranscript(data) {
const body = document.getElementById('transcript-body');
const verdictEl = document.getElementById('transcript-verdict');
body.innerHTML = '';
const head = document.createElement('div');
head.className = 'text-cyan-300 mb-2';
head.textContent = `Episode: ${data.scenario.scenario_id} -> ${data.scenario.task_description || ''}`;
body.appendChild(head);
for (const s of (data.steps || [])) {
const line = document.createElement('div');
const rewardColor = s.reward >= 0.5 ? 'text-emerald-300' : (s.reward > 0 ? 'text-amber-300' : 'text-rose-300');
const arrow = s.annotation ? `<span class="text-slate-400 ml-3">${'<-'} ${s.annotation}</span>` : '';
line.innerHTML = `<span class="text-slate-500">Step ${s.step}:</span> <span class="text-cyan-300">${s.command.padEnd(20, ' ')}</span> <span class="${rewardColor}">reward=${s.reward >= 0 ? '+' : ''}${(s.reward||0).toFixed(2)}</span>${arrow}`;
body.appendChild(line);
}
const verdictBadge = data.verdict === 'RESOLVED' ? 'bg-emerald-500/20 text-emerald-300' : (data.verdict === 'PARTIAL' ? 'bg-amber-500/20 text-amber-300' : 'bg-rose-500/20 text-rose-300');
verdictEl.className = `text-xs px-2 py-1 rounded ${verdictBadge}`;
verdictEl.textContent = `${data.verdict}, final ${data.final_score.toFixed(2)} in ${data.n_steps} steps`;
const finalLine = document.createElement('div');
finalLine.className = 'text-emerald-300 mt-2 pt-2 border-t border-slate-700';
finalLine.textContent = `-> Judge verification: ${data.verdict}, final score ${data.final_score.toFixed(2)}`;
body.appendChild(finalLine);
}
const _kf = { episodes: 0, successes: 0, totalScore: 0, totalSteps: 0 };
function recordKeyFindings(data) {
_kf.episodes += 1;
if (data.verdict === 'RESOLVED') _kf.successes += 1;
_kf.totalScore += data.final_score || 0;
_kf.totalSteps += data.n_steps || 0;
document.getElementById('kf-episodes').textContent = _kf.episodes;
document.getElementById('kf-success').textContent = `${_kf.successes}/${_kf.episodes} (${(100 * _kf.successes / _kf.episodes).toFixed(0)}%)`;
document.getElementById('kf-avg').textContent = (_kf.totalScore / _kf.episodes).toFixed(3);
document.getElementById('kf-steps').textContent = (_kf.totalSteps / _kf.episodes).toFixed(1);
}
document.getElementById('run-btn').addEventListener('click', runEpisode);
// =====================================================================
// HumanAgent panel
// =====================================================================
let _haSessionId = null;
async function haReset() {
const tid = document.getElementById('ha-task-select').value || document.getElementById('task-select').value;
setHaStatus('Resetting...');
try {
const res = await fetch('/session/reset', {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({task_id: tid, session_id: _haSessionId})
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
_haSessionId = data.session_id;
document.getElementById('ha-sid').textContent = _haSessionId.slice(0, 10) + '...';
document.getElementById('ha-stepcount').textContent = '0';
document.getElementById('ha-lastreward').textContent = '--';
document.getElementById('ha-status').textContent = 'Reset';
document.getElementById('ha-history').innerHTML = '<div class="italic text-slate-500">No actions taken yet</div>';
renderHaObs(data.observation);
populateHaTaskSelect(data.task_id);
} catch (e) {
setHaStatus(`Error: ${e.message}`);
}
}
async function haStep() {
if (!_haSessionId) { setHaStatus('Reset first'); return; }
const raw = document.getElementById('ha-action').value.trim();
let action;
try { action = JSON.parse(raw); }
catch (e) { setHaStatus('Invalid JSON in action'); return; }
setHaStatus('Stepping...');
try {
const res = await fetch('/session/step', {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({session_id: _haSessionId, action: action})
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
document.getElementById('ha-status').textContent = data.status;
document.getElementById('ha-stepcount').textContent = data.step_count;
document.getElementById('ha-lastreward').textContent = (data.step_entry.reward).toFixed(3);
renderHaObs(data.observation);
renderHaHistory(data.history);
} catch (e) {
setHaStatus(`Error: ${e.message}`);
}
}
async function haGetState() {
if (!_haSessionId) { setHaStatus('Reset first'); return; }
try {
const res = await fetch(`/session/state?session_id=${encodeURIComponent(_haSessionId)}`);
const data = await res.json();
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
document.getElementById('ha-status').textContent = data.status;
document.getElementById('ha-stepcount').textContent = data.step_count;
renderHaObs(data.observation);
renderHaHistory(data.history);
} catch (e) {
setHaStatus(`Error: ${e.message}`);
}
}
function setHaStatus(s) {
document.getElementById('ha-status').textContent = s;
}
function renderHaObs(obs) {
if (!obs) { document.getElementById('ha-obs').textContent = 'No observation yet'; return; }
const lines = [];
lines.push(`scenario_id : ${obs.scenario_id || '-'}`);
lines.push(`task : ${obs.task_description || '-'}`);
lines.push(`framework / lang : ${obs.framework || '-'} / ${obs.language || '-'}`);
lines.push(`step : ${obs.steps_taken} of ${obs.max_steps}`);
lines.push(`done : ${obs.done}`);
lines.push(`quality_score : ${obs.quality_score.toFixed(3)}`);
lines.push(`reward (last) : ${obs.reward.toFixed(3)}`);
lines.push(`detected_changes : ${obs.n_detected_changes}`);
lines.push(`generated_patches: ${obs.n_generated_patches}`);
if (obs.test_total !== null) lines.push(`tests passed : ${obs.test_passed} of ${obs.test_total}`);
lines.push(`rollback_present : ${obs.rollback_present}`);
if (obs.message) lines.push(`message : ${obs.message}`);
if (obs.last_action_error) lines.push(`error : ${obs.last_action_error}`);
lines.push('');
lines.push(`available_commands:`);
for (const c of (obs.available_commands || [])) lines.push(` - ${c}`);
document.getElementById('ha-obs').textContent = lines.join('\\n');
}
function renderHaHistory(history) {
const el = document.getElementById('ha-history');
if (!history || history.length === 0) {
el.innerHTML = '<div class="italic text-slate-500">No actions taken yet</div>';
return;
}
el.innerHTML = '';
for (const h of history) {
const row = document.createElement('div');
const rewardColor = h.reward >= 0.5 ? 'text-emerald-700' : (h.reward > 0 ? 'text-amber-700' : 'text-rose-700');
row.className = 'border-l-2 border-slate-200 pl-2 py-0.5';
row.innerHTML = `<span class="text-slate-500">${h.step}.</span> <code class="text-indigo-700">${h.command}</code> <span class="${rewardColor}">${h.reward >= 0 ? '+' : ''}${h.reward.toFixed(3)}</span>${h.annotation ? `<div class="text-slate-500 ml-4 text-xs italic">${h.annotation}</div>` : ''}`;
el.appendChild(row);
}
}
function populateHaTaskSelect(currentTid) {
const sel = document.getElementById('ha-task-select');
sel.innerHTML = '';
currentTasks.slice(0, 12).forEach(t => {
const tid = typeof t === 'string' ? t : (t.task_id || t.scenario_id || '');
const opt = document.createElement('option');
opt.value = tid;
opt.textContent = tid;
if (tid === currentTid) opt.selected = true;
sel.appendChild(opt);
});
}
document.getElementById('ha-step-btn').addEventListener('click', haStep);
document.getElementById('ha-reset-btn').addEventListener('click', haReset);
document.getElementById('ha-state-btn').addEventListener('click', haGetState);
loadTasks();
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def root():
return HTMLResponse(content=_DASHBOARD_HTML)
@app.get("/web", response_class=HTMLResponse, include_in_schema=False)
async def web():
return HTMLResponse(content=_DASHBOARD_HTML)
# Static asset route for plots, served from outputs/ at the repo root
@app.get("/assets/{filename}", include_in_schema=False)
async def assets(filename: str):
"""Serve plot images from outputs/. Used by the web UI plot section."""
from fastapi.responses import FileResponse
safe = os.path.basename(filename)
candidate = os.path.join("outputs", safe)
if not os.path.exists(candidate):
return JSONResponse(status_code=404, content={"error": "asset not found", "path": candidate})
return FileResponse(candidate)
# ---------------------------------------------------------------------
# Server entry point (for `uv run server` and `python -m server.app`)
# ---------------------------------------------------------------------
def main() -> None:
"""Start uvicorn on the standard OpenEnv port."""
import uvicorn
uvicorn.run(
"server.app:app",
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", "7860")),
log_level="info",
)
if __name__ == "__main__":
main()
"""APIShift FastAPI app β the OpenEnv server entry point.
Built on top of openenv-core's create_fastapi_app, which provides the
official OpenEnv contract:
HTTP endpoints (stateless β one env instance per request):
POST /reset POST /step GET /state GET /schema
GET /metadata GET /health GET /docs
WebSocket endpoint (stateful β one env instance per connection):
/ws with messages {"type": "reset"|"step"|"state"|"close", "data": {...}}
Because APIShift's Manager runs multi-step episodes (Diff β Patch β Test
β Rollback β Submit), the canonical transport is the WebSocket /ws
endpoint, where one connection == one episode. The HTTP /reset and /step
remain available for stateless one-shot calls.
In addition to the openenv-core endpoints we mount three GET routes that
expose the inspectable artifacts (program, lessons, curriculum) so judges
and reviewers can fetch them directly without cloning the repo.
"""
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse
from models import APIShiftAction, APIShiftObservation
from server.environment import APIShiftEnvironment, list_tasks
# ---------------------------------------------------------------------
# Build the OpenEnv-standard FastAPI app
# ---------------------------------------------------------------------
# create_fastapi_app expects a *factory* (callable returning a fresh env
# per call). Our env constructor takes no required arguments, so passing
# the class itself works. Each new HTTP request gets its own instance;
# each WebSocket connection gets its own dedicated session env.
try:
from openenv.core.env_server import create_fastapi_app
app: FastAPI = create_fastapi_app(
APIShiftEnvironment,
APIShiftAction,
APIShiftObservation,
)
_OPENENV_AVAILABLE = True
except ImportError:
# Fallback for local dev without openenv-core installed.
_OPENENV_AVAILABLE = False
app = FastAPI(title="APIShift", version="0.1.0")
_env = APIShiftEnvironment()
async def reset_endpoint(req):
body = await req.json()
obs = _env.reset(**(body or {}))
return JSONResponse(content={
"observation": obs.model_dump(),
"reward": obs.reward,
"done": obs.done,
})
async def step_endpoint(req):
body = await req.json()
action_body = body.get("action", body) if isinstance(body, dict) else body
action = APIShiftAction.model_validate(action_body)
obs = _env.step(action)
return JSONResponse(content={
"observation": obs.model_dump(),
"reward": obs.reward,
"done": obs.done,
})
async def state_endpoint():
return JSONResponse(content=_env.state.model_dump())
async def health():
return {"status": "healthy"}
# ---------------------------------------------------------------------
# Cross-origin support so the env is browseable from anywhere
# ---------------------------------------------------------------------
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------
# APIShift-specific endpoints (additive, do not override OpenEnv routes)