saadpie commited on
Commit
dd216e6
·
verified ·
1 Parent(s): c04f0c5

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +61 -45
server.py CHANGED
@@ -1,98 +1,114 @@
1
  import os
2
  import subprocess
 
 
3
  from fastapi import FastAPI, BackgroundTasks, HTTPException
4
- from fastapi.responses import FileResponse
5
  from pydantic import BaseModel
6
 
7
- app = FastAPI(title="Ash CLI Portal - Headless Multi-Agent Matrix")
 
 
 
 
8
 
9
  class AgentTask(BaseModel):
10
  session_id: str
11
  task: str
12
 
13
- # In-memory tracking for task states
14
  task_registry = {}
15
 
16
  def execute_isolated_hermes(session_id: str, task: str):
17
  task_registry[session_id] = "running"
18
- session_workspace = f"/workspace/sessions/{session_id}"
19
- os.makedirs(session_workspace, exist_ok=True)
20
 
21
- # Define paths to store execution logs inside the user's isolated folder
22
- log_file_path = os.path.join(session_workspace, "agent_execution.log")
23
 
24
- # CRITICAL FIX: Pass environment variables to the subprocess
25
- # This ensures Hermes knows where to find its config and credentials
26
  worker_env = os.environ.copy()
27
- worker_env["HOME"] = "/root"
28
- worker_env["HERMES_HOME"] = "/root/.hermes"
 
 
 
29
 
30
- print(f"[Core] Spawning autonomous pipeline for Session: {session_id}")
31
 
32
  try:
33
- # Opening a physical log file to catch the agent's real-time thoughts and skill builds
34
- with open(log_file_path, "w") as log_file:
35
  process = subprocess.Popen(
36
  ["hermes", "chat", "-q", task, "--resume", session_id, "--yolo"],
37
- cwd=session_workspace,
38
  stdout=log_file,
39
- stderr=log_file,
40
- env=worker_env, # Injects the config path
41
- text=True
 
42
  )
43
- process.wait() # Let the agent finish its execution chain safely
44
-
45
- if process.returncode == 0:
46
  task_registry[session_id] = "completed"
47
- print(f"[Core] Session {session_id} successfully finished task chain.")
48
  else:
49
- task_registry[session_id] = "failed"
50
- print(f"[Core Error] Session {session_id} crashed or halted.")
51
 
 
 
 
 
 
52
  except Exception as e:
53
  task_registry[session_id] = f"error: {str(e)}"
54
- print(f"[System Exception] Critical worker thread failure for {session_id}: {str(e)}")
55
 
56
  @app.post("/agent/execute")
57
  async def trigger_autonomous_agent(payload: AgentTask, background_tasks: BackgroundTasks):
58
  if not payload.session_id or not payload.task:
59
- raise HTTPException(status_code=400, detail="Missing required parameters.")
60
 
61
  background_tasks.add_task(execute_isolated_hermes, payload.session_id, payload.task)
62
  return {
63
- "status": "processing",
64
  "session_id": payload.session_id,
65
- "message": "Task queued. Background runner instance is up, pooling your 100 Gemini keys."
66
  }
67
 
68
- # Route to check if the agent is still running or finished
69
  @app.get("/agent/status/{session_id}")
70
  def get_agent_status(session_id: str):
71
- status = task_registry.get(session_id, "unknown/idle")
72
- session_workspace = f"/workspace/sessions/{session_id}"
73
- log_path = os.path.join(session_workspace, "agent_execution.log")
74
 
75
  recent_logs = ""
76
- if os.path.exists(log_path):
77
  with open(log_path, "r") as f:
78
- # Grab the last 30 lines of execution steps so you can see what tool it's using
79
  lines = f.readlines()
80
- recent_logs = "".join(lines[-30:])
81
-
82
- return {
83
  "session_id": session_id,
84
  "status": status,
85
- "recent_activity": recent_logs
86
- }
87
 
88
- # Route to download any file (videos, txt, code) created by the agent
89
  @app.get("/agent/files/{session_id}/{filename}")
90
  def get_agent_file(session_id: str, filename: str):
91
- file_path = f"/workspace/sessions/{session_id}/{filename}"
92
- if not os.path.exists(file_path):
93
- raise HTTPException(status_code=404, detail="Requested file not found in agent workspace state.")
94
- return FileResponse(file_path)
 
 
 
 
95
 
96
  @app.get("/health")
97
  def system_check():
98
- return {"engine": "Hermes Agent Framework v0.14.0", "status": "operational"}
 
 
 
 
 
 
 
 
 
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="Ash CLI Portal - Hermes Serverless")
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
  task_registry = {}
20
 
21
  def execute_isolated_hermes(session_id: str, task: str):
22
  task_registry[session_id] = "running"
23
+ session_workspace = Path(SESSIONS_DIR) / session_id
24
+ session_workspace.mkdir(parents=True, exist_ok=True)
25
 
26
+ log_file_path = session_workspace / "agent_execution.log"
 
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(log_file_path, "a") as log_file:
39
+ log_file.write(f"\n=== Task: {task} ===\n")
40
  process = subprocess.Popen(
41
  ["hermes", "chat", "-q", task, "--resume", session_id, "--yolo"],
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: {str(e)}"
62
+ print(f"[Error] Session {session_id}: {e}")
63
 
64
  @app.post("/agent/execute")
65
  async def trigger_autonomous_agent(payload: AgentTask, background_tasks: BackgroundTasks):
66
  if not payload.session_id or not payload.task:
67
+ raise HTTPException(status_code=400, detail="Missing session_id or task")
68
 
69
  background_tasks.add_task(execute_isolated_hermes, payload.session_id, payload.task)
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 get_agent_status(session_id: str):
78
+ status = task_registry.get(session_id, "unknown")
79
+ log_path = Path(SESSIONS_DIR) / session_id / "agent_execution.log"
 
80
 
81
  recent_logs = ""
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 get_agent_file(session_id: str, filename: str):
95
+ # Prevent path traversal
96
+ if "/" in filename or ".." in filename:
97
+ raise HTTPException(status_code=400, detail="Invalid filename")
98
+
99
+ file_path = Path(SESSIONS_DIR) / session_id / filename if not file_path.exists():
100
+ raise HTTPException(status_code=404, detail="File not found")
101
+
102
+ return FileResponse(str(file_path))
103
 
104
  @app.get("/health")
105
  def system_check():
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": "Ash CLI Portal API", "docs": "/docs"}