Spaces:
Configuration error
Configuration error
File size: 18,169 Bytes
18535e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | """
FastAPI server exposing the full Super Agent OS over HTTP.
Provides endpoints for: scans, tasks, models, connectors, usage, browser, revenue, scheduler, memory, system health.
"""
import asyncio
import json
import logging
import os
import time
from typing import Optional
from fastapi import FastAPI, BackgroundTasks, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, FileResponse
from pydantic import BaseModel
# Agent modules
from router import get_provider_status, test_provider, get_connector_status
from tasks import (
create_task, get_task, list_tasks, update_task_state,
update_task_plan, add_task_log, add_tool_call, add_artifact, get_timeline, get_task_artifacts
)
from usage import get_usage, record_llm_call, record_browser_action, record_external_api_call, record_task_created
from agents.commander import plan_task, AGENT_REGISTRY
from agents.browser import screenshot, navigate, extract_page_text
from agents.revenue import discover_opportunities
from agents.verifier import verify_task_completion
from agents.security import check_input_safety, check_approval_gate
from agents.memory import set_preference, get_preference, get_history, record_outcome
from agents.scheduler import schedule_task, list_scheduled, run_due_tasks, cancel_scheduled
from agents.document import list_outputs, generate_markdown_report
logger = logging.getLogger("super-agent-os.api")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
app = FastAPI(
title="Super Agent OS",
description="Autonomous multi-agent AI operating system with model routing, task engine, browser automation, revenue discovery, and on-chain payouts",
version="2.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Background scan state ---
_active_scans: dict = {}
_scan_results: dict = {}
# === Pydantic Models ===
class ScanRequest(BaseModel):
target: str
settlement_contract: Optional[str] = ""
attacker_token: Optional[str] = ""
victim_token: Optional[str] = ""
class ScopeUpdate(BaseModel):
in_scope: list[str]
out_of_scope: list[str]
program_name: Optional[str] = "My Program"
platform: Optional[str] = "bugcrowd"
class TaskCreate(BaseModel):
goal: str
class TaskAction(BaseModel):
action: str # run, cancel, approve
metadata: Optional[dict] = {}
class ModelSelect(BaseModel):
provider: str
class BrowserAction(BaseModel):
url: str
action: str = "screenshot" # screenshot, navigate, extract
full_page: bool = False
class RevenueQuery(BaseModel):
query: str = ""
max_results: int = 10
class ScheduleRequest(BaseModel):
name: str
interval_hours: int
goal: str
max_runs: int = 10
class MemorySet(BaseModel):
key: str
value: str
class SecurityCheck(BaseModel):
text: str
action_type: str = ""
class ApprovalCheck(BaseModel):
action_type: str
metadata: Optional[dict] = {}
class DocumentReport(BaseModel):
title: str
sections: list[dict]
# === Health & System ===
@app.post("/api/system/activity")
async def system_activity():
activity_path = os.environ.get("USER_ACTIVITY_FILE", "/app/runtime/user_activity.last")
os.makedirs(os.path.dirname(activity_path), exist_ok=True)
with open(activity_path, "w") as f:
f.write(str(time.time()))
return {"ok": True, "updated_at": time.time()}
@app.get("/api/system/health")
async def health():
from config import CEREBRAS_API_KEY, COINBASE_API_KEY_NAME, WALLET_PRIVATE_KEY
return {
"status": "ok",
"service": "super-agent-os",
"version": "2.0.0",
"timestamp": time.time(),
"llm_configured": bool(CEREBRAS_API_KEY or os.environ.get("GROQ_API_KEY") or os.environ.get("OPENROUTER_API_KEY")),
"coinbase_configured": bool(COINBASE_API_KEY_NAME),
"wallet_configured": bool(WALLET_PRIVATE_KEY),
}
# === Model Router ===
@app.get("/api/models")
async def models():
status = get_provider_status()
return status
@app.get("/api/models/active")
async def active_model():
status = get_provider_status()
return {
"primary_provider": status.get("primary_provider"),
"primary_model": status.get("primary_model"),
"fallback_provider": status.get("fallback_provider"),
"fallback_model": status.get("fallback_model"),
}
@app.post("/api/models/test")
async def test_model(req: ModelSelect):
result = await test_provider(req.provider)
return result
@app.post("/api/models/select")
async def select_model(req: ModelSelect):
# Persist user selection to memory
set_preference("selected_primary", req.provider)
return {"provider": req.provider, "persisted": True}
@app.get("/api/providers/status")
async def providers_status():
return get_provider_status()
# === Connectors ===
@app.get("/api/connectors")
async def connectors():
return {"connectors": get_connector_status()}
@app.post("/api/connectors/test")
async def test_connector(req: ModelSelect):
# Test a connector by name
all_connectors = get_connector_status()
conn = next((c for c in all_connectors if c["name"] == req.provider), None)
if not conn:
return {"success": False, "error": "Connector not found"}
if not conn["configured"]:
return {"success": False, "error": "Connector not configured", "key_env": conn["key_env"]}
# For LLM connectors, run a model test
if conn["name"] in ["cerebras", "groq", "openai", "openrouter", "gemini", "anthropic", "together", "fireworks", "ollama", "hf"]:
result = await test_provider(conn["name"])
return {"success": result.get("success", False), "details": result}
return {"success": True, "connector": conn["name"], "message": "Configured"}
# === Tasks ===
@app.post("/api/tasks")
async def create_task_endpoint(req: TaskCreate):
record_task_created()
task = create_task(req.goal)
# Auto-plan
plan = plan_task(req.goal)
update_task_plan(task.id, plan["plan"], plan["agents"])
return {"task": {"id": task.id, "goal": task.goal, "state": task.state, "plan": plan["plan"], "agents": plan["agents"], "tags": task.tags, "bounty_id": task.bounty_id, "platform": task.platform, "program_handle": task.program_handle, "created_at": task.created_at}}
@app.get("/api/tasks")
async def list_tasks_endpoint(limit: int = 50):
tasks = list_tasks(limit)
return {"tasks": [{"id": t.id, "goal": t.goal, "state": t.state, "created_at": t.created_at,
"tags": t.tags, "bounty_id": t.bounty_id, "platform": t.platform, "program_handle": t.program_handle,
"confidence": t.confidence, "requires_approval": t.requires_approval} for t in tasks],
"total": len(tasks)}
@app.get("/api/tasks/{task_id}")
async def get_task_endpoint(task_id: str):
task = get_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return {
"id": task.id, "goal": task.goal, "state": task.state,
"plan": task.plan, "agents": task.agent_assignments,
"tags": task.tags, "bounty_id": task.bounty_id, "platform": task.platform, "program_handle": task.program_handle,
"result": task.result, "error": task.error,
"confidence": task.confidence, "requires_approval": task.requires_approval,
"created_at": task.created_at, "started_at": task.started_at, "completed_at": task.completed_at,
"tool_calls": len(task.tool_calls), "artifacts": len(task.artifacts),
}
@app.post("/api/tasks/{task_id}/run")
async def run_task(task_id: str, background_tasks: BackgroundTasks = None):
task = get_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
if task.state in ("running", "tool_executing"):
return {"status": "already_running", "task_id": task_id}
update_task_state(task_id, "planned")
update_task_state(task_id, "running")
add_task_log(task_id, "orchestrator", "", "Background execution started")
# Fire actual execution in background using FastAPI BackgroundTasks
from orchestrator import run_task_async
if background_tasks:
background_tasks.add_task(run_task_async, task_id, task.goal)
else:
asyncio.create_task(run_task_async(task_id, task.goal))
return {"status": "running", "task_id": task_id, "message": "Task is executing in the background. Check /api/tasks/{id}/timeline for progress."}
@app.post("/api/tasks/{task_id}/cancel")
async def cancel_task(task_id: str):
task = get_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
update_task_state(task_id, "cancelled")
return {"status": "cancelled", "task_id": task_id}
@app.get("/api/tasks/{task_id}/timeline")
async def task_timeline(task_id: str):
task = get_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return {"timeline": get_timeline(task_id)}
@app.get("/api/tasks/{task_id}/artifacts")
async def task_artifacts(task_id: str):
task = get_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return {"artifacts": get_task_artifacts(task_id)}
# === Logs Stream (SSE) ===
@app.get("/api/logs/stream")
async def logs_stream():
async def event_generator():
while True:
yield f"data: {{'timestamp': {time.time()}, 'message': 'heartbeat'}}\n\n"
await asyncio.sleep(5)
return StreamingResponse(event_generator(), media_type="text/event-stream")
# === Usage & Guardrails ===
@app.get("/api/usage")
async def usage():
return get_usage()
# === Browser ===
@app.post("/api/browser/screenshot")
async def browser_screenshot(req: BrowserAction):
record_browser_action()
if req.action == "screenshot":
result = await screenshot(req.url, req.full_page)
elif req.action == "navigate":
result = await navigate(req.url)
elif req.action == "extract":
result = await extract_page_text(req.url)
else:
raise HTTPException(status_code=400, detail="Unknown action")
return result
# === Revenue ===
@app.post("/api/revenue/discover")
async def revenue_discover(req: RevenueQuery):
opps = discover_opportunities(req.query, req.max_results)
return {"opportunities": opps, "total": len(opps)}
@app.get("/api/revenue/opportunities")
async def revenue_opportunities(query: str = "", max_results: int = 10):
opps = discover_opportunities(query, max_results)
return {"opportunities": opps, "total": len(opps)}
# === Scheduler ===
@app.post("/api/scheduler/schedule")
async def scheduler_schedule(req: ScheduleRequest):
task = schedule_task(req.name, req.interval_hours, req.goal, req.max_runs)
return {"scheduled": task}
@app.get("/api/scheduler")
async def scheduler_list():
return {"tasks": list_scheduled()}
@app.post("/api/scheduler/run-due")
async def scheduler_run():
results = run_due_tasks()
return {"ran": results}
@app.post("/api/scheduler/{task_id}/cancel")
async def scheduler_cancel(task_id: str):
ok = cancel_scheduled(task_id)
return {"cancelled": ok}
# === Memory ===
@app.post("/api/memory/preference")
async def memory_set(req: MemorySet):
set_preference(req.key, req.value)
return {"key": req.key, "value": req.value}
@app.get("/api/memory/preference/{key}")
async def memory_get(key: str):
val = get_preference(key)
return {"key": key, "value": val}
@app.get("/api/memory/history")
async def memory_history(limit: int = 50):
return {"history": get_history(limit)}
# === Security ===
@app.post("/api/security/check")
async def security_check(req: SecurityCheck):
return check_input_safety(req.text, req.action_type)
@app.post("/api/security/approval")
async def security_approval(req: ApprovalCheck):
return check_approval_gate(req.action_type, req.metadata)
# === Verifier ===
@app.post("/api/verifier/{task_id}")
async def verify_task(task_id: str):
task = get_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
result = verify_task_completion(task_id, task.goal, task.artifacts, task.tool_calls)
return result
# === Documents/Artifacts ===
@app.get("/api/artifacts")
async def list_artifacts():
return {"artifacts": list_outputs()}
@app.post("/api/artifacts/report")
async def create_report(req: DocumentReport):
path = generate_markdown_report(req.title, req.sections)
return {"path": path, "name": os.path.basename(path)}
@app.get("/api/artifacts/{artifact_name}/download")
async def download_artifact(artifact_name: str):
from agents.document import OUTPUT_DIR
if ".." in artifact_name or "/" in artifact_name:
raise HTTPException(status_code=400, detail="Invalid artifact name")
path = os.path.join(OUTPUT_DIR, artifact_name)
if not os.path.exists(path):
raise HTTPException(status_code=404, detail="Artifact not found")
return FileResponse(path, filename=artifact_name)
# === Legacy Bounty Endpoints (backward compat) ===
@app.get("/health")
async def legacy_health():
return await health()
@app.get("/status")
async def legacy_status():
from config import CEREBRAS_API_KEY, COINBASE_API_KEY_NAME, WALLET_PRIVATE_KEY
return {
"cerebras_configured": bool(CEREBRAS_API_KEY),
"coinbase_configured": bool(COINBASE_API_KEY_NAME),
"wallet_configured": bool(WALLET_PRIVATE_KEY),
"active_scans": len(_active_scans),
"completed_scans": len(_scan_results),
}
@app.post("/scan/start")
async def legacy_start_scan(req: ScanRequest, background_tasks: BackgroundTasks):
scan_id = f"scan-{int(time.time())}"
_active_scans[scan_id] = {
"id": scan_id, "target": req.target, "status": "running",
"started_at": time.time(), "progress": [],
}
async def run():
try:
from graph import run_dual_cluster
result = await run_dual_cluster(
target=req.target,
settlement_contract=req.settlement_contract or "",
attacker_token=req.attacker_token or "",
victim_token=req.victim_token or "",
)
_scan_results[scan_id] = result
_active_scans[scan_id]["status"] = "completed"
_active_scans[scan_id]["completed_at"] = time.time()
except Exception as e:
_active_scans[scan_id]["status"] = "error"
_active_scans[scan_id]["error"] = str(e)
background_tasks.add_task(run)
return {"scan_id": scan_id, "status": "started", "target": req.target}
@app.get("/scan/{scan_id}/status")
async def legacy_scan_status(scan_id: str):
if scan_id not in _active_scans:
raise HTTPException(status_code=404, detail="Scan not found")
return _active_scans[scan_id]
@app.get("/scans")
async def legacy_list_scans():
return {"scans": list(_active_scans.values()), "total": len(_active_scans)}
@app.get("/reports")
async def legacy_reports():
from config import REPORTS_DIR
reports = []
try:
for fname in sorted(os.listdir(REPORTS_DIR), reverse=True):
if fname.endswith(".md"):
fpath = os.path.join(REPORTS_DIR, fname)
reports.append({"filename": fname, "size_bytes": os.path.getsize(fpath), "created_at": os.path.getctime(fpath)})
except Exception:
pass
return {"reports": reports, "total": len(reports)}
@app.get("/reports/{filename}")
async def legacy_get_report(filename: str):
from config import REPORTS_DIR
if ".." in filename or "/" in filename:
raise HTTPException(status_code=400, detail="Invalid filename")
fpath = os.path.join(REPORTS_DIR, filename)
if not os.path.exists(fpath):
raise HTTPException(status_code=404, detail="Report not found")
with open(fpath) as f:
return {"filename": filename, "content": f.read()}
@app.get("/scope")
async def legacy_get_scope():
from config import SCOPE_FILE
try:
with open(SCOPE_FILE) as f:
return json.load(f)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/scope")
async def legacy_update_scope(scope: ScopeUpdate):
from config import SCOPE_FILE
try:
with open(SCOPE_FILE) as f:
existing = json.load(f)
except Exception:
existing = {}
updated = {**existing, "program_name": scope.program_name, "platform": scope.platform,
"in_scope": scope.in_scope, "out_of_scope": scope.out_of_scope}
with open(SCOPE_FILE, "w") as f:
json.dump(updated, f, indent=2)
return {"status": "updated", "scope": updated}
@app.get("/gas/estimate")
async def legacy_gas(contract: str = "0x0000000000000000000000000000000000000000"):
from blockchain import payout_engine
from config import GAS_MIN_USD, GAS_MAX_USD
gas_usd, gas_gwei, gas_units = payout_engine.estimate_gas_cost_usd(contract)
confirmed_cost = gas_usd < 999
in_window = confirmed_cost and gas_usd <= GAS_MAX_USD
return {
"gas_usd": round(gas_usd, 6), "gas_gwei": round(gas_gwei, 4), "gas_units": gas_units,
"gas_min_usd": 0.0, "gas_soft_usd": GAS_MIN_USD, "gas_max_usd": GAS_MAX_USD,
"within_ceiling": in_window,
"verdict": "SAFE" if in_window else "BLOCKED",
"rule": "Cheaper confirmed gas is allowed; unknown gas or gas above hard ceiling is blocked.",
}
from v2_transition import register_v2_routes
register_v2_routes(app)
# Sync secrets from Doppler on startup (if token available)
from secrets_loader import sync_from_doppler
sync_from_doppler()
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 8000))
uvicorn.run("api_server:app", host="0.0.0.0", port=port, reload=False)
|