briga-core-api / app /api /agents.py
yabeskn's picture
Upload app/api/agents.py with huggingface_hub
225fb88 verified
Raw History Blame Contribute Delete
12.6 kB
"""AI Agents API — Antigravity Gateway."""
from typing import Any, Dict, Optional, List
from fastapi import APIRouter, Depends, HTTPException, Security, Request
from fastapi.security.api_key import APIKeyHeader
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
from app.database import get_db
from app.services.antigravity import AntigravityOrchestrator
from app.services.orchestrator_service import Orchestrator
from app.services.deploy_service import DeployService
from app.config.settings import settings
from sqlalchemy import text
router = APIRouter(prefix="/v1/agents", tags=["AI Agents"])
# Boardroom Security setup
API_KEY_NAME = "Authorization"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
async def verify_boardroom_token(api_key_header: str = Security(api_key_header)):
if not api_key_header:
raise HTTPException(status_code=401, detail="Missing Authorization Header")
# Extract token (remove 'Bearer ' if present)
token = api_key_header.replace("Bearer ", "").strip()
# Check against the secure token in .env
expected_token = settings.security_webhook_token
if not expected_token or token != expected_token:
raise HTTPException(status_code=403, detail="Invalid Super Admin Token")
return token
class AgentTaskRequest(BaseModel):
agent_name: str
task_name: str
payload: Dict[str, Any]
priority: int = 0
user_email: Optional[str] = None
class BoardDirectiveRequest(BaseModel):
directive: str
@router.get("/boardroom/activities")
async def get_agent_activities(
db: AsyncSession = Depends(get_db),
_: str = Depends(verify_boardroom_token)
):
"""Fetch the latest agent activities for the Boardroom Kanban (Admin Only)."""
query = text("""
SELECT id, agent_id, task_description, status, next_action, requires_intervention, created_at, updated_at
FROM agent_activities
ORDER BY created_at DESC
LIMIT 50
""")
res = await db.execute(query)
rows = res.fetchall()
activities = []
for row in rows:
activities.append({
"id": row.id,
"agent_id": row.agent_id,
"task_description": row.task_description,
"status": row.status,
"next_action": row.next_action,
"requires_intervention": row.requires_intervention,
"created_at": row.created_at.isoformat(),
"updated_at": row.updated_at.isoformat()
})
return {"success": True, "data": activities}
@router.post("/boardroom/directive")
async def process_board_directive(
request: BoardDirectiveRequest
):
"""Send a high-level directive to the AI Organization Boardroom (CEO Orchestrated)."""
result = await Orchestrator.process_board_directive(request.directive)
return result
@router.post("/execute")
async def execute_agent_task(
request: AgentTaskRequest,
db: AsyncSession = Depends(get_db)
):
"""Execute an autonomous AI task through the Antigravity gateway."""
orchestrator = AntigravityOrchestrator(db)
result = await orchestrator.execute_task(
agent_name=request.agent_name,
task_name=request.task_name,
payload=request.payload,
priority=request.priority,
user_email=request.user_email
)
if result.get("status") == "error":
raise HTTPException(status_code=503, detail=result.get("message"))
return result
@router.get("/stats")
async def get_agent_stats(
db: AsyncSession = Depends(get_db)
):
"""Exposes Antigravity Command Center data for the Admin Dashboard."""
orchestrator = AntigravityOrchestrator(db)
stats = await orchestrator.get_command_center_stats()
return stats
@router.post("/nettest")
async def nettest(_: str = Security(verify_boardroom_token)):
"""[SEMENTARA] Diagnosa egress dari dalam Space."""
import httpx
out = {}
async with httpx.AsyncClient(timeout=10) as c:
for name, url in {
"workers_dev": "https://briga-telegram-proxy.brigawan.workers.dev/",
"telegram_api": "https://api.telegram.org",
"telegram_root2": "https://api.telegram.org/bot123:x/getMe",
"briga_id": "https://briga.id/api/config",
"googleapis": "https://generativelanguage.googleapis.com",
"hf_space": "https://yabeskn-briga-agent-worker.hf.space/health",
"example": "https://example.com",
}.items():
try:
r = await c.get(url)
out[name] = f"HTTP {r.status_code}"
except Exception as e:
out[name] = f"{type(e).__name__}"
return {"net": out}
@router.post("/activity-report")
async def trigger_activity_report(
request: Request,
_: str = Security(verify_boardroom_token),
):
"""Kirim laporan aktivitas agent ke Founder via Telegram sekarang (Boardroom/Super Admin token).
Di-middleware masuk PUBLIC_PATHS — route ini melindungi dirinya sendiri, meniru pola webhook."""
try:
hours = 24
try:
body = await request.json()
hours = int(body.get("hours", 24))
except Exception:
pass
from app.services.agent_activity_report_service import send_now
ok = await send_now(hours=max(1, min(hours, 168)))
return {"success": ok, "detail": "laporan terkirim via Telegram CEO" if ok else "gagal kirim — cek log backend"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post('/deploy/preview')
async def trigger_preview(request: Request):
body = await request.json()
project = body.get('project', 'main-frontend-native')
# Trigger CF preview and notify CEO
deploy_resp = DeployService.trigger_cloudflare_preview(project)
if not deploy_resp.get('success'):
return {'success': False, 'error': deploy_resp.get('error')}
preview_url = deploy_resp.get('preview_url')
deploy_id = deploy_resp.get('raw', {}).get('result', {}).get('id', 'unknown')
DeployService.notify_ceo_preview(preview_url, deploy_id)
return {'success': True, 'preview_url': preview_url, 'deploy_id': deploy_id}
class HealApprovalRequest(BaseModel):
task_id: str
approved: bool
@router.post("/heal/approve")
async def approve_heal_task(
request: HealApprovalRequest,
req: Request,
db: AsyncSession = Depends(get_db)
):
"""
Receives authorization to apply code patch and deploy sync for a failed task.
Enforces header verification (X-Webhook-Token).
"""
import os
import json
import shutil
import subprocess
from datetime import datetime
from loguru import logger
from app.models.content import KnowledgeQueue
# 1. Verification of incoming token
received_token = req.headers.get("X-Security-Token") or req.headers.get("X-Webhook-Token")
expected_token = settings.webhook_secret or os.getenv("WEBHOOK_SECRET", "briga_secret_webhook_123_xyz")
if not received_token or received_token != expected_token:
logger.warning("[CTOAgent Webhook] Unauthorized approval attempt.")
raise HTTPException(status_code=403, detail="Unauthorized webhook token")
if not request.approved:
return {"success": False, "message": "Approval rejected by client"}
# 2. Fetch the task from knowledge_queue
from sqlalchemy import select
stmt = select(KnowledgeQueue).where(KnowledgeQueue.id == request.task_id)
res = await db.execute(stmt)
task = res.scalar_one_or_none()
if not task:
raise HTTPException(status_code=404, detail="Task not found in queue")
# Parse fact JSON
try:
fact_data = json.loads(task.fact) if isinstance(task.fact, str) else task.fact
if not isinstance(fact_data, dict):
fact_data = {}
except Exception:
fact_data = {}
target_file = fact_data.get("target_file")
target_code = fact_data.get("target_code_to_replace")
replacement_code = fact_data.get("replacement_code")
if not target_file or not target_code:
raise HTTPException(status_code=400, detail="Missing patch parameters in task fact data")
# 3. Resolve file paths
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not os.path.isabs(target_file):
abs_path = os.path.join(base_dir, target_file)
else:
abs_path = target_file
if not os.path.exists(abs_path):
# Fallback to direct path check
abs_path = target_file
if not os.path.exists(abs_path):
raise HTTPException(status_code=404, detail=f"Target file {target_file} not found in workspace")
# Create Safety Backup (.bak)
try:
backup_path = abs_path + ".bak"
shutil.copy2(abs_path, backup_path)
logger.info(f"[CTOAgent Webhook] Created safety backup at {backup_path}")
except Exception as e:
logger.error(f"[CTOAgent Webhook] Backup failed: {e}")
raise HTTPException(status_code=500, detail=f"Failed to create file backup: {str(e)}")
# Replace content and compile-check
try:
with open(abs_path, "r", encoding="utf-8") as f:
content = f.read()
if target_code not in content:
raise HTTPException(status_code=400, detail="Target code block not found in file content")
new_content = content.replace(target_code, replacement_code)
# Dry-run compile check (if Python)
if abs_path.endswith(".py"):
try:
compile(new_content, abs_path, "exec")
logger.info("[CTOAgent Webhook] Patch dry-run compile validation passed.")
except Exception as ce:
logger.error(f"[CTOAgent Webhook] Compilation error: {ce}")
raise HTTPException(status_code=422, detail=f"Patch compilation check failed: {str(ce)}")
# Write verified patch
with open(abs_path, "w", encoding="utf-8") as f:
f.write(new_content)
logger.info(f"[CTOAgent Webhook] Patch applied successfully to {abs_path}")
except HTTPException:
raise
except Exception as e:
logger.error(f"[CTOAgent Webhook] Error writing patch: {e}")
raise HTTPException(status_code=500, detail=f"Failed to write patch: {str(e)}")
# 4. RUN DEPLOYMENT PIPELINE
deploy_output = []
try:
workspace_root = os.path.dirname(base_dir)
git_root = os.path.join(workspace_root, "brigawan")
# Git operations (best-effort)
if os.path.exists(git_root):
subprocess.run(["git", "add", "-A"], cwd=git_root, capture_output=True, text=True)
commit_res = subprocess.run(["git", "commit", "-m", f"auto-heal: patch {os.path.basename(target_file)} via CTO Agent"], cwd=git_root, capture_output=True, text=True)
push_res = subprocess.run(["git", "push", "origin", "master"], cwd=git_root, capture_output=True, text=True)
deploy_output.append(f"Git commit/push exit code: {push_res.returncode}")
# Run split_monolith.py
split_script = os.path.join(workspace_root, "split_monolith.py")
if os.path.exists(split_script):
split_res = subprocess.run(["python", "split_monolith.py"], cwd=workspace_root, capture_output=True, text=True)
deploy_output.append(f"split_monolith exit code: {split_res.returncode}")
# Run hf upload
hf_res = subprocess.run([
"hf", "upload", "yabeskn/briga-agent-worker",
"./spaces/briga-agent-worker/", ".", "--repo-type", "space"
], cwd=workspace_root, capture_output=True, text=True)
deploy_output.append(f"hf upload exit code: {hf_res.returncode}")
except Exception as de:
logger.error(f"[CTOAgent Webhook] Deploy sync error: {de}")
deploy_output.append(f"Deploy sync failed: {str(de)}")
# 5. Update Task Status
task.status = "Healed"
task.timestamp = datetime.now()
fact_data["healing_logs"] = deploy_output
task.fact = json.dumps(fact_data)
await db.commit()
return {"success": True, "message": f"Patch applied to {target_file}", "logs": deploy_output}