File size: 31,407 Bytes
085b0d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
#!/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")


@dataclass(frozen=True)
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

    @property
    def workspace(self) -> Path:
        return self.data_dir / "workspace"

    @property
    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

    @staticmethod
    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
# --------------------------------------------------------------------------- #
@dataclass
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

    @staticmethod
    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:])

    @staticmethod
    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
# --------------------------------------------------------------------------- #
@dataclass
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()

    @staticmethod
    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"""


@dataclass
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)

    @staticmethod
    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")

    @app.get("/")
    def root() -> Dict[str, object]:
        return {"service": "coding-agent-local", "model_ready": agent.llm.ready, **asdict(agent.state)}

    @app.get("/status")
    def status() -> Dict[str, object]:
        return {**asdict(agent.state), "model_ready": agent.llm.ready, "git": agent.git.status()}

    @app.get("/logs")
    def logs() -> JSONResponse:
        return JSONResponse(list(agent.logs))

    @app.post("/task")
    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é"}

    @app.post("/stop")
    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()