import os import threading import time from contextlib import asynccontextmanager from fastapi import Depends, FastAPI, Header, HTTPException from fastapi.responses import HTMLResponse from agents.scraper import fetch_web_context from core.constraint import apply_plan, validate_plan from core.llm_engine import SkyCEO from core.oracle import SilentOracle from core.state import StateManager DATA_DIR = os.environ.get("DATA_DIR", "./data") MAX_RETRIES = 3 SCRAPE_INTERVAL_S = 900 sm = StateManager(DATA_DIR) oracle = SilentOracle() ceo = SkyCEO() cycle_lock = threading.Lock() def need_token(x_token: str = Header(default="")): expected = os.environ.get("ADMIN_TOKEN") if expected and x_token != expected: raise HTTPException(status_code=401, detail="Token invalide.") def refresh_web_context() -> str: ctx = fetch_web_context() with sm.lock: sm.state.web_context = ctx sm.save() return ctx def scraper_loop() -> None: while True: try: refresh_web_context() except Exception as e: print(f"[scraper loop] {e}") time.sleep(SCRAPE_INTERVAL_S) @asynccontextmanager async def lifespan(_: FastAPI): threading.Thread(target=ceo.load, daemon=True).start() threading.Thread(target=scraper_loop, daemon=True).start() yield app = FastAPI(title="Sky-LG", lifespan=lifespan) @app.get("/health") def health(): return {"status": "ok", "model_state": ceo.status, "model_error": ceo.error} @app.get("/api/state") def get_state(): return sm.snapshot().model_dump() @app.post("/api/refresh", dependencies=[Depends(need_token)]) def refresh(): return {"web_context": refresh_web_context()} @app.post("/api/reset", dependencies=[Depends(need_token)]) def reset(): with cycle_lock: sm.reset() return {"status": "reset"} @app.post("/api/execute", dependencies=[Depends(need_token)]) def execute(): if ceo.status == "loading": raise HTTPException(status_code=503, detail="Le CEO est en cours de chargement.") if ceo.status == "failed": raise HTTPException(status_code=500, detail=f"Échec du modèle : {ceo.error}") if not cycle_lock.acquire(blocking=False): raise HTTPException(status_code=409, detail="Un cycle est déjà en cours.") try: state = sm.snapshot() if not any(t.status == "pending" for t in state.tasks): return {"status": "done", "detail": "Toutes les tâches sont terminées."} metrics = oracle.analyze(state) if not metrics["feasible_set"]: return { "status": "blocked", "reason": "Aucune tâche restante n'est finançable avec le budget actuel.", "oracle": metrics, } attempts = [] feedback = None for attempt in range(1, MAX_RETRIES + 1): plan = ceo.generate_plan(metrics, feedback) ok, reason = validate_plan(plan, state) attempts.append({"attempt": attempt, "plan": plan, "valid": ok, "reason": reason}) if ok: with sm.lock: apply_plan(plan, sm.state) sm.save() new_state = sm.state.model_copy(deep=True) return { "status": "success", "plan": plan, "oracle": metrics, "attempts": attempts, "new_budget": new_state.budget_usd, "day": new_state.day, } feedback = reason fallback = { "task_ids": metrics["feasible_set"][:3], "reasoning": "Repli Oracle : plan du CEO rejeté trois fois.", } ok, reason = validate_plan(fallback, state) if ok: with sm.lock: apply_plan(fallback, sm.state) sm.save() new_state = sm.state.model_copy(deep=True) return { "status": "fallback", "plan": fallback, "oracle": metrics, "attempts": attempts, "new_budget": new_state.budget_usd, "day": new_state.day, } return {"status": "rejected", "reason": reason, "oracle": metrics, "attempts": attempts} finally: cycle_lock.release() @app.get("/", response_class=HTMLResponse) def index(): return """Sky-LG

Sky-LG

...
"""