File size: 12,622 Bytes
3a006a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584d1a5
 
 
 
 
 
 
 
 
225fb88
 
584d1a5
 
 
 
 
 
 
 
 
 
 
 
240a150
 
 
 
 
6cc1f82
 
240a150
 
 
 
 
 
 
 
 
 
 
 
 
 
3a006a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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}