Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- server/app.py +164 -0
- server/opencode_environment.py +356 -4
- uv.lock +2 -2
server/app.py
CHANGED
|
@@ -4,6 +4,11 @@ Mirrors the ``e2b_desktop`` pattern: pass a ``gradio_builder`` to
|
|
| 4 |
``create_app`` and let OpenEnv handle the Gradio mount (including the
|
| 5 |
HF-Space-compatible ``/web`` path). No manual ``gr.mount_gradio_app``.
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
Usage::
|
| 8 |
|
| 9 |
# Development:
|
|
@@ -69,6 +74,165 @@ app = create_app(
|
|
| 69 |
)
|
| 70 |
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
def main(host: str = "0.0.0.0", port: int = 8000) -> None:
|
| 73 |
import uvicorn
|
| 74 |
|
|
|
|
| 4 |
``create_app`` and let OpenEnv handle the Gradio mount (including the
|
| 5 |
HF-Space-compatible ``/web`` path). No manual ``gr.mount_gradio_app``.
|
| 6 |
|
| 7 |
+
Also mounts a bespoke SSE endpoint at ``GET /rollouts/{rollout_id}/events``
|
| 8 |
+
that multiplexes opencode serve's ``/event`` stream with our proxy's
|
| 9 |
+
per-turn frames. MCP tools don't support streaming; this gives the UI
|
| 10 |
+
and interactive clients a live feed.
|
| 11 |
+
|
| 12 |
Usage::
|
| 13 |
|
| 14 |
# Development:
|
|
|
|
| 74 |
)
|
| 75 |
|
| 76 |
|
| 77 |
+
def _find_active_environment(request):
|
| 78 |
+
"""Locate the currently-active OpenCodeEnvironment instance for a request.
|
| 79 |
+
|
| 80 |
+
``create_app`` keeps per-session envs behind the scenes; for the SSE
|
| 81 |
+
endpoint we just grab the most recent one (single-worker Space), so
|
| 82 |
+
we poke at ``app.state.env_cache`` and fall back to ``web_manager``.
|
| 83 |
+
"""
|
| 84 |
+
cache = getattr(app.state, "env_cache", None)
|
| 85 |
+
if cache:
|
| 86 |
+
try:
|
| 87 |
+
return next(iter(cache.values()))
|
| 88 |
+
except StopIteration:
|
| 89 |
+
pass
|
| 90 |
+
try:
|
| 91 |
+
return _web_manager.get_environment() # type: ignore[name-defined]
|
| 92 |
+
except Exception:
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@app.get("/rollouts/{rollout_id}/events")
|
| 97 |
+
async def rollout_events(rollout_id: str):
|
| 98 |
+
"""Server-Sent Events feed for a rollout started via ``start_rollout``.
|
| 99 |
+
|
| 100 |
+
Merges two streams:
|
| 101 |
+
|
| 102 |
+
1. opencode serve's ``GET /event`` (session-level events: message
|
| 103 |
+
parts, tool calls, idle/abort markers) β forwarded as-is.
|
| 104 |
+
2. our proxy's ``proxy_trace.jsonl`` in the sandbox (per-turn
|
| 105 |
+
LLM turns + logprobs) β tailed and emitted as
|
| 106 |
+
``{type: "proxy.turn", turn, tokens, logprobs, finish_reason, ...}``.
|
| 107 |
+
|
| 108 |
+
Terminates on a final ``{"type": "rollout.done", ...}`` frame once the
|
| 109 |
+
session has idled or erred.
|
| 110 |
+
"""
|
| 111 |
+
import asyncio
|
| 112 |
+
import json as _json
|
| 113 |
+
|
| 114 |
+
from starlette.responses import StreamingResponse
|
| 115 |
+
|
| 116 |
+
env = _find_active_environment(None)
|
| 117 |
+
if env is None:
|
| 118 |
+
return StreamingResponse(
|
| 119 |
+
iter([f"data: {_json.dumps({'type': 'error', 'reason': 'env not found'})}\n\n"]),
|
| 120 |
+
media_type="text/event-stream",
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
registry = getattr(env, "_registry", None)
|
| 124 |
+
handle = registry.get(rollout_id) if registry else None
|
| 125 |
+
if handle is None:
|
| 126 |
+
async def _single_error():
|
| 127 |
+
yield (
|
| 128 |
+
"data: "
|
| 129 |
+
+ _json.dumps({"type": "error", "rollout_id": rollout_id, "reason": "unknown rollout"})
|
| 130 |
+
+ "\n\n"
|
| 131 |
+
)
|
| 132 |
+
return StreamingResponse(_single_error(), media_type="text/event-stream")
|
| 133 |
+
|
| 134 |
+
async def _gen():
|
| 135 |
+
# Wait briefly for the serve client to be wired by the worker.
|
| 136 |
+
for _ in range(60):
|
| 137 |
+
if handle.session is not None and getattr(handle.session, "serve_client", None):
|
| 138 |
+
break
|
| 139 |
+
if handle.is_done():
|
| 140 |
+
break
|
| 141 |
+
await asyncio.sleep(0.25)
|
| 142 |
+
session = handle.session
|
| 143 |
+
if session is None:
|
| 144 |
+
yield (
|
| 145 |
+
"data: "
|
| 146 |
+
+ _json.dumps({
|
| 147 |
+
"type": "error",
|
| 148 |
+
"rollout_id": rollout_id,
|
| 149 |
+
"reason": "session never created",
|
| 150 |
+
"detail": handle.error,
|
| 151 |
+
})
|
| 152 |
+
+ "\n\n"
|
| 153 |
+
)
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
sandbox = session.sandbox
|
| 157 |
+
proxy_trace_path = session._proxy_trace_path
|
| 158 |
+
serve_client = getattr(session, "serve_client", None)
|
| 159 |
+
|
| 160 |
+
# Task A: forward opencode serve events.
|
| 161 |
+
serve_q: asyncio.Queue = asyncio.Queue()
|
| 162 |
+
|
| 163 |
+
async def forward_serve():
|
| 164 |
+
if serve_client is None:
|
| 165 |
+
return
|
| 166 |
+
try:
|
| 167 |
+
async for ev in serve_client.astream_events():
|
| 168 |
+
await serve_q.put({"source": "serve", **ev})
|
| 169 |
+
if handle.is_done():
|
| 170 |
+
break
|
| 171 |
+
except Exception as exc: # noqa: BLE001
|
| 172 |
+
await serve_q.put({"source": "serve", "type": "error", "reason": str(exc)})
|
| 173 |
+
finally:
|
| 174 |
+
await serve_q.put(None)
|
| 175 |
+
|
| 176 |
+
# Task B: tail proxy trace file (incremental) from the sandbox.
|
| 177 |
+
async def tail_proxy():
|
| 178 |
+
last_len = 0
|
| 179 |
+
while not handle.is_done():
|
| 180 |
+
try:
|
| 181 |
+
if proxy_trace_path:
|
| 182 |
+
content = sandbox.read_text(proxy_trace_path) or ""
|
| 183 |
+
if len(content) > last_len:
|
| 184 |
+
new = content[last_len:]
|
| 185 |
+
last_len = len(content)
|
| 186 |
+
for line in new.splitlines():
|
| 187 |
+
line = line.strip()
|
| 188 |
+
if not line:
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
turn = _json.loads(line)
|
| 192 |
+
except Exception:
|
| 193 |
+
continue
|
| 194 |
+
await serve_q.put({
|
| 195 |
+
"source": "proxy",
|
| 196 |
+
"type": "proxy.turn",
|
| 197 |
+
"turn": turn.get("turn"),
|
| 198 |
+
"finish_reason": turn.get("finish_reason"),
|
| 199 |
+
"n_tokens": len(turn.get("completion_tokens") or []),
|
| 200 |
+
"first_tokens": (turn.get("completion_tokens") or [])[:6],
|
| 201 |
+
"first_logps": (turn.get("per_token_logps") or [])[:6],
|
| 202 |
+
"latency_s": turn.get("latency_s"),
|
| 203 |
+
})
|
| 204 |
+
except Exception:
|
| 205 |
+
pass
|
| 206 |
+
await asyncio.sleep(1.0)
|
| 207 |
+
|
| 208 |
+
t_serve = asyncio.create_task(forward_serve())
|
| 209 |
+
t_proxy = asyncio.create_task(tail_proxy())
|
| 210 |
+
|
| 211 |
+
try:
|
| 212 |
+
while True:
|
| 213 |
+
try:
|
| 214 |
+
ev = await asyncio.wait_for(serve_q.get(), timeout=1.0)
|
| 215 |
+
except asyncio.TimeoutError:
|
| 216 |
+
ev = None
|
| 217 |
+
if ev is None:
|
| 218 |
+
if handle.is_done():
|
| 219 |
+
break
|
| 220 |
+
continue
|
| 221 |
+
yield "data: " + _json.dumps(ev) + "\n\n"
|
| 222 |
+
finally:
|
| 223 |
+
t_serve.cancel()
|
| 224 |
+
t_proxy.cancel()
|
| 225 |
+
|
| 226 |
+
yield "data: " + _json.dumps({
|
| 227 |
+
"source": "server",
|
| 228 |
+
"type": "rollout.done",
|
| 229 |
+
"rollout_id": rollout_id,
|
| 230 |
+
"error": handle.error,
|
| 231 |
+
}) + "\n\n"
|
| 232 |
+
|
| 233 |
+
return StreamingResponse(_gen(), media_type="text/event-stream")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
def main(host: str = "0.0.0.0", port: int = 8000) -> None:
|
| 237 |
import uvicorn
|
| 238 |
|
server/opencode_environment.py
CHANGED
|
@@ -21,6 +21,7 @@ from __future__ import annotations
|
|
| 21 |
|
| 22 |
import json
|
| 23 |
import os
|
|
|
|
| 24 |
import time
|
| 25 |
from typing import Any, Optional
|
| 26 |
from uuid import uuid4
|
|
@@ -50,17 +51,87 @@ WORKDIR_PATH = "/home/user/workdir"
|
|
| 50 |
VERIFIER_TIMEOUT_S = 120
|
| 51 |
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
class OpenCodeEnvironment(MCPEnvironment):
|
| 54 |
-
"""
|
| 55 |
|
| 56 |
-
The
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
"""
|
| 60 |
|
| 61 |
SUPPORTS_CONCURRENT_SESSIONS = True
|
| 62 |
|
| 63 |
def __init__(self) -> None:
|
|
|
|
|
|
|
|
|
|
| 64 |
# Import inside __init__ to keep module import cheap and to allow
|
| 65 |
# patching for tests. Dual-import pattern: package when installed,
|
| 66 |
# flat when run directly out of the repo via ``server.app:app``.
|
|
@@ -151,6 +222,143 @@ class OpenCodeEnvironment(MCPEnvironment):
|
|
| 151 |
agent_timeout_s=agent_timeout_s,
|
| 152 |
)
|
| 153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
super().__init__(mcp)
|
| 155 |
|
| 156 |
# ββ OpenEnv lifecycle ββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -397,6 +605,150 @@ def _clamp_turn(turn: dict[str, Any]) -> dict[str, Any]:
|
|
| 397 |
return out
|
| 398 |
|
| 399 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
def _tail(events: list[dict[str, Any]], n: int) -> str:
|
| 401 |
"""Return the last ``n`` opencode event lines as a newline-joined string."""
|
| 402 |
if not events:
|
|
|
|
| 21 |
|
| 22 |
import json
|
| 23 |
import os
|
| 24 |
+
import threading
|
| 25 |
import time
|
| 26 |
from typing import Any, Optional
|
| 27 |
from uuid import uuid4
|
|
|
|
| 51 |
VERIFIER_TIMEOUT_S = 120
|
| 52 |
|
| 53 |
|
| 54 |
+
class _RolloutRegistry:
|
| 55 |
+
"""Per-environment bookkeeping for in-flight non-blocking rollouts.
|
| 56 |
+
|
| 57 |
+
Every ``start_rollout`` call spawns a background thread that owns a
|
| 58 |
+
session through its full lifecycle (create sandbox β install opencode
|
| 59 |
+
β start proxy + opencode serve β fire instruction β wait for agent β
|
| 60 |
+
finalize on demand). The registry keeps one :class:`_RolloutHandle`
|
| 61 |
+
per ``rollout_id`` so subsequent ``subscribe_events`` / ``abort_rollout``
|
| 62 |
+
/ ``finalize`` tool calls can find it.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self) -> None:
|
| 66 |
+
self._lock = threading.Lock()
|
| 67 |
+
self._handles: dict[str, "_RolloutHandle"] = {}
|
| 68 |
+
|
| 69 |
+
def add(self, handle: "_RolloutHandle") -> None:
|
| 70 |
+
with self._lock:
|
| 71 |
+
self._handles[handle.rollout_id] = handle
|
| 72 |
+
|
| 73 |
+
def get(self, rollout_id: str) -> "_RolloutHandle | None":
|
| 74 |
+
with self._lock:
|
| 75 |
+
return self._handles.get(rollout_id)
|
| 76 |
+
|
| 77 |
+
def drop(self, rollout_id: str) -> None:
|
| 78 |
+
with self._lock:
|
| 79 |
+
self._handles.pop(rollout_id, None)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class _RolloutHandle:
|
| 83 |
+
"""Everything the server needs to finalize / observe / abort a rollout."""
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
rollout_id: str,
|
| 88 |
+
task_id: str,
|
| 89 |
+
session_factory_kwargs: dict[str, Any],
|
| 90 |
+
task: Any,
|
| 91 |
+
) -> None:
|
| 92 |
+
self.rollout_id = rollout_id
|
| 93 |
+
self.task_id = task_id
|
| 94 |
+
self._kwargs = session_factory_kwargs
|
| 95 |
+
self._task = task
|
| 96 |
+
|
| 97 |
+
# Set by the worker thread as the session progresses.
|
| 98 |
+
self.session: Any | None = None
|
| 99 |
+
self.error: str | None = None
|
| 100 |
+
self.started_at = time.time()
|
| 101 |
+
self.finished_at: float | None = None
|
| 102 |
+
self._done = threading.Event()
|
| 103 |
+
self._worker: threading.Thread | None = None
|
| 104 |
+
self._verifier_stdout = ""
|
| 105 |
+
self._verifier_stderr = ""
|
| 106 |
+
self._test_exit_code: int | None = None
|
| 107 |
+
self._test_script: str = ""
|
| 108 |
+
|
| 109 |
+
def is_done(self) -> bool:
|
| 110 |
+
return self._done.is_set()
|
| 111 |
+
|
| 112 |
+
def wait(self, timeout: float | None = None) -> bool:
|
| 113 |
+
return self._done.wait(timeout)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
class OpenCodeEnvironment(MCPEnvironment):
|
| 117 |
+
"""Two-tier MCP environment for OpenCode rollouts.
|
| 118 |
|
| 119 |
+
The **macro tool** ``run_rollout`` runs a blocking end-to-end rollout
|
| 120 |
+
and returns the final :class:`RolloutResult` (kept for training, which
|
| 121 |
+
doesn't benefit from per-turn streaming).
|
| 122 |
+
|
| 123 |
+
The **fine-grained tools** ``start_rollout`` / ``subscribe_events``
|
| 124 |
+
(server-side SSE via a helper endpoint) / ``abort_rollout`` / ``finalize``
|
| 125 |
+
are meant for the Gradio UI and interactive inspection β they expose
|
| 126 |
+
the PR #471-style session primitives directly.
|
| 127 |
"""
|
| 128 |
|
| 129 |
SUPPORTS_CONCURRENT_SESSIONS = True
|
| 130 |
|
| 131 |
def __init__(self) -> None:
|
| 132 |
+
# Per-environment rollout registry (one per HTTP session/worker).
|
| 133 |
+
self._registry = _RolloutRegistry()
|
| 134 |
+
|
| 135 |
# Import inside __init__ to keep module import cheap and to allow
|
| 136 |
# patching for tests. Dual-import pattern: package when installed,
|
| 137 |
# flat when run directly out of the repo via ``server.app:app``.
|
|
|
|
| 222 |
agent_timeout_s=agent_timeout_s,
|
| 223 |
)
|
| 224 |
|
| 225 |
+
# ββ Fine-grained tools (non-blocking) β Phase 2b ββββββββββββββββββββ
|
| 226 |
+
#
|
| 227 |
+
# These wrap the primitive's ``driver="serve"`` path so the UI and
|
| 228 |
+
# interactive clients can observe a rollout in flight. Training keeps
|
| 229 |
+
# using the blocking ``run_rollout`` tool above.
|
| 230 |
+
|
| 231 |
+
@mcp.tool
|
| 232 |
+
def start_rollout(
|
| 233 |
+
vllm_url: str,
|
| 234 |
+
model: str,
|
| 235 |
+
instruction: str,
|
| 236 |
+
test_script: str = "",
|
| 237 |
+
task_id: str = "",
|
| 238 |
+
setup_shell: str = "",
|
| 239 |
+
upload_files: Optional[dict[str, str]] = None,
|
| 240 |
+
provider: str = "openai_compatible",
|
| 241 |
+
api_key: str = "intercepted",
|
| 242 |
+
mode: str = "transparent_proxy",
|
| 243 |
+
disable_thinking: bool = False,
|
| 244 |
+
max_tokens_cap: int = 4096,
|
| 245 |
+
agent_timeout_s: float = 600.0,
|
| 246 |
+
) -> str:
|
| 247 |
+
"""Start a rollout asynchronously; return a ``rollout_id`` immediately.
|
| 248 |
+
|
| 249 |
+
Spawns a background worker that creates the sandbox, installs
|
| 250 |
+
opencode, boots ``opencode serve``, and fires the instruction.
|
| 251 |
+
The caller then uses ``subscribe_events`` / ``get_state`` /
|
| 252 |
+
``abort_rollout`` / ``finalize`` with the returned id.
|
| 253 |
+
"""
|
| 254 |
+
rid = uuid4().hex[:12]
|
| 255 |
+
handle = self._spawn_async_rollout(
|
| 256 |
+
rollout_id=rid,
|
| 257 |
+
vllm_url=vllm_url,
|
| 258 |
+
model=model,
|
| 259 |
+
instruction=instruction,
|
| 260 |
+
test_script=test_script,
|
| 261 |
+
task_id=task_id,
|
| 262 |
+
setup_shell=setup_shell,
|
| 263 |
+
upload_files=upload_files or {},
|
| 264 |
+
provider=provider,
|
| 265 |
+
api_key=api_key,
|
| 266 |
+
mode=mode,
|
| 267 |
+
disable_thinking=disable_thinking,
|
| 268 |
+
max_tokens_cap=max_tokens_cap,
|
| 269 |
+
agent_timeout_s=agent_timeout_s,
|
| 270 |
+
)
|
| 271 |
+
return json.dumps({
|
| 272 |
+
"rollout_id": handle.rollout_id,
|
| 273 |
+
"task_id": handle.task_id,
|
| 274 |
+
"status": "starting",
|
| 275 |
+
"started_at": handle.started_at,
|
| 276 |
+
})
|
| 277 |
+
|
| 278 |
+
@mcp.tool
|
| 279 |
+
def get_state(rollout_id: str) -> str:
|
| 280 |
+
"""Return a small JSON snapshot of the rollout's current state.
|
| 281 |
+
|
| 282 |
+
Useful for UI polling between SSE reconnects. The payload mirrors
|
| 283 |
+
what an ``agent_done`` event would carry plus a ``status`` field.
|
| 284 |
+
"""
|
| 285 |
+
handle = self._registry.get(rollout_id)
|
| 286 |
+
if handle is None:
|
| 287 |
+
return json.dumps({"rollout_id": rollout_id, "status": "unknown"})
|
| 288 |
+
session = handle.session
|
| 289 |
+
serve_session_id = getattr(session, "serve_session_id", None)
|
| 290 |
+
turns_n = 0
|
| 291 |
+
if session is not None and session._proxy_trace_path:
|
| 292 |
+
try:
|
| 293 |
+
content = session.sandbox.read_text(session._proxy_trace_path)
|
| 294 |
+
turns_n = sum(1 for line in content.splitlines() if line.strip())
|
| 295 |
+
except Exception:
|
| 296 |
+
pass
|
| 297 |
+
return json.dumps({
|
| 298 |
+
"rollout_id": rollout_id,
|
| 299 |
+
"task_id": handle.task_id,
|
| 300 |
+
"status": "done" if handle.is_done() else "running",
|
| 301 |
+
"serve_session_id": serve_session_id,
|
| 302 |
+
"proxy_turns_so_far": turns_n,
|
| 303 |
+
"error": handle.error,
|
| 304 |
+
"started_at": handle.started_at,
|
| 305 |
+
"finished_at": handle.finished_at,
|
| 306 |
+
})
|
| 307 |
+
|
| 308 |
+
@mcp.tool
|
| 309 |
+
def abort_rollout(rollout_id: str) -> str:
|
| 310 |
+
"""Cancel an in-flight rollout.
|
| 311 |
+
|
| 312 |
+
Calls ``POST /session/:id/abort`` on the sandbox's opencode serve
|
| 313 |
+
(which stops token generation immediately), then lets the worker
|
| 314 |
+
unwind and close the sandbox. Returns a small JSON payload.
|
| 315 |
+
"""
|
| 316 |
+
handle = self._registry.get(rollout_id)
|
| 317 |
+
if handle is None:
|
| 318 |
+
return json.dumps({"rollout_id": rollout_id, "aborted": False, "reason": "unknown"})
|
| 319 |
+
aborted = False
|
| 320 |
+
if handle.session is not None:
|
| 321 |
+
try:
|
| 322 |
+
aborted = bool(handle.session.abort())
|
| 323 |
+
except Exception as exc: # noqa: BLE001
|
| 324 |
+
return json.dumps({
|
| 325 |
+
"rollout_id": rollout_id, "aborted": False, "reason": str(exc),
|
| 326 |
+
})
|
| 327 |
+
return json.dumps({"rollout_id": rollout_id, "aborted": aborted})
|
| 328 |
+
|
| 329 |
+
@mcp.tool
|
| 330 |
+
def finalize_rollout(rollout_id: str, wait_s: float = 300.0) -> str:
|
| 331 |
+
"""Block until the rollout's worker finishes, then return its
|
| 332 |
+
full :class:`RolloutResult` as JSON (same shape as ``run_rollout``).
|
| 333 |
+
|
| 334 |
+
Must be called exactly once per rollout β this also de-registers
|
| 335 |
+
the handle and closes the sandbox.
|
| 336 |
+
"""
|
| 337 |
+
handle = self._registry.get(rollout_id)
|
| 338 |
+
if handle is None:
|
| 339 |
+
return json.dumps({
|
| 340 |
+
"task_id": "", "sandbox_id": "", "reward": None,
|
| 341 |
+
"exit_code": 0, "wall_s": 0.0, "mode": "",
|
| 342 |
+
"proxy_turns": [], "workdir_files": {},
|
| 343 |
+
"agent_log_tail": "", "verifier_stdout": "",
|
| 344 |
+
"verifier_stderr": "", "test_exit_code": None,
|
| 345 |
+
"error": f"unknown rollout_id: {rollout_id}",
|
| 346 |
+
"proxy_log_tail": "", "install_log_tail": "",
|
| 347 |
+
})
|
| 348 |
+
if not handle.wait(timeout=wait_s):
|
| 349 |
+
return json.dumps({
|
| 350 |
+
"task_id": handle.task_id, "sandbox_id": "",
|
| 351 |
+
"reward": None, "exit_code": -1, "wall_s": 0.0,
|
| 352 |
+
"mode": "", "proxy_turns": [], "workdir_files": {},
|
| 353 |
+
"agent_log_tail": "", "verifier_stdout": "",
|
| 354 |
+
"verifier_stderr": "", "test_exit_code": None,
|
| 355 |
+
"error": f"timeout waiting for rollout_id={rollout_id}",
|
| 356 |
+
"proxy_log_tail": "", "install_log_tail": "",
|
| 357 |
+
})
|
| 358 |
+
payload = self._finalize_handle(handle)
|
| 359 |
+
self._registry.drop(rollout_id)
|
| 360 |
+
return payload
|
| 361 |
+
|
| 362 |
super().__init__(mcp)
|
| 363 |
|
| 364 |
# ββ OpenEnv lifecycle ββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 605 |
return out
|
| 606 |
|
| 607 |
|
| 608 |
+
# ββ Async rollout plumbing βββββββββββββββββββββββββββββββββββββββββββββ
|
| 609 |
+
|
| 610 |
+
def _spawn_async_rollout(
|
| 611 |
+
self,
|
| 612 |
+
*,
|
| 613 |
+
rollout_id: str,
|
| 614 |
+
vllm_url: str,
|
| 615 |
+
model: str,
|
| 616 |
+
instruction: str,
|
| 617 |
+
test_script: str,
|
| 618 |
+
task_id: str,
|
| 619 |
+
setup_shell: str,
|
| 620 |
+
upload_files: dict[str, str],
|
| 621 |
+
provider: str,
|
| 622 |
+
api_key: str,
|
| 623 |
+
mode: str,
|
| 624 |
+
disable_thinking: bool,
|
| 625 |
+
max_tokens_cap: int,
|
| 626 |
+
agent_timeout_s: float,
|
| 627 |
+
) -> _RolloutHandle:
|
| 628 |
+
from opencode_env import OpenCodeTask
|
| 629 |
+
|
| 630 |
+
# Build the task payload up-front; staging happens on the worker.
|
| 631 |
+
merged_uploads = dict(upload_files)
|
| 632 |
+
if test_script:
|
| 633 |
+
merged_uploads[REMOTE_TEST_PATH] = test_script
|
| 634 |
+
task = OpenCodeTask(
|
| 635 |
+
instruction=instruction,
|
| 636 |
+
setup_shell=setup_shell or None,
|
| 637 |
+
upload_files=merged_uploads,
|
| 638 |
+
metadata={"task_id": task_id},
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
provider_model = _qualify_model(provider, model)
|
| 642 |
+
config = self._OpenCodeConfig(
|
| 643 |
+
provider=provider,
|
| 644 |
+
base_url=vllm_url.rstrip("/"),
|
| 645 |
+
api_key=api_key,
|
| 646 |
+
model=provider_model,
|
| 647 |
+
agent_timeout_s=agent_timeout_s,
|
| 648 |
+
proxy_disable_thinking=disable_thinking,
|
| 649 |
+
proxy_max_tokens_cap=max_tokens_cap if max_tokens_cap > 0 else None,
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
handle = _RolloutHandle(
|
| 653 |
+
rollout_id=rollout_id,
|
| 654 |
+
task_id=task_id,
|
| 655 |
+
session_factory_kwargs={
|
| 656 |
+
"config": config,
|
| 657 |
+
"mode": mode,
|
| 658 |
+
"agent_timeout_s": agent_timeout_s,
|
| 659 |
+
},
|
| 660 |
+
task=task,
|
| 661 |
+
)
|
| 662 |
+
handle._test_script = test_script
|
| 663 |
+
self._registry.add(handle)
|
| 664 |
+
|
| 665 |
+
def worker() -> None:
|
| 666 |
+
try:
|
| 667 |
+
factory = self._OpenCodeSessionFactory(
|
| 668 |
+
config=config,
|
| 669 |
+
sandbox_backend=self._E2BSandboxBackend(),
|
| 670 |
+
mode=mode,
|
| 671 |
+
verifier=None,
|
| 672 |
+
driver="serve", # Phase 2b path
|
| 673 |
+
)
|
| 674 |
+
handle.session = factory.create(task=task)
|
| 675 |
+
# Block until the agent idles. The caller can abort via
|
| 676 |
+
# ``abort_rollout`` any time; that triggers the serve
|
| 677 |
+
# ``/abort`` endpoint and ``wait_for_completion`` returns.
|
| 678 |
+
try:
|
| 679 |
+
handle.session.wait_for_completion(timeout_s=agent_timeout_s)
|
| 680 |
+
except Exception as exc: # noqa: BLE001
|
| 681 |
+
handle.error = f"wait_for_completion: {type(exc).__name__}: {exc}"
|
| 682 |
+
except Exception as exc: # noqa: BLE001
|
| 683 |
+
handle.error = f"{type(exc).__name__}: {exc}"
|
| 684 |
+
finally:
|
| 685 |
+
handle.finished_at = time.time()
|
| 686 |
+
handle._done.set()
|
| 687 |
+
|
| 688 |
+
t = threading.Thread(target=worker, daemon=True, name=f"rollout-{rollout_id}")
|
| 689 |
+
t.start()
|
| 690 |
+
handle._worker = t
|
| 691 |
+
return handle
|
| 692 |
+
|
| 693 |
+
def _finalize_handle(self, handle: _RolloutHandle) -> str:
|
| 694 |
+
"""Run the verifier (if test_script present), collect the trace, and
|
| 695 |
+
return a JSON-serialized :class:`RolloutResult` matching the shape
|
| 696 |
+
returned by ``run_rollout``. Closes the session + sandbox."""
|
| 697 |
+
result = self._result_cls(task_id=handle.task_id, mode=handle._kwargs.get("mode", ""))
|
| 698 |
+
session = handle.session
|
| 699 |
+
if session is None:
|
| 700 |
+
result.error = handle.error or "session never created"
|
| 701 |
+
return result.model_dump_json()
|
| 702 |
+
|
| 703 |
+
result.sandbox_id = session.sandbox.sandbox_id
|
| 704 |
+
result.exit_code = 0 # serve-driver has no exit code; use 0 unless aborted
|
| 705 |
+
wall_s = (handle.finished_at or time.time()) - handle.started_at
|
| 706 |
+
result.wall_s = round(wall_s, 3)
|
| 707 |
+
|
| 708 |
+
try:
|
| 709 |
+
if handle._test_script:
|
| 710 |
+
session.sandbox.exec(
|
| 711 |
+
"mkdir -p /home/user/logs/verifier /home/user/tests && "
|
| 712 |
+
f"chmod +x {REMOTE_TEST_PATH}",
|
| 713 |
+
timeout=15,
|
| 714 |
+
)
|
| 715 |
+
v = session.sandbox.exec(
|
| 716 |
+
f"bash {REMOTE_TEST_PATH}",
|
| 717 |
+
cwd=WORKDIR_PATH,
|
| 718 |
+
timeout=VERIFIER_TIMEOUT_S,
|
| 719 |
+
)
|
| 720 |
+
result.test_exit_code = int(v.exit_code)
|
| 721 |
+
result.verifier_stdout = (v.stdout or "")[:4000]
|
| 722 |
+
result.verifier_stderr = (v.stderr or "")[:2000]
|
| 723 |
+
result.reward = _read_reward(session.sandbox, REMOTE_REWARD_PATH)
|
| 724 |
+
|
| 725 |
+
summary = self._collect_rollout_summary(session)
|
| 726 |
+
result.agent_log_tail = _tail(summary.opencode_events, 20)
|
| 727 |
+
result.workdir_files = {
|
| 728 |
+
path: (contents or "")[:8000]
|
| 729 |
+
for path, contents in (summary.workdir_contents or {}).items()
|
| 730 |
+
}
|
| 731 |
+
for raw in summary.proxy_turns:
|
| 732 |
+
result.proxy_turns.append(self._turn_cls(**_clamp_turn(raw)))
|
| 733 |
+
result.proxy_log_tail = _read_safe(
|
| 734 |
+
session.sandbox, "/home/user/logs/agent/proxy.log", tail_chars=4000
|
| 735 |
+
)
|
| 736 |
+
except Exception as exc: # noqa: BLE001
|
| 737 |
+
if not handle.error:
|
| 738 |
+
result.error = f"finalize: {type(exc).__name__}: {exc}"
|
| 739 |
+
else:
|
| 740 |
+
result.error = handle.error
|
| 741 |
+
finally:
|
| 742 |
+
try:
|
| 743 |
+
session.close()
|
| 744 |
+
except Exception:
|
| 745 |
+
pass
|
| 746 |
+
|
| 747 |
+
if handle.error and not result.error:
|
| 748 |
+
result.error = handle.error
|
| 749 |
+
return result.model_dump_json()
|
| 750 |
+
|
| 751 |
+
|
| 752 |
def _tail(events: list[dict[str, Any]], n: int) -> str:
|
| 753 |
"""Return the last ``n`` opencode event lines as a newline-joined string."""
|
| 754 |
if not events:
|
uv.lock
CHANGED
|
@@ -1710,7 +1710,7 @@ dev = [
|
|
| 1710 |
[[package]]
|
| 1711 |
name = "openenv-core"
|
| 1712 |
version = "0.2.3"
|
| 1713 |
-
source = { git = "https://github.com/adithya-s-k/OpenEnv.git?rev=opencode-harness#
|
| 1714 |
dependencies = [
|
| 1715 |
{ name = "fastapi" },
|
| 1716 |
{ name = "fastmcp" },
|
|
@@ -1741,7 +1741,7 @@ core = [
|
|
| 1741 |
[[package]]
|
| 1742 |
name = "openenv-opencode-env"
|
| 1743 |
version = "0.1.0"
|
| 1744 |
-
source = { git = "https://github.com/adithya-s-k/OpenEnv.git?subdirectory=envs%2Fopencode_env&rev=opencode-harness#
|
| 1745 |
dependencies = [
|
| 1746 |
{ name = "e2b" },
|
| 1747 |
{ name = "fastapi" },
|
|
|
|
| 1710 |
[[package]]
|
| 1711 |
name = "openenv-core"
|
| 1712 |
version = "0.2.3"
|
| 1713 |
+
source = { git = "https://github.com/adithya-s-k/OpenEnv.git?rev=opencode-harness#5d760274516f8c917212506240983e781b467c1d" }
|
| 1714 |
dependencies = [
|
| 1715 |
{ name = "fastapi" },
|
| 1716 |
{ name = "fastmcp" },
|
|
|
|
| 1741 |
[[package]]
|
| 1742 |
name = "openenv-opencode-env"
|
| 1743 |
version = "0.1.0"
|
| 1744 |
+
source = { git = "https://github.com/adithya-s-k/OpenEnv.git?subdirectory=envs%2Fopencode_env&rev=opencode-harness#5d760274516f8c917212506240983e781b467c1d" }
|
| 1745 |
dependencies = [
|
| 1746 |
{ name = "e2b" },
|
| 1747 |
{ name = "fastapi" },
|