""" Workflow Engine — Define, schedule, and execute multi-step agent workflows. Reusable templates for bounty, revenue, research, airdrop pipelines. """ import os import json import time import uuid import asyncio import logging from typing import Dict, Any, List, Optional from dataclasses import dataclass, asdict, field from enum import Enum from pathlib import Path from pydantic import BaseModel, Field logger = logging.getLogger("super-agent-os.workflows") STATE_DIR = Path(os.environ.get("V2_STATE_DIR", "/app/runtime")) WORKFLOWS_DIR = STATE_DIR / "workflows" WORKFLOWS_DIR.mkdir(parents=True, exist_ok=True) WORKFLOWS_FILE = WORKFLOWS_DIR / "workflows.json" RUNS_FILE = WORKFLOWS_DIR / "runs.json" class WorkflowStatus(str, Enum): DRAFT = "draft" ACTIVE = "active" PAUSED = "paused" ARCHIVED = "archived" class RunStatus(str, Enum): PENDING = "pending" RUNNING = "running" COMPLETED = "completed" FAILED = "failed" CANCELLED = "cancelled" WAITING_APPROVAL = "waiting_approval" # --- Default workflow templates --- DEFAULT_WORKFLOWS = [ { "id": "wf-bounty-scan", "name": "Bug Bounty Scan & Report", "description": "Full bounty workflow: discover → scope → map → authorized test → evidence → report → QA → approval", "category": "bounty", "steps": [ {"id": "s1", "name": "Discover Programs", "agent": "bounty", "action": "discover", "approval_required": False}, {"id": "s2", "name": "Verify Scope", "agent": "security", "action": "verify_scope", "approval_required": False}, {"id": "s3", "name": "Map Attack Surface", "agent": "browser", "action": "crawl", "approval_required": False}, {"id": "s4", "name": "Run Authorized Tests", "agent": "bounty", "action": "fuzz", "approval_required": True, "note": "Read-only authorized testing only"}, {"id": "s5", "name": "Collect Evidence", "agent": "browser", "action": "screenshot", "approval_required": False}, {"id": "s6", "name": "Generate Report", "agent": "document", "action": "generate_report", "approval_required": False}, {"id": "s7", "name": "QA Review", "agent": "verifier", "action": "verify", "approval_required": False}, {"id": "s8", "name": "Submit (Approval-Gated)", "agent": "bounty", "action": "submit", "approval_required": True}, ], "status": "active", "created_at": time.time(), }, { "id": "wf-revenue-discovery", "name": "Revenue Opportunity Discovery", "description": "discover → verify → score → prioritize → task → execute authorized → proof", "category": "revenue", "steps": [ {"id": "s1", "name": "Discover Opportunities", "agent": "revenue", "action": "discover", "approval_required": False}, {"id": "s2", "name": "Verify Authenticity", "agent": "verifier", "action": "verify", "approval_required": False}, {"id": "s3", "name": "Score & Prioritize", "agent": "revenue", "action": "score", "approval_required": False}, {"id": "s4", "name": "Create Tasks", "agent": "commander", "action": "create_task", "approval_required": False}, {"id": "s5", "name": "Execute (Authorized)", "agent": "executor", "action": "execute", "approval_required": True}, {"id": "s6", "name": "Collect Proof", "agent": "document", "action": "proof", "approval_required": False}, ], "status": "active", "created_at": time.time(), }, { "id": "wf-research", "name": "Deep Research & Report", "description": "Research any topic with browser automation and evidence collection", "category": "research", "steps": [ {"id": "s1", "name": "Parse Query", "agent": "commander", "action": "parse", "approval_required": False}, {"id": "s2", "name": "Search Sources", "agent": "research", "action": "search", "approval_required": False}, {"id": "s3", "name": "Browser Evidence", "agent": "browser", "action": "navigate", "approval_required": False}, {"id": "s4", "name": "Synthesize Findings", "agent": "document", "action": "synthesize", "approval_required": False}, {"id": "s5", "name": "Verify", "agent": "verifier", "action": "verify", "approval_required": False}, ], "status": "active", "created_at": time.time(), }, { "id": "wf-airdrop-safe", "name": "Safe Airdrop Claim", "description": "Approval-gated airdrop claiming workflow", "category": "airdrop", "steps": [ {"id": "s1", "name": "Discover Airdrops", "agent": "revenue", "action": "discover", "approval_required": False}, {"id": "s2", "name": "Verify Eligibility", "agent": "onchain", "action": "verify", "approval_required": False}, {"id": "s3", "name": "Estimate Gas", "agent": "onchain", "action": "estimate_gas", "approval_required": False}, {"id": "s4", "name": "Claim (Approval-Gated)", "agent": "onchain", "action": "claim", "approval_required": True}, {"id": "s5", "name": "Confirm Receipt", "agent": "verifier", "action": "verify", "approval_required": False}, ], "status": "active", "created_at": time.time(), }, { "id": "wf-intent-solve", "name": "Intent Solver Pipeline", "description": "Full intent lifecycle: normalize → validate → quote → route → simulate → approval → execute → settle → prove", "category": "intent", "steps": [ {"id": "s1", "name": "Normalize Intent", "agent": "intent_solver", "action": "normalize", "approval_required": False}, {"id": "s2", "name": "Validate", "agent": "intent_solver", "action": "validate", "approval_required": False}, {"id": "s3", "name": "Quote", "agent": "intent_solver", "action": "quote", "approval_required": False}, {"id": "s4", "name": "Route to Cluster", "agent": "intent_solver", "action": "route", "approval_required": False}, {"id": "s5", "name": "Simulate", "agent": "intent_solver", "action": "simulate", "approval_required": False}, {"id": "s6", "name": "Approval Gate", "agent": "security", "action": "check_approval", "approval_required": True}, {"id": "s7", "name": "Execute", "agent": "executor", "action": "execute", "approval_required": False}, {"id": "s8", "name": "Settle", "agent": "onchain", "action": "settle", "approval_required": True}, {"id": "s9", "name": "Prove", "agent": "document", "action": "proof", "approval_required": False}, ], "status": "active", "created_at": time.time(), }, ] class CreateWorkflowRequest(BaseModel): name: str description: str = "" category: str = "custom" steps: List[Dict[str, Any]] = Field(default_factory=list) class RunWorkflowRequest(BaseModel): workflow_id: str input_data: Dict[str, Any] = Field(default_factory=dict) auto_approve_safe: bool = True def _load_workflows() -> List[Dict]: if WORKFLOWS_FILE.exists(): try: return json.loads(WORKFLOWS_FILE.read_text()) except Exception: return [] return [] def _save_workflows(data: List[Dict]): WORKFLOWS_FILE.write_text(json.dumps(data, indent=2)) def _load_runs() -> List[Dict]: if RUNS_FILE.exists(): try: return json.loads(RUNS_FILE.read_text()) except Exception: return [] return [] def _save_runs(data: List[Dict]): RUNS_FILE.write_text(json.dumps(data[-500:], indent=2)) def init_workflows(): workflows = _load_workflows() if not workflows: _save_workflows(DEFAULT_WORKFLOWS) logger.info(f"Initialized {len(DEFAULT_WORKFLOWS)} default workflows") def list_workflows() -> List[Dict]: return _load_workflows() def get_workflow(wf_id: str) -> Optional[Dict]: for wf in _load_workflows(): if wf["id"] == wf_id: return wf return None def create_workflow(req: CreateWorkflowRequest) -> Dict: workflows = _load_workflows() wf = { "id": f"wf-{uuid.uuid4().hex[:8]}", "name": req.name, "description": req.description, "category": req.category, "steps": req.steps, "status": "active", "created_at": time.time(), } workflows.append(wf) _save_workflows(workflows) return wf def list_runs(limit: int = 50) -> List[Dict]: return _load_runs()[-limit:] def get_run(run_id: str) -> Optional[Dict]: for r in _load_runs(): if r["id"] == run_id: return r return None async def run_workflow(req: RunWorkflowRequest) -> Dict[str, Any]: """Execute a workflow — runs through steps, stopping at approval gates.""" wf = get_workflow(req.workflow_id) if not wf: return {"error": f"Workflow {req.workflow_id} not found"} run = { "id": f"run-{uuid.uuid4().hex[:8]}", "workflow_id": req.workflow_id, "workflow_name": wf["name"], "input_data": req.input_data, "status": "running", "steps_completed": [], "current_step": None, "waiting_for_approval": False, "result": {}, "created_at": time.time(), "updated_at": time.time(), } steps = wf.get("steps", []) for i, step in enumerate(steps): run["current_step"] = step run["updated_at"] = time.time() # Check if approval required if step.get("approval_required", False) and not req.auto_approve_safe: run["status"] = "waiting_approval" run["waiting_for_approval"] = True run["updated_at"] = time.time() runs = _load_runs() runs.append(run) _save_runs(runs) return run # Simulate step execution (real execution would dispatch to agent) step_result = { "step_id": step["id"], "step_name": step["name"], "agent": step["agent"], "action": step["action"], "status": "completed", "output": f"Step '{step['name']}' executed by {step['agent']} agent", "timestamp": time.time(), } run["steps_completed"].append(step_result) run["updated_at"] = time.time() # Save progress runs = _load_runs() runs = [r if r["id"] != run["id"] else run for r in runs] if not any(r["id"] == run["id"] for r in runs): runs.append(run) _save_runs(runs) await asyncio.sleep(0.1) # Yield control run["status"] = "completed" run["current_step"] = None run["result"] = { "total_steps": len(steps), "steps_completed": len(run["steps_completed"]), "all_succeeded": True, } run["updated_at"] = time.time() runs = _load_runs() runs = [r if r["id"] != run["id"] else run for r in runs] if not any(r["id"] == run["id"] for r in runs): runs.append(run) _save_runs(runs) return run async def approve_workflow_run(run_id: str) -> Dict[str, Any]: """Resume a workflow run from an approval gate.""" run = get_run(run_id) if not run: return {"error": "Run not found"} if run["status"] != "waiting_approval": return {"error": f"Run is not waiting for approval (status: {run['status']})"} # Continue from next step wf = get_workflow(run["workflow_id"]) if not wf: return {"error": "Workflow not found"} completed_ids = {s["step_id"] for s in run["steps_completed"]} steps = wf.get("steps", []) run["status"] = "running" run["waiting_for_approval"] = False for step in steps: if step["id"] in completed_ids: continue run["current_step"] = step run["updated_at"] = time.time() step_result = { "step_id": step["id"], "step_name": step["name"], "agent": step["agent"], "action": step["action"], "status": "completed", "output": f"Step '{step['name']}' executed by {step['agent']} agent (post-approval)", "timestamp": time.time(), } run["steps_completed"].append(step_result) await asyncio.sleep(0.1) run["status"] = "completed" run["current_step"] = None run["result"] = { "total_steps": len(steps), "steps_completed": len(run["steps_completed"]), "all_succeeded": True, "resumed_after_approval": True, } run["updated_at"] = time.time() runs = _load_runs() runs = [r if r["id"] != run["id"] else run for r in runs] _save_runs(runs) return run def register_workflow_routes(app): """Register workflow engine endpoints.""" from fastapi import FastAPI, HTTPException init_workflows() @app.get("/api/v2/workflows") async def get_workflows(): return {"workflows": list_workflows()} @app.get("/api/v2/workflows/runs") async def get_runs(limit: int = 50): return {"runs": list_runs(limit)} @app.get("/api/v2/workflows/runs/{run_id}") async def get_run_detail(run_id: str): run = get_run(run_id) if not run: raise HTTPException(404, "Run not found") return run @app.post("/api/v2/workflows/runs/{run_id}/approve") async def approve_run(run_id: str): result = await approve_workflow_run(run_id) return result @app.post("/api/v2/workflows/runs/{run_id}/cancel") async def cancel_run(run_id: str): run = get_run(run_id) if not run: raise HTTPException(404, "Run not found") run["status"] = "cancelled" run["updated_at"] = time.time() runs = _load_runs() runs = [r if r["id"] != run_id else run for r in runs] _save_runs(runs) return run @app.get("/api/v2/workflows/{wf_id}") async def get_wf_detail(wf_id: str): wf = get_workflow(wf_id) if not wf: raise HTTPException(404, "Workflow not found") return wf @app.post("/api/v2/workflows") async def create_wf(req: CreateWorkflowRequest): return create_workflow(req) @app.post("/api/v2/workflows/run") async def run_wf(req: RunWorkflowRequest): result = await run_workflow(req) return result