Download app.py from RDS777/data: direct link, hf CLI and curl.
- Browser
- Download file 31.4 kB
-
https://huggingface.co/spaces/RDS777/data/resolve/main/app.py
- Command line
-
hf download hf://spaces/RDS777/data/app.py
-
curl -L -o app.py https://huggingface.co/spaces/RDS777/data/resolve/main/app.py
31.4 kB
| #!/usr/bin/env python3 | |
| """Agent de codage autonome, persistant et 100 % local (CPU) pour Hugging Face Spaces. | |
| Le modèle de code (Qwen2.5-Coder par défaut) est chargé via transformers et | |
| exécuté sur le CPU du Space : aucun appel API distant à l'inférence. | |
| Dépendances (requirements.txt) : fastapi, uvicorn, torch, transformers, accelerate | |
| Variables d'environnement : | |
| MODEL_ID modèle local (défaut : Qwen/Qwen2.5-Coder-1.5B-Instruct) | |
| HF_TOKEN jeton Hugging Face pour le téléchargement (optionnel) | |
| DTYPE float32 | bfloat16 | float16 (défaut : float32) | |
| MAX_INPUT_TOKENS budget de contexte en tokens (défaut : 6000) | |
| MAX_NEW_TOKENS longueur maximale générée par tour (défaut : 1024) | |
| HISTORY_TURNS nombre de tours passés conservés (défaut : 1) | |
| DATA_DIR répertoire persistant (défaut : /data si présent, sinon ./data) | |
| REPO_URL dépôt Git à cloner (optionnel) | |
| TEST_CMD commande de tests (défaut : python -m pytest -x -q) | |
| MAX_ITERATIONS 0 = illimité (défaut : 0) | |
| TEST_TIMEOUT timeout par exécution de tests, secondes (défaut : 7200) | |
| ADMIN_TOKEN jeton d'accès aux endpoints d'écriture (optionnel) | |
| PORT port HTTP (défaut : 7860) | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import gc | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import shlex | |
| import subprocess | |
| import threading | |
| import time | |
| import traceback | |
| from collections import deque | |
| from dataclasses import asdict, dataclass, field | |
| from pathlib import Path | |
| from typing import Deque, Dict, List, Optional, Tuple | |
| import uvicorn | |
| from fastapi import FastAPI, Header, HTTPException | |
| from fastapi.responses import JSONResponse | |
| import torch | |
| from transformers import ( | |
| AutoModelForCausalLM, | |
| AutoTokenizer, | |
| StoppingCriteria, | |
| StoppingCriteriaList, | |
| pipeline, | |
| ) | |
| from pydantic import BaseModel | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| LOG = logging.getLogger("agent") | |
| # --------------------------------------------------------------------------- # | |
| # Configuration | |
| # --------------------------------------------------------------------------- # | |
| def _default_data_dir() -> Path: | |
| """Retourne le répertoire persistant (/data sur HF Spaces si activé).""" | |
| env = os.environ.get("DATA_DIR") | |
| if env: | |
| return Path(env) | |
| return Path("/data") if Path("/data").is_dir() else Path("./data") | |
| class Config: | |
| """Configuration globale de l'agent.""" | |
| hf_token: str = os.environ.get("HF_TOKEN", "") | |
| model_id: str = os.environ.get("MODEL_ID", "Qwen/Qwen2.5-Coder-1.5B-Instruct") | |
| dtype: str = os.environ.get("DTYPE", "float32") | |
| max_input_tokens: int = int(os.environ.get("MAX_INPUT_TOKENS", "6000")) | |
| max_new_tokens: int = int(os.environ.get("MAX_NEW_TOKENS", "1024")) | |
| history_turns: int = int(os.environ.get("HISTORY_TURNS", "1")) | |
| data_dir: Path = field(default_factory=_default_data_dir) | |
| repo_url: str = os.environ.get("REPO_URL", "") | |
| test_cmd: str = os.environ.get("TEST_CMD", "python -m pytest -x -q") | |
| max_iterations: int = int(os.environ.get("MAX_ITERATIONS", "0")) | |
| test_timeout: int = int(os.environ.get("TEST_TIMEOUT", "7200")) | |
| admin_token: str = os.environ.get("ADMIN_TOKEN", "") | |
| port: int = int(os.environ.get("PORT", "7860")) | |
| map_budget_chars: int = 6000 | |
| file_budget_chars: int = 12000 | |
| llm_retry_cap_s: int = 300 | |
| def workspace(self) -> Path: | |
| return self.data_dir / "workspace" | |
| def state_file(self) -> Path: | |
| return self.data_dir / "state.json" | |
| class AgentError(Exception): | |
| """Erreur générique de l'agent.""" | |
| class StopRequested(AgentError): | |
| """Arrêt demandé par l'utilisateur.""" | |
| class EditError(AgentError): | |
| """Erreur lors de l'application d'une édition.""" | |
| # --------------------------------------------------------------------------- # | |
| # Gestionnaire Git | |
| # --------------------------------------------------------------------------- # | |
| class GitManager: | |
| """Encapsule les opérations Git sur le dépôt local.""" | |
| IGNORED = {".git", "__pycache__", "node_modules", ".venv", "venv", ".pytest_cache"} | |
| def __init__(self, root: Path) -> None: | |
| self.root = root | |
| def run(self, *args: str, check: bool = True, timeout: int = 300) -> str: | |
| """Exécute une commande git et retourne sa sortie standard.""" | |
| try: | |
| proc = subprocess.run( | |
| ["git", *args], cwd=self.root, capture_output=True, | |
| text=True, timeout=timeout, errors="replace", | |
| ) | |
| except (OSError, subprocess.SubprocessError) as exc: | |
| raise AgentError(f"git {' '.join(args)} a échoué : {exc}") from exc | |
| if check and proc.returncode != 0: | |
| raise AgentError(f"git {' '.join(args)} -> {proc.returncode}: {proc.stderr.strip()}") | |
| return proc.stdout | |
| def ensure_repo(self, repo_url: str) -> None: | |
| """Initialise ou clone le dépôt de travail si nécessaire.""" | |
| self.root.parent.mkdir(parents=True, exist_ok=True) | |
| if not (self.root / ".git").is_dir(): | |
| if repo_url: | |
| subprocess.run(["git", "clone", repo_url, str(self.root)], check=True, timeout=1800) | |
| else: | |
| self.root.mkdir(parents=True, exist_ok=True) | |
| self.run("init") | |
| self.run("config", "user.name", "coding-agent", check=False) | |
| self.run("config", "user.email", "agent@localhost", check=False) | |
| def status(self) -> str: | |
| return self.run("status", "--short", check=False).strip() or "(propre)" | |
| def diff(self, limit: int = 6000) -> str: | |
| out = self.run("diff", "HEAD", check=False) or self.run("diff", check=False) | |
| return out[:limit] + ("\n…[tronqué]" if len(out) > limit else "") | |
| def tree(self, max_entries: int = 300) -> str: | |
| """Arborescence compacte des fichiers du projet.""" | |
| entries: List[str] = [] | |
| for path in sorted(self.root.rglob("*")): | |
| rel = path.relative_to(self.root) | |
| if any(part in self.IGNORED for part in rel.parts) or path.is_dir(): | |
| continue | |
| entries.append(str(rel)) | |
| if len(entries) >= max_entries: | |
| entries.append("…") | |
| break | |
| return "\n".join(entries) or "(vide)" | |
| def commit_all(self, message: str) -> bool: | |
| """Crée un commit atomique ; retourne False s'il n'y a rien à valider.""" | |
| self.run("add", "-A") | |
| if not self.run("status", "--porcelain", check=False).strip(): | |
| return False | |
| self.run("commit", "-m", message[:200]) | |
| return True | |
| # --------------------------------------------------------------------------- # | |
| # Carte du dépôt | |
| # --------------------------------------------------------------------------- # | |
| class RepoMap: | |
| """Construit une carte légère : signatures de classes et fonctions.""" | |
| SKIP = GitManager.IGNORED | |
| GENERIC = re.compile( | |
| r"^\s*(?:export\s+)?(?:async\s+)?(?:function|class|def|struct|interface|fn)\s+\w+.*$" | |
| ) | |
| def __init__(self, root: Path, budget: int) -> None: | |
| self.root = root | |
| self.budget = budget | |
| def _py_signatures(source: str) -> List[str]: | |
| sigs: List[str] = [] | |
| try: | |
| tree = ast.parse(source) | |
| except SyntaxError as exc: | |
| return [f" ! erreur de syntaxe ligne {exc.lineno}"] | |
| def visit(nodes: List[ast.stmt], indent: int) -> None: | |
| for node in nodes: | |
| pad = " " * indent | |
| if isinstance(node, ast.ClassDef): | |
| sigs.append(f"{pad}class {node.name}:") | |
| visit(node.body, indent + 1) | |
| elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): | |
| prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def" | |
| try: | |
| args = ast.unparse(node.args) | |
| except Exception: # noqa: BLE001 | |
| args = "..." | |
| ret = f" -> {ast.unparse(node.returns)}" if node.returns else "" | |
| sigs.append(f"{pad}{prefix} {node.name}({args}){ret}") | |
| visit(tree.body, 1) | |
| return sigs | |
| def build(self) -> str: | |
| """Retourne la carte textuelle, tronquée au budget configuré.""" | |
| lines: List[str] = [] | |
| for path in sorted(self.root.rglob("*")): | |
| rel = path.relative_to(self.root) | |
| if path.is_dir() or any(p in self.SKIP for p in rel.parts): | |
| continue | |
| if path.suffix not in {".py", ".js", ".ts", ".rs", ".go", ".java", ".c", ".cpp"}: | |
| continue | |
| try: | |
| text = path.read_text(encoding="utf-8", errors="replace") | |
| except OSError: | |
| continue | |
| lines.append(f"{rel}:") | |
| if path.suffix == ".py": | |
| lines.extend(self._py_signatures(text)) | |
| else: | |
| lines.extend(" " + ln.strip()[:120] for ln in text.splitlines() if self.GENERIC.match(ln)) | |
| if sum(len(x) + 1 for x in lines) > self.budget: | |
| lines.append("…[carte tronquée]") | |
| break | |
| return "\n".join(lines) or "(aucun fichier source)" | |
| # --------------------------------------------------------------------------- # | |
| # Moteur d'édition Search/Replace | |
| # --------------------------------------------------------------------------- # | |
| class EditBlock: | |
| """Un bloc d'édition SEARCH/REPLACE ciblant un fichier.""" | |
| path: str | |
| search: str | |
| replace: str | |
| class EditEngine: | |
| """Analyse et applique des blocs SEARCH/REPLACE de façon atomique.""" | |
| PATTERN = re.compile( | |
| r"^(?P<path>[^\n]+)\n<<<<<<< SEARCH\n(?P<search>.*?)\n?=======\n" | |
| r"(?P<replace>.*?)\n?>>>>>>> REPLACE", | |
| re.DOTALL | re.MULTILINE, | |
| ) | |
| def __init__(self, root: Path) -> None: | |
| self.root = root.resolve() | |
| def parse(self, text: str) -> List[EditBlock]: | |
| """Extrait les blocs d'édition d'une réponse du modèle.""" | |
| blocks: List[EditBlock] = [] | |
| for m in self.PATTERN.finditer(text): | |
| path = m.group("path").strip().strip("`").strip() | |
| blocks.append(EditBlock(path, m.group("search"), m.group("replace"))) | |
| return blocks | |
| def _safe_path(self, rel: str) -> Path: | |
| target = (self.root / rel).resolve() | |
| if self.root != target and self.root not in target.parents: | |
| raise EditError(f"Chemin hors du dépôt : {rel}") | |
| return target | |
| def _fuzzy_replace(content: str, search: str, replace: str) -> Optional[str]: | |
| """Remplacement tolérant aux espaces en fin de ligne.""" | |
| c_lines = content.split("\n") | |
| s_lines = [ln.rstrip() for ln in search.split("\n")] | |
| n = len(s_lines) | |
| hits = [i for i in range(len(c_lines) - n + 1) | |
| if [ln.rstrip() for ln in c_lines[i:i + n]] == s_lines] | |
| if len(hits) != 1: | |
| return None | |
| i = hits[0] | |
| return "\n".join(c_lines[:i] + replace.split("\n") + c_lines[i + n:]) | |
| def check_syntax(path: Path, content: str) -> None: | |
| """Vérifie la syntaxe selon l'extension (Python, JSON).""" | |
| try: | |
| if path.suffix == ".py": | |
| compile(content, str(path), "exec") | |
| elif path.suffix == ".json": | |
| json.loads(content) | |
| except (SyntaxError, ValueError) as exc: | |
| raise EditError(f"Syntaxe invalide dans {path.name} : {exc}") from exc | |
| def apply(self, blocks: List[EditBlock]) -> List[str]: | |
| """Applique tous les blocs ou aucun. Retourne les fichiers modifiés.""" | |
| if not blocks: | |
| raise EditError("Aucun bloc SEARCH/REPLACE valide trouvé.") | |
| staged: Dict[Path, str] = {} | |
| for blk in blocks: | |
| target = self._safe_path(blk.path) | |
| if target in staged: | |
| content = staged[target] | |
| elif target.exists(): | |
| content = target.read_text(encoding="utf-8") | |
| else: | |
| content = "" | |
| if not blk.search.strip(): | |
| if content.strip(): | |
| raise EditError(f"SEARCH vide mais {blk.path} existe déjà et n'est pas vide.") | |
| new = blk.replace | |
| else: | |
| count = content.count(blk.search) | |
| if count == 1: | |
| new = content.replace(blk.search, blk.replace, 1) | |
| elif count > 1: | |
| raise EditError(f"Bloc SEARCH ambigu ({count} occurrences) dans {blk.path}.") | |
| else: | |
| fuzzy = self._fuzzy_replace(content, blk.search, blk.replace) | |
| if fuzzy is None: | |
| raise EditError(f"Bloc SEARCH introuvable dans {blk.path}.") | |
| new = fuzzy | |
| self.check_syntax(target, new) | |
| staged[target] = new | |
| try: | |
| for target, content in staged.items(): | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = target.with_suffix(target.suffix + ".tmp") | |
| tmp.write_text(content, encoding="utf-8") | |
| os.replace(tmp, target) | |
| except OSError as exc: | |
| raise EditError(f"Écriture impossible : {exc}") from exc | |
| return [str(p.relative_to(self.root)) for p in staged] | |
| # --------------------------------------------------------------------------- # | |
| # Exécution des tests | |
| # --------------------------------------------------------------------------- # | |
| class TestResult: | |
| """Résultat d'une exécution de tests.""" | |
| ok: bool | |
| output: str | |
| class TestRunner: | |
| """Lance la commande de tests locale avec un timeout généreux.""" | |
| def __init__(self, root: Path, cmd: str, timeout: int) -> None: | |
| self.root, self.cmd, self.timeout = root, cmd, timeout | |
| def run(self) -> TestResult: | |
| has_tests = any(self.root.rglob("test_*.py")) or any(self.root.rglob("*_test.py")) | |
| cmd = self.cmd if has_tests else "python -m compileall -q ." | |
| try: | |
| proc = subprocess.run( | |
| shlex.split(cmd), cwd=self.root, capture_output=True, text=True, | |
| timeout=self.timeout, errors="replace", | |
| ) | |
| except subprocess.TimeoutExpired: | |
| return TestResult(False, f"Timeout dépassé ({self.timeout}s) pour : {cmd}") | |
| except (OSError, ValueError) as exc: | |
| return TestResult(False, f"Impossible d'exécuter '{cmd}' : {exc}") | |
| out = (proc.stdout + "\n" + proc.stderr).strip() | |
| return TestResult(proc.returncode == 0, out[-8000:]) | |
| # --------------------------------------------------------------------------- # | |
| # Client LLM local (transformers, CPU) | |
| # --------------------------------------------------------------------------- # | |
| class StopOnEvent(StoppingCriteria): | |
| """Interrompt la génération dès que l'événement d'arrêt est levé.""" | |
| def __init__(self, event: threading.Event) -> None: | |
| self.event = event | |
| def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs: object) -> torch.BoolTensor: | |
| return torch.full((input_ids.shape[0],), self.event.is_set(), dtype=torch.bool, device=input_ids.device) | |
| class LLMClient: | |
| """Génération de texte locale sur CPU via un pipeline transformers.""" | |
| def __init__(self, cfg: Config, stop: threading.Event) -> None: | |
| self.cfg, self.stop = cfg, stop | |
| self.ready = False | |
| self._pipe: Optional[object] = None | |
| self._tok: Optional[AutoTokenizer] = None | |
| self._lock = threading.Lock() | |
| def normalize(messages: List[Dict[str, str]]) -> List[Dict[str, str]]: | |
| """Garantit : system en tête, puis alternance stricte user/assistant, | |
| terminée par un message user (fusionne les rôles consécutifs identiques).""" | |
| out: List[Dict[str, str]] = [] | |
| for msg in messages: | |
| role, content = msg["role"], msg["content"] | |
| if not content.strip(): | |
| continue | |
| if out and out[-1]["role"] == role and role != "system": | |
| out[-1] = {"role": role, "content": out[-1]["content"] + "\n\n" + content} | |
| else: | |
| out.append({"role": role, "content": content}) | |
| body = [m for m in out if m["role"] != "system"] | |
| while body and body[0]["role"] != "user": | |
| body.pop(0) | |
| while body and body[-1]["role"] != "user": | |
| body.pop() | |
| system = [m for m in out if m["role"] == "system"][:1] | |
| return system + body | |
| def load(self) -> None: | |
| """Charge tokenizer et modèle (une seule fois), avec reprise sur erreur réseau.""" | |
| with self._lock: | |
| if self._pipe is not None: | |
| return | |
| delay = 5 | |
| while not self.stop.is_set(): | |
| try: | |
| LOG.info("Chargement du modèle local %s…", self.cfg.model_id) | |
| torch.set_num_threads(max(1, os.cpu_count() or 1)) | |
| cache = str(self.cfg.data_dir / "models") | |
| token = self.cfg.hf_token or None | |
| tok = AutoTokenizer.from_pretrained(self.cfg.model_id, cache_dir=cache, token=token) | |
| dtype = getattr(torch, self.cfg.dtype, torch.float32) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| self.cfg.model_id, cache_dir=cache, token=token, | |
| torch_dtype=dtype, low_cpu_mem_usage=True, | |
| ) | |
| model.eval() | |
| self._tok = tok | |
| self._pipe = pipeline("text-generation", model=model, tokenizer=tok, device=-1) | |
| self.ready = True | |
| LOG.info("Modèle prêt (CPU, %s).", self.cfg.dtype) | |
| return | |
| except Exception as exc: # noqa: BLE001 | |
| LOG.warning("Chargement du modèle échoué (%s). Nouvel essai dans %ss", exc, delay) | |
| self.stop.wait(delay) | |
| delay = min(delay * 2, self.cfg.llm_retry_cap_s) | |
| raise StopRequested("Arrêt demandé pendant le chargement du modèle.") | |
| def _render(self, messages: List[Dict[str, str]]) -> str: | |
| assert self._tok is not None | |
| return str(self._tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)) | |
| def _count(self, text: str) -> int: | |
| assert self._tok is not None | |
| return len(self._tok(text, add_special_tokens=False)["input_ids"]) | |
| def _fit(self, messages: List[Dict[str, str]], budget: int) -> str: | |
| """Applique le template natif et réduit le contexte pour tenir dans le budget.""" | |
| msgs = [dict(m) for m in messages] | |
| while True: | |
| prompt = self._render(msgs) | |
| if self._count(prompt) <= budget: | |
| return prompt | |
| if len(msgs) > 2: | |
| del msgs[1:3] # supprime le plus ancien couple user/assistant | |
| continue | |
| content = msgs[-1]["content"] | |
| if len(content) < 500: | |
| return prompt | |
| head, tail = int(len(content) * 0.25), int(len(content) * 0.5) | |
| msgs[-1]["content"] = content[:head] + "\n…[contexte tronqué]…\n" + content[-tail:] | |
| def chat(self, messages: List[Dict[str, str]]) -> str: | |
| """Génère une réponse ; réduit budgets et longueur en cas d'erreur mémoire.""" | |
| msgs = self.normalize(messages) | |
| self.load() | |
| budget, new_tokens, failures = self.cfg.max_input_tokens, self.cfg.max_new_tokens, 0 | |
| while not self.stop.is_set(): | |
| try: | |
| prompt = self._fit(msgs, budget) | |
| assert callable(self._pipe) | |
| with torch.inference_mode(): | |
| out = self._pipe( | |
| prompt, max_new_tokens=new_tokens, do_sample=False, return_full_text=False, | |
| stopping_criteria=StoppingCriteriaList([StopOnEvent(self.stop)]), | |
| ) | |
| if self.stop.is_set(): | |
| break | |
| return str(out[0]["generated_text"]) | |
| except (RuntimeError, MemoryError) as exc: | |
| failures += 1 | |
| LOG.warning("Échec de génération (%s) [%d/4]", exc, failures) | |
| if failures >= 4: | |
| raise AgentError(f"Génération impossible : {exc}") from exc | |
| budget, new_tokens = max(1024, budget // 2), max(256, new_tokens // 2) | |
| self.stop.wait(2) | |
| finally: | |
| gc.collect() | |
| raise StopRequested("Arrêt demandé pendant la génération.") | |
| # --------------------------------------------------------------------------- # | |
| # Agent | |
| # --------------------------------------------------------------------------- # | |
| SYSTEM_PROMPT = """Tu es un agent de codage autonome. Tu reçois une tâche, une carte du dépôt, \ | |
| l'état git et le dernier rapport de tests. Réponds UNIQUEMENT avec : | |
| 1) optionnellement des lignes `READ: chemin/fichier` pour voir des fichiers au prochain tour ; | |
| 2) des blocs d'édition au format exact : | |
| chemin/fichier.py | |
| <<<<<<< SEARCH | |
| code existant exact (vide pour créer un nouveau fichier) | |
| ======= | |
| nouveau code | |
| >>>>>>> REPLACE | |
| Inclure les tests nécessaires. Le code doit être typé, documenté et robuste. | |
| Si la tâche est entièrement terminée et que les tests passent, réponds exactement : DONE""" | |
| class AgentState: | |
| """État persistant sérialisable de l'agent.""" | |
| task: str = "" | |
| status: str = "idle" # idle | running | success | stopped | error | |
| iteration: int = 0 | |
| last_message: str = "" | |
| updated_at: float = 0.0 | |
| class CodingAgent: | |
| """Orchestre la boucle édition -> tests -> correction jusqu'au succès.""" | |
| def __init__(self, cfg: Config) -> None: | |
| self.cfg = cfg | |
| cfg.data_dir.mkdir(parents=True, exist_ok=True) | |
| self.stop = threading.Event() | |
| self.lock = threading.Lock() | |
| self.logs: Deque[str] = deque(maxlen=500) | |
| self.state = self._load_state() | |
| self.git = GitManager(cfg.workspace) | |
| self.git.ensure_repo(cfg.repo_url) | |
| self.edits = EditEngine(cfg.workspace) | |
| self.tests = TestRunner(cfg.workspace, cfg.test_cmd, cfg.test_timeout) | |
| self.llm = LLMClient(cfg, self.stop) | |
| self.thread: Optional[threading.Thread] = None | |
| # -- persistance ------------------------------------------------------- # | |
| def _load_state(self) -> AgentState: | |
| try: | |
| return AgentState(**json.loads(self.cfg.state_file.read_text(encoding="utf-8"))) | |
| except (OSError, ValueError, TypeError): | |
| return AgentState() | |
| def _save_state(self) -> None: | |
| self.state.updated_at = time.time() | |
| try: | |
| tmp = self.cfg.state_file.with_suffix(".tmp") | |
| tmp.write_text(json.dumps(asdict(self.state), ensure_ascii=False), encoding="utf-8") | |
| os.replace(tmp, self.cfg.state_file) | |
| except OSError as exc: | |
| LOG.error("Sauvegarde d'état impossible : %s", exc) | |
| def log(self, msg: str) -> None: | |
| LOG.info(msg) | |
| self.logs.append(f"{time.strftime('%H:%M:%S')} {msg}") | |
| # -- contrôle ---------------------------------------------------------- # | |
| def start(self, task: str) -> None: | |
| """Démarre une nouvelle tâche (échoue si une tâche est en cours).""" | |
| with self.lock: | |
| if self.thread and self.thread.is_alive(): | |
| raise AgentError("Une tâche est déjà en cours.") | |
| self.stop.clear() | |
| self.state = AgentState(task=task, status="running") | |
| self._save_state() | |
| self.thread = threading.Thread(target=self._guard, daemon=True) | |
| self.thread.start() | |
| def resume_if_needed(self) -> None: | |
| """Reprend automatiquement une tâche interrompue par un redémarrage.""" | |
| if self.state.status == "running" and self.state.task: | |
| self.log("Reprise de la tâche interrompue.") | |
| self.stop.clear() | |
| self.thread = threading.Thread(target=self._guard, daemon=True) | |
| self.thread.start() | |
| def request_stop(self) -> None: | |
| self.stop.set() | |
| def _guard(self) -> None: | |
| try: | |
| self._loop() | |
| except StopRequested: | |
| self.log("Arrêt demandé.") | |
| self.state.status = "stopped" | |
| self._save_state() | |
| except Exception as exc: # noqa: BLE001 | |
| self.log(f"ERREUR FATALE : {exc}\n{traceback.format_exc(limit=3)}") | |
| self.state.status, self.state.last_message = "error", str(exc) | |
| self._save_state() | |
| # -- boucle principale ------------------------------------------------- # | |
| def _read_files(self, paths: List[str]) -> str: | |
| chunks: List[str] = [] | |
| budget = self.cfg.file_budget_chars | |
| for rel in paths: | |
| try: | |
| target = self.edits._safe_path(rel) | |
| text = target.read_text(encoding="utf-8", errors="replace") | |
| except (OSError, EditError): | |
| chunks.append(f"### {rel}\n(illisible ou inexistant)") | |
| continue | |
| text = text[:budget] | |
| budget -= len(text) | |
| chunks.append(f"### {rel}\n{text}") | |
| if budget <= 0: | |
| break | |
| return "\n\n".join(chunks) | |
| def _files_from_report(report: str) -> List[str]: | |
| found = re.findall(r'File "([^"]+)"|^([\w./-]+\.py):\d+', report, re.MULTILINE) | |
| out: List[str] = [] | |
| for a, b in found: | |
| p = a or b | |
| if p and not p.startswith("/usr") and "site-packages" not in p and p not in out: | |
| out.append(p) | |
| return out[:5] | |
| def _loop(self) -> None: | |
| ws = self.cfg.workspace | |
| report, extra_files = "(aucun test exécuté)", "" | |
| turns: Deque[Tuple[str, str]] = deque(maxlen=max(1, self.cfg.history_turns)) | |
| while not self.stop.is_set(): | |
| if self.cfg.max_iterations and self.state.iteration >= self.cfg.max_iterations: | |
| self.state.status, self.state.last_message = "error", "Limite d'itérations atteinte." | |
| break | |
| self.state.iteration += 1 | |
| self.log(f"=== Itération {self.state.iteration} ===") | |
| context = ( | |
| f"TÂCHE:\n{self.state.task}\n\nARBORESCENCE:\n{self.git.tree()}\n\n" | |
| f"CARTE DU DÉPÔT:\n{RepoMap(ws, self.cfg.map_budget_chars).build()}\n\n" | |
| f"GIT STATUS:\n{self.git.status()}\n\nGIT DIFF:\n{self.git.diff()}\n\n" | |
| f"DERNIER RAPPORT:\n{report}\n\n{extra_files}" | |
| ) | |
| messages: List[Dict[str, str]] = [{"role": "system", "content": SYSTEM_PROMPT}] | |
| for past_user, past_assistant in turns: | |
| messages += [{"role": "user", "content": past_user}, | |
| {"role": "assistant", "content": past_assistant}] | |
| messages.append({"role": "user", "content": context}) | |
| answer = self.llm.chat(messages) | |
| turns.append((f"Itération {self.state.iteration}. Rapport :\n{report[:1500]}", answer[:3000])) | |
| done = bool(re.search(r"^\s*DONE\s*$", answer, re.MULTILINE)) | |
| reads = re.findall(r"^READ:\s*(\S+)", answer, re.MULTILINE) | |
| blocks = self.edits.parse(answer) | |
| extra_files = self._read_files(reads) if reads else "" | |
| if blocks: | |
| try: | |
| changed = self.edits.apply(blocks) | |
| self.log(f"Édition appliquée : {', '.join(changed)}") | |
| if self.git.commit_all(f"agent: itération {self.state.iteration} ({', '.join(changed)[:120]})"): | |
| self.log("Commit créé.") | |
| except (EditError, AgentError) as exc: | |
| report = f"ÉCHEC D'ÉDITION : {exc}" | |
| self.log(report) | |
| continue | |
| elif not done and not reads: | |
| report = "Réponse sans bloc valide. Respecte strictement le format SEARCH/REPLACE." | |
| self.log(report) | |
| continue | |
| if reads and not blocks and not done: | |
| report = "Fichiers demandés fournis dans le contexte." | |
| continue | |
| result = self.tests.run() | |
| report = result.output or "(sortie vide)" | |
| self.log("Tests : " + ("OK" if result.ok else "ÉCHEC")) | |
| if not result.ok: | |
| extra_files = (extra_files + "\n\n" + self._read_files(self._files_from_report(report))).strip() | |
| self.state.last_message = report[-500:] | |
| self._save_state() | |
| if result.ok and done: | |
| self.state.status = "success" | |
| self.log("Tâche terminée avec succès.") | |
| self._save_state() | |
| return | |
| if self.state.status == "running": | |
| self.state.status = "stopped" | |
| self._save_state() | |
| # --------------------------------------------------------------------------- # | |
| # API HTTP (requise par HF Spaces) | |
| # --------------------------------------------------------------------------- # | |
| class TaskRequest(BaseModel): | |
| """Corps de requête pour lancer une tâche.""" | |
| task: str | |
| def create_app(agent: CodingAgent) -> FastAPI: | |
| """Construit l'application FastAPI exposant l'agent.""" | |
| app = FastAPI(title="Agent de codage autonome") | |
| def auth(token: Optional[str]) -> None: | |
| if agent.cfg.admin_token and token != agent.cfg.admin_token: | |
| raise HTTPException(status_code=401, detail="Jeton invalide") | |
| def root() -> Dict[str, object]: | |
| return {"service": "coding-agent-local", "model_ready": agent.llm.ready, **asdict(agent.state)} | |
| def status() -> Dict[str, object]: | |
| return {**asdict(agent.state), "model_ready": agent.llm.ready, "git": agent.git.status()} | |
| def logs() -> JSONResponse: | |
| return JSONResponse(list(agent.logs)) | |
| def task(req: TaskRequest, x_token: Optional[str] = Header(default=None)) -> Dict[str, str]: | |
| auth(x_token) | |
| try: | |
| agent.start(req.task) | |
| except AgentError as exc: | |
| raise HTTPException(status_code=409, detail=str(exc)) from exc | |
| return {"status": "démarré"} | |
| def stop(x_token: Optional[str] = Header(default=None)) -> Dict[str, str]: | |
| auth(x_token) | |
| agent.request_stop() | |
| return {"status": "arrêt demandé"} | |
| return app | |
| def main() -> None: | |
| """Point d'entrée : prépare l'agent, reprend le travail et sert l'API.""" | |
| cfg = Config() | |
| agent = CodingAgent(cfg) | |
| agent.resume_if_needed() | |
| uvicorn.run(create_app(agent), host="0.0.0.0", port=cfg.port, log_level="info") | |
| if __name__ == "__main__": | |
| main() |