""" 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)