Spaces:
Paused

File size: 4,561 Bytes
0a6db2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9ef2b
 
 
 
 
 
 
 
0a6db2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2375c60
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6db2f
 
 
 
 
 
 
 
 
2375c60
 
 
 
 
 
 
 
 
 
0a6db2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""État partagé (un seul modèle, un seul verrou) utilisé par l'UI Gradio et l'API headless."""
from __future__ import annotations

import faulthandler
import os
import threading
import traceback

faulthandler.enable()  # pile Python sur crash natif (132 = SIGILL, 139 = SIGSEGV)
os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")

from database import Database  # noqa: E402
from tools import Workspace  # noqa: E402

MODEL_REPO = os.environ.get("MODEL_REPO", "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF")
MODEL_FILE = os.environ.get("MODEL_FILE", "Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf")
MODEL_DIR = os.environ.get("MODEL_DIR", os.path.expanduser("~/models"))

API_KEY = os.environ.get("SKY_API_KEY", "").strip()
AUTH_ON = bool(API_KEY) and API_KEY.lower() != "none"
ALLOW_ANON = API_KEY.lower() == "none" or os.environ.get("SKY_ALLOW_ANON") == "1"

WS = Workspace(os.environ.get("SKY_WORKSPACE", "~/workspace"))
try:
    DB = Database()
except Exception as e:  # dernier recours : base vide en mémoire de travail, l'app démarre quand même
    import tempfile

    print(f"[DB] base inutilisable ({e!r}) : base temporaire non persistée", flush=True)
    DB = Database(os.path.join(tempfile.mkdtemp(), "cycle_logs.db"), persist_path=None)
    DB.notice = f"Base persistante inutilisable ({type(e).__name__}) : journal temporaire, non conservé."
RUN_LOCK = threading.Lock()   # llama.cpp n'est pas thread-safe : un seul cycle à la fois
STOP = threading.Event()
state = {"agent": None, "status": "Chargement du modèle...", "error": ""}
_started = False


def harden_process() -> None:
    """PR_SET_DUMPABLE=0 : le code généré (même uid) ne peut plus lire /proc/<pid>/environ de ce processus."""
    try:
        import ctypes

        libc = ctypes.CDLL(None, use_errno=True)
        ok = libc.prctl(4, 0, 0, 0, 0) == 0
        print("[SEC] processus non-dumpable" if ok else "[SEC] prctl(PR_SET_DUMPABLE) a échoué", flush=True)
    except Exception as e:  # plateforme non Linux
        print(f"[SEC] durcissement indisponible : {e}", flush=True)


def ensure_model() -> str:
    path = os.path.join(MODEL_DIR, MODEL_FILE)
    if os.path.exists(path):
        print(f"[LLM] CACHE HIT — {path}", flush=True)
        return path
    from huggingface_hub import hf_hub_download

    print(f"[LLM] CACHE MISS — téléchargement de {MODEL_FILE} (~18 Go)...", flush=True)
    return hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE, local_dir=MODEL_DIR)


JUDGE_REPO = os.environ.get("SKY_JUDGE_REPO", "")
JUDGE_FILE = os.environ.get("SKY_JUDGE_FILE", "")


def ensure_judge_model() -> str:
    path = os.path.join(MODEL_DIR, JUDGE_FILE)
    if os.path.exists(path):
        return path
    from huggingface_hub import hf_hub_download

    print(f"[JUGE] téléchargement de {JUDGE_FILE}...", flush=True)
    return hf_hub_download(repo_id=JUDGE_REPO, filename=JUDGE_FILE, local_dir=MODEL_DIR)


def _load_model() -> None:
    try:
        from orchestrator import AgentOrchestrator

        state["agent"] = AgentOrchestrator(ensure_model())
        state["status"] = "Prêt"
    except Exception as e:
        state["status"], state["error"] = "Erreur", repr(e)
        traceback.print_exc()
        return
    if JUDGE_FILE:  # un juge qui ne charge pas n'empêche pas l'usine de fonctionner : l'Arbitre reste Qwen
        try:
            name = JUDGE_FILE.split("-Instruct")[0].split(".gguf")[0]
            state["judge"] = f"chargement de {name}..."
            state["agent"].attach_judge(ensure_judge_model(), name)
            state["judge"] = f"{name} (CPU)" if os.environ.get("SKY_JUDGE_GPU_LAYERS", "0") == "0" else name
        except Exception as e:
            state["judge"] = f"indisponible ({type(e).__name__}) : Arbitre = Codeur"
            traceback.print_exc()


def start() -> None:
    """Idempotent : durcit le processus, prépare le workspace, charge le modèle en arrière-plan."""
    global _started
    if _started:
        return
    _started = True
    harden_process()
    try:
        WS.init()
    except Exception as e:
        print(f"[WS] init : {e}", flush=True)
    threading.Thread(target=_load_model, daemon=True).start()


def precheck() -> str | None:
    """Message d'erreur si on ne peut pas lancer de cycle, sinon None."""
    if not (AUTH_ON or ALLOW_ANON):
        return "⛔ Définissez le secret SKY_API_KEY (ou SKY_ALLOW_ANON=1) avant d'exécuter un cycle."
    if state["agent"] is None:
        return f"Modèle pas prêt : {state['status']} {state['error']}"
    return None