Spaces:
Paused
Paused
Update server.py
Browse files
server.py
CHANGED
|
@@ -1,114 +1,60 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import subprocess
|
| 3 |
-
import json
|
| 4 |
from pathlib import Path
|
| 5 |
from fastapi import FastAPI, BackgroundTasks, HTTPException
|
| 6 |
from fastapi.responses import FileResponse, JSONResponse
|
| 7 |
from pydantic import BaseModel
|
| 8 |
|
| 9 |
-
app = FastAPI(title="
|
| 10 |
-
|
| 11 |
-
# Use /data for persistent storage on HF Spaces
|
| 12 |
SESSIONS_DIR = os.environ.get("SESSIONS_DIR", "/data/sessions")
|
| 13 |
Path(SESSIONS_DIR).mkdir(parents=True, exist_ok=True)
|
|
|
|
| 14 |
|
| 15 |
class AgentTask(BaseModel):
|
| 16 |
session_id: str
|
| 17 |
task: str
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def execute_isolated_hermes(session_id: str, task: str):
|
| 22 |
task_registry[session_id] = "running"
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
worker_env = os.environ.copy()
|
| 29 |
-
worker_env.update({
|
| 30 |
-
"HOME": "/root",
|
| 31 |
-
"HERMES_HOME": "/root/.hermes",
|
| 32 |
-
"PATH": f"/root/.local/bin:{os.environ.get('PATH', '')}"
|
| 33 |
-
})
|
| 34 |
-
|
| 35 |
-
print(f"[Core] Starting session: {session_id}")
|
| 36 |
-
|
| 37 |
try:
|
| 38 |
-
with open(
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
cwd=str(session_workspace),
|
| 43 |
-
stdout=log_file,
|
| 44 |
-
stderr=subprocess.STDOUT,
|
| 45 |
-
env=worker_env,
|
| 46 |
-
text=True,
|
| 47 |
-
bufsize=1
|
| 48 |
-
)
|
| 49 |
-
returncode = process.wait(timeout=1800) # 30 min timeout
|
| 50 |
-
if returncode == 0:
|
| 51 |
-
task_registry[session_id] = "completed"
|
| 52 |
-
else:
|
| 53 |
-
task_registry[session_id] = f"failed (code: {returncode})"
|
| 54 |
-
|
| 55 |
-
except subprocess.TimeoutExpired:
|
| 56 |
-
process.kill()
|
| 57 |
-
task_registry[session_id] = "timeout"
|
| 58 |
-
except FileNotFoundError:
|
| 59 |
-
task_registry[session_id] = "error: hermes not installed"
|
| 60 |
except Exception as e:
|
| 61 |
-
task_registry[session_id] = f"error:
|
| 62 |
-
print(f"[Error] Session {session_id}: {e}")
|
| 63 |
|
| 64 |
@app.post("/agent/execute")
|
| 65 |
-
async def
|
| 66 |
if not payload.session_id or not payload.task:
|
| 67 |
-
raise HTTPException(
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
return {
|
| 71 |
-
"status": "queued",
|
| 72 |
-
"session_id": payload.session_id,
|
| 73 |
-
"message": "Task accepted. Agent will begin execution shortly."
|
| 74 |
-
}
|
| 75 |
|
| 76 |
@app.get("/agent/status/{session_id}")
|
| 77 |
-
def
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
if log_path.exists():
|
| 83 |
-
with open(log_path, "r") as f:
|
| 84 |
-
lines = f.readlines()
|
| 85 |
-
recent_logs = "".join(lines[-50:]) # Last 50 lines
|
| 86 |
-
|
| 87 |
-
return JSONResponse(content={
|
| 88 |
-
"session_id": session_id,
|
| 89 |
-
"status": status,
|
| 90 |
-
"recent_activity": recent_logs[-2000:] if len(recent_logs) > 2000 else recent_logs
|
| 91 |
-
})
|
| 92 |
|
| 93 |
@app.get("/agent/files/{session_id}/{filename}")
|
| 94 |
-
def
|
| 95 |
-
# Prevent path traversal
|
| 96 |
if "/" in filename or ".." in filename:
|
| 97 |
-
raise HTTPException(
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
raise HTTPException(
|
| 101 |
-
|
| 102 |
-
return FileResponse(str(file_path))
|
| 103 |
|
| 104 |
@app.get("/health")
|
| 105 |
-
def
|
| 106 |
-
return {
|
| 107 |
-
"engine": "Hermes Serverless v0.14.0",
|
| 108 |
-
"status": "operational",
|
| 109 |
-
"sessions_dir": str(SESSIONS_DIR)
|
| 110 |
-
}
|
| 111 |
|
| 112 |
@app.get("/")
|
| 113 |
def root():
|
| 114 |
-
return {"message": "
|
|
|
|
| 1 |
+
import os, subprocess, json
|
|
|
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
from fastapi import FastAPI, BackgroundTasks, HTTPException
|
| 4 |
from fastapi.responses import FileResponse, JSONResponse
|
| 5 |
from pydantic import BaseModel
|
| 6 |
|
| 7 |
+
app = FastAPI(title="Hermes Serverless")
|
|
|
|
|
|
|
| 8 |
SESSIONS_DIR = os.environ.get("SESSIONS_DIR", "/data/sessions")
|
| 9 |
Path(SESSIONS_DIR).mkdir(parents=True, exist_ok=True)
|
| 10 |
+
task_registry = {}
|
| 11 |
|
| 12 |
class AgentTask(BaseModel):
|
| 13 |
session_id: str
|
| 14 |
task: str
|
| 15 |
|
| 16 |
+
def execute_hermes(session_id: str, task: str):
|
|
|
|
|
|
|
| 17 |
task_registry[session_id] = "running"
|
| 18 |
+
workspace = Path(SESSIONS_DIR) / session_id
|
| 19 |
+
workspace.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
log_path = workspace / "output.log"
|
| 21 |
+
env = os.environ.copy()
|
| 22 |
+
env.update({"HOME": "/root", "HERMES_HOME": "/root/.hermes"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
+
with open(log_path, "a") as f:
|
| 25 |
+
p = subprocess.Popen(["hermes", "chat", "-q", task, "--resume", session_id, "--yolo"], cwd=str(workspace), stdout=f, stderr=subprocess.STDOUT, env=env, text=True)
|
| 26 |
+
rc = p.wait(timeout=1800)
|
| 27 |
+
task_registry[session_id] = "completed" if rc == 0 else f"failed:{rc}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
except Exception as e:
|
| 29 |
+
task_registry[session_id] = f"error:{str(e)}"
|
|
|
|
| 30 |
|
| 31 |
@app.post("/agent/execute")
|
| 32 |
+
async def run(payload: AgentTask, bg: BackgroundTasks):
|
| 33 |
if not payload.session_id or not payload.task:
|
| 34 |
+
raise HTTPException(400, "Missing session_id or task")
|
| 35 |
+
bg.add_task(execute_hermes, payload.session_id, payload.task)
|
| 36 |
+
return {"status": "queued", "session_id": payload.session_id}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
@app.get("/agent/status/{session_id}")
|
| 39 |
+
def status(session_id: str):
|
| 40 |
+
st = task_registry.get(session_id, "unknown")
|
| 41 |
+
log = Path(SESSIONS_DIR) / session_id / "output.log"
|
| 42 |
+
logs = log.read_text()[-2000:] if log.exists() else ""
|
| 43 |
+
return {"session_id": session_id, "status": st, "logs": logs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
@app.get("/agent/files/{session_id}/{filename}")
|
| 46 |
+
def file(session_id: str, filename: str):
|
|
|
|
| 47 |
if "/" in filename or ".." in filename:
|
| 48 |
+
raise HTTPException(400, "Invalid filename")
|
| 49 |
+
path = Path(SESSIONS_DIR) / session_id / filename
|
| 50 |
+
if not path.exists():
|
| 51 |
+
raise HTTPException(404, "File not found")
|
| 52 |
+
return FileResponse(str(path))
|
|
|
|
| 53 |
|
| 54 |
@app.get("/health")
|
| 55 |
+
def health():
|
| 56 |
+
return {"status": "ok", "engine": "hermes-serverless"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
@app.get("/")
|
| 59 |
def root():
|
| 60 |
+
return {"message": "Hermes Serverless API", "docs": "/docs"}
|