Update app.py
Browse files
app.py
CHANGED
|
@@ -11,13 +11,10 @@ import secrets
|
|
| 11 |
import asyncio
|
| 12 |
import sqlite3
|
| 13 |
import tempfile
|
| 14 |
-
import shutil
|
| 15 |
-
import difflib
|
| 16 |
import subprocess
|
| 17 |
import sys
|
| 18 |
-
import traceback
|
| 19 |
from pathlib import Path
|
| 20 |
-
from typing import Dict, Any, Optional, List
|
| 21 |
from datetime import datetime
|
| 22 |
from contextlib import asynccontextmanager
|
| 23 |
import logging
|
|
@@ -25,12 +22,11 @@ from dataclasses import dataclass, field
|
|
| 25 |
|
| 26 |
import requests
|
| 27 |
import yaml
|
| 28 |
-
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends, Header
|
| 29 |
from fastapi.middleware.cors import CORSMiddleware
|
| 30 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 31 |
import numpy as np
|
| 32 |
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 33 |
-
import feedparser
|
| 34 |
from bs4 import BeautifulSoup
|
| 35 |
|
| 36 |
import torch
|
|
@@ -40,11 +36,9 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
| 40 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(message)s")
|
| 41 |
logger = logging.getLogger("nexus_v103")
|
| 42 |
|
| 43 |
-
# Detection materielle centralisee
|
| 44 |
_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 45 |
logger.info(f"Materiel detecte : {_DEVICE.upper()}" + (f" ({torch.cuda.get_device_name(0)})" if _DEVICE == "cuda" else " — pas de GPU disponible, bascule automatique sur CPU"))
|
| 46 |
|
| 47 |
-
# Plafond de connexions WS en attente
|
| 48 |
MAX_PENDING_AUTH = int(os.getenv("MAX_PENDING_AUTH", 50))
|
| 49 |
_auth_semaphore = asyncio.Semaphore(MAX_PENDING_AUTH)
|
| 50 |
|
|
@@ -163,8 +157,74 @@ class DBConnectionPool:
|
|
| 163 |
c.execute("PRAGMA journal_mode=WAL;")
|
| 164 |
c.execute("PRAGMA synchronous=NORMAL;")
|
| 165 |
c.executescript('''
|
| 166 |
-
CREATE TABLE IF NOT EXISTS source_states (
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
''')
|
| 169 |
conn.commit()
|
| 170 |
conn.close()
|
|
@@ -185,11 +245,130 @@ async def verify_any_token(authorization: str = Header(...)):
|
|
| 185 |
|
| 186 |
# =================== VECTOR STORE ===================
|
| 187 |
class VectorStore:
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
# =================== INFÉRENCE ===================
|
| 195 |
class LocalInference:
|
|
@@ -270,9 +449,9 @@ TOOLS = [
|
|
| 270 |
{"name": "run_python", "description": "Execute Python code", "parameters": {"code": {"type": "string"}}}
|
| 271 |
]
|
| 272 |
|
| 273 |
-
# =================== AGENT
|
| 274 |
class AgentV103:
|
| 275 |
-
MAX_NUDGES_PER_TASK = 3
|
| 276 |
_CONFUSION_MARKERS = (
|
| 277 |
"je ne peux pas", "je n'ai pas", "je ne suis pas capable",
|
| 278 |
"désolé", "je ne sais pas", "je ne trouve pas",
|
|
@@ -287,7 +466,6 @@ class AgentV103:
|
|
| 287 |
self.system_prompt = self._build_system_prompt()
|
| 288 |
|
| 289 |
def _build_system_prompt(self) -> str:
|
| 290 |
-
# Prompt ultra‑explicite avec personnalité "Expert Development Agent"
|
| 291 |
return """You are an EXPERT DEVELOPMENT AGENT in ADN NEXUS IDE.
|
| 292 |
You have been given access to the following TOOLS. You MUST use them to perform actions on the user's behalf.
|
| 293 |
NEVER claim you cannot access files or execute code – you have the tools to do so.
|
|
@@ -464,10 +642,8 @@ REMEMBER: You are an expert agent. You have the tools. Use them. Never say you c
|
|
| 464 |
messages.append({"role": "tool", "content": json.dumps(result)})
|
| 465 |
continue
|
| 466 |
|
| 467 |
-
# Si la réponse est textuelle et que la tâche n'est pas terminée, on force un nudge
|
| 468 |
if nudges_used < self.MAX_NUDGES_PER_TASK:
|
| 469 |
nudges_used += 1
|
| 470 |
-
# On ajoute un message utilisateur très direct pour contraindre le format JSON
|
| 471 |
await websocket.send_json({
|
| 472 |
"type": "thinking",
|
| 473 |
"iteration": i + 1,
|
|
@@ -485,7 +661,6 @@ REMEMBER: You are an expert agent. You have the tools. Use them. Never say you c
|
|
| 485 |
})
|
| 486 |
continue
|
| 487 |
|
| 488 |
-
# Si on a dépassé les nudges, on considère que l'agent est bloqué et on le force à répondre en texte (mais cela pourrait être un échec)
|
| 489 |
await websocket.send_json({"type": "complete", "result": response})
|
| 490 |
return {"success": True, "result": response}
|
| 491 |
|
|
@@ -493,7 +668,6 @@ REMEMBER: You are an expert agent. You have the tools. Use them. Never say you c
|
|
| 493 |
return {"success": False, "error": "Max iterations"}
|
| 494 |
|
| 495 |
def _parse_tool_call(self, text):
|
| 496 |
-
# On cherche une structure JSON complète contenant "tool"
|
| 497 |
decoder = json.JSONDecoder()
|
| 498 |
start = 0
|
| 499 |
while True:
|
|
@@ -523,7 +697,6 @@ REMEMBER: You are an expert agent. You have the tools. Use them. Never say you c
|
|
| 523 |
result = {"success": False, "error": f"Tool {name} unknown"}
|
| 524 |
return result
|
| 525 |
|
| 526 |
-
# === MEMOIRE PERSISTANTE ===
|
| 527 |
async def _save_task_memory(self, task: str, result: Dict):
|
| 528 |
if not Config.MEMORY_ENABLED:
|
| 529 |
return
|
|
@@ -629,7 +802,6 @@ class Sandbox:
|
|
| 629 |
Path(temp_path).unlink(missing_ok=True)
|
| 630 |
|
| 631 |
async def run_command(self, args: list, timeout=30):
|
| 632 |
-
# Pour pytest, flake8, etc.
|
| 633 |
try:
|
| 634 |
proc = await asyncio.create_subprocess_exec(
|
| 635 |
*args,
|
|
@@ -648,17 +820,589 @@ class Sandbox:
|
|
| 648 |
|
| 649 |
sandbox = Sandbox()
|
| 650 |
|
| 651 |
-
# =================== TELEMETRY
|
| 652 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
|
| 654 |
# =================== AGENT INSTANCIATION ===================
|
| 655 |
agent = AgentV103(inference, TOOLS)
|
| 656 |
|
| 657 |
-
# =================== CLIENT HTML
|
| 658 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 659 |
|
| 660 |
# =================== FASTAPI APP ===================
|
| 661 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
|
| 663 |
# =================== LANCEMENT ===================
|
| 664 |
if __name__ == "__main__":
|
|
|
|
| 11 |
import asyncio
|
| 12 |
import sqlite3
|
| 13 |
import tempfile
|
|
|
|
|
|
|
| 14 |
import subprocess
|
| 15 |
import sys
|
|
|
|
| 16 |
from pathlib import Path
|
| 17 |
+
from typing import Dict, Any, Optional, List
|
| 18 |
from datetime import datetime
|
| 19 |
from contextlib import asynccontextmanager
|
| 20 |
import logging
|
|
|
|
| 22 |
|
| 23 |
import requests
|
| 24 |
import yaml
|
| 25 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends, Header
|
| 26 |
from fastapi.middleware.cors import CORSMiddleware
|
| 27 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 28 |
import numpy as np
|
| 29 |
from sentence_transformers import SentenceTransformer, CrossEncoder
|
|
|
|
| 30 |
from bs4 import BeautifulSoup
|
| 31 |
|
| 32 |
import torch
|
|
|
|
| 36 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(message)s")
|
| 37 |
logger = logging.getLogger("nexus_v103")
|
| 38 |
|
|
|
|
| 39 |
_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
logger.info(f"Materiel detecte : {_DEVICE.upper()}" + (f" ({torch.cuda.get_device_name(0)})" if _DEVICE == "cuda" else " — pas de GPU disponible, bascule automatique sur CPU"))
|
| 41 |
|
|
|
|
| 42 |
MAX_PENDING_AUTH = int(os.getenv("MAX_PENDING_AUTH", 50))
|
| 43 |
_auth_semaphore = asyncio.Semaphore(MAX_PENDING_AUTH)
|
| 44 |
|
|
|
|
| 157 |
c.execute("PRAGMA journal_mode=WAL;")
|
| 158 |
c.execute("PRAGMA synchronous=NORMAL;")
|
| 159 |
c.executescript('''
|
| 160 |
+
CREATE TABLE IF NOT EXISTS source_states (
|
| 161 |
+
url TEXT PRIMARY KEY, last_modified TEXT, last_scraped TEXT,
|
| 162 |
+
status TEXT, interval_minutes REAL DEFAULT 60, is_rss INTEGER DEFAULT 0,
|
| 163 |
+
source_metadata TEXT DEFAULT '{}', active INTEGER DEFAULT 1
|
| 164 |
+
);
|
| 165 |
+
CREATE TABLE IF NOT EXISTS encyclopedia_chunks (
|
| 166 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT,
|
| 167 |
+
metadata TEXT DEFAULT '{}', embedding BLOB, source_url TEXT,
|
| 168 |
+
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 169 |
+
);
|
| 170 |
+
CREATE TABLE IF NOT EXISTS harbor_memory (
|
| 171 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, task TEXT,
|
| 172 |
+
hypothesis TEXT, action TEXT, observation TEXT, status TEXT,
|
| 173 |
+
feedback TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 174 |
+
);
|
| 175 |
+
CREATE TABLE IF NOT EXISTS cognitive_logs (
|
| 176 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, question TEXT,
|
| 177 |
+
prompt TEXT, answer TEXT, status TEXT, feedback TEXT,
|
| 178 |
+
chunks_used TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 179 |
+
);
|
| 180 |
+
CREATE TABLE IF NOT EXISTS scrape_queue (
|
| 181 |
+
url TEXT PRIMARY KEY, priority INTEGER DEFAULT 0,
|
| 182 |
+
added_at TEXT DEFAULT CURRENT_TIMESTAMP, status TEXT DEFAULT 'pending'
|
| 183 |
+
);
|
| 184 |
+
CREATE TABLE IF NOT EXISTS task_tracker (
|
| 185 |
+
task_id TEXT PRIMARY KEY, task_type TEXT, payload TEXT,
|
| 186 |
+
status TEXT DEFAULT 'pending', created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
| 187 |
+
completed_at TEXT, error_message TEXT
|
| 188 |
+
);
|
| 189 |
+
CREATE TABLE IF NOT EXISTS sessions (
|
| 190 |
+
id TEXT PRIMARY KEY, created_at TEXT, project_path TEXT
|
| 191 |
+
);
|
| 192 |
+
CREATE TABLE IF NOT EXISTS files (
|
| 193 |
+
id INTEGER PRIMARY KEY, session_id TEXT, path TEXT,
|
| 194 |
+
content TEXT, language TEXT, last_modified TEXT
|
| 195 |
+
);
|
| 196 |
+
CREATE TABLE IF NOT EXISTS operations (
|
| 197 |
+
id INTEGER PRIMARY KEY, session_id TEXT, type TEXT,
|
| 198 |
+
file_path TEXT, diff TEXT, status TEXT, error TEXT,
|
| 199 |
+
created_at TEXT, applied_at TEXT
|
| 200 |
+
);
|
| 201 |
+
CREATE TABLE IF NOT EXISTS agent_runs (
|
| 202 |
+
id INTEGER PRIMARY KEY, session_id TEXT, task TEXT,
|
| 203 |
+
tool_calls TEXT, result TEXT, status TEXT, created_at TEXT
|
| 204 |
+
);
|
| 205 |
+
CREATE TABLE IF NOT EXISTS telemetry (
|
| 206 |
+
id INTEGER PRIMARY KEY, execution_id TEXT, file_path TEXT,
|
| 207 |
+
event_type TEXT, line_no INTEGER, function_name TEXT,
|
| 208 |
+
locals_snapshot TEXT, timestamp REAL
|
| 209 |
+
);
|
| 210 |
+
CREATE TABLE IF NOT EXISTS symbols (
|
| 211 |
+
id TEXT PRIMARY KEY, name TEXT, type TEXT, language TEXT,
|
| 212 |
+
file_path TEXT, line_start INTEGER, line_end INTEGER,
|
| 213 |
+
signature TEXT, docstring TEXT
|
| 214 |
+
);
|
| 215 |
+
CREATE TABLE IF NOT EXISTS relationships (
|
| 216 |
+
id INTEGER PRIMARY KEY, source_id TEXT, target_id TEXT,
|
| 217 |
+
relation_type TEXT, confidence REAL
|
| 218 |
+
);
|
| 219 |
+
CREATE TABLE IF NOT EXISTS agent_memory (
|
| 220 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 221 |
+
task TEXT,
|
| 222 |
+
result TEXT,
|
| 223 |
+
success INTEGER,
|
| 224 |
+
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 225 |
+
);
|
| 226 |
+
CREATE INDEX IF NOT EXISTS idx_agent_memory_task ON agent_memory(task);
|
| 227 |
+
CREATE INDEX IF NOT EXISTS idx_agent_memory_created ON agent_memory(created_at);
|
| 228 |
''')
|
| 229 |
conn.commit()
|
| 230 |
conn.close()
|
|
|
|
| 245 |
|
| 246 |
# =================== VECTOR STORE ===================
|
| 247 |
class VectorStore:
|
| 248 |
+
def __init__(self):
|
| 249 |
+
self.encoder = None
|
| 250 |
+
self.chunks = []
|
| 251 |
+
self.embeddings = None
|
| 252 |
+
self._lock = asyncio.Lock()
|
| 253 |
+
self._load_encoder()
|
| 254 |
+
|
| 255 |
+
def _load_encoder(self):
|
| 256 |
+
try:
|
| 257 |
+
self.encoder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2', device=Config.DEVICE)
|
| 258 |
+
logger.info(f"Encodeur charge sur {Config.DEVICE}")
|
| 259 |
+
except Exception as e:
|
| 260 |
+
logger.warning(f"Encodeur desactive: {e}")
|
| 261 |
|
| 262 |
+
async def load_from_db(self):
|
| 263 |
+
rows = await db_pool.query("SELECT id, content, metadata, source_url FROM encyclopedia_chunks")
|
| 264 |
+
async with self._lock:
|
| 265 |
+
self.chunks = []
|
| 266 |
+
for r in rows:
|
| 267 |
+
self.chunks.append({
|
| 268 |
+
"id": r["id"], "content": r["content"],
|
| 269 |
+
"metadata": json.loads(r["metadata"] or "{}"),
|
| 270 |
+
"source_url": r["source_url"]
|
| 271 |
+
})
|
| 272 |
+
if self.chunks and self.encoder:
|
| 273 |
+
texts = [c["content"] for c in self.chunks]
|
| 274 |
+
loop = asyncio.get_running_loop()
|
| 275 |
+
self.embeddings = await loop.run_in_executor(None, self.encoder.encode, texts, False)
|
| 276 |
+
logger.info(f"{len(self.chunks)} chunks charges")
|
| 277 |
+
|
| 278 |
+
async def add(self, content, metadata=None, source_url=None):
|
| 279 |
+
chunker = TextChunker()
|
| 280 |
+
text_chunks = chunker.chunk_text(content)
|
| 281 |
+
row_ids = []
|
| 282 |
+
async with self._lock:
|
| 283 |
+
for chunk_text in text_chunks:
|
| 284 |
+
if self.encoder:
|
| 285 |
+
loop = asyncio.get_running_loop()
|
| 286 |
+
emb = await loop.run_in_executor(None, self.encoder.encode, [chunk_text])
|
| 287 |
+
emb = emb[0]
|
| 288 |
+
row_id = await db_pool.execute(
|
| 289 |
+
"INSERT INTO encyclopedia_chunks (content, metadata, source_url, embedding) VALUES (?, ?, ?, ?)",
|
| 290 |
+
(chunk_text, json.dumps(metadata or {}), source_url, emb.tobytes())
|
| 291 |
+
)
|
| 292 |
+
if self.embeddings is None:
|
| 293 |
+
self.embeddings = emb.reshape(1, -1)
|
| 294 |
+
else:
|
| 295 |
+
self.embeddings = np.vstack([self.embeddings, emb])
|
| 296 |
+
else:
|
| 297 |
+
row_id = await db_pool.execute(
|
| 298 |
+
"INSERT INTO encyclopedia_chunks (content, metadata, source_url) VALUES (?, ?, ?)",
|
| 299 |
+
(chunk_text, json.dumps(metadata or {}), source_url)
|
| 300 |
+
)
|
| 301 |
+
self.chunks.append({"id": row_id, "content": chunk_text, "metadata": metadata or {}, "source_url": source_url})
|
| 302 |
+
row_ids.append(row_id)
|
| 303 |
+
return row_ids
|
| 304 |
+
|
| 305 |
+
async def search(self, query, top_k=5):
|
| 306 |
+
async with self._lock:
|
| 307 |
+
if not self.chunks:
|
| 308 |
+
return []
|
| 309 |
+
if self.encoder and self.embeddings is not None:
|
| 310 |
+
loop = asyncio.get_running_loop()
|
| 311 |
+
q_emb = await loop.run_in_executor(None, self.encoder.encode, [query])
|
| 312 |
+
q_emb = q_emb[0]
|
| 313 |
+
norms = np.linalg.norm(self.embeddings, axis=1) * np.linalg.norm(q_emb) + 1e-8
|
| 314 |
+
sim = np.dot(self.embeddings, q_emb) / norms
|
| 315 |
+
idx = np.argsort(sim)[::-1][:top_k]
|
| 316 |
+
return [{**self.chunks[i].copy(), "score": float(sim[i])} for i in idx]
|
| 317 |
+
q_words = set(query.lower().split())
|
| 318 |
+
scored = []
|
| 319 |
+
for c in self.chunks:
|
| 320 |
+
cw = set(c["content"].lower().split())
|
| 321 |
+
scored.append((len(q_words & cw) / max(len(q_words), 1), c))
|
| 322 |
+
scored.sort(reverse=True)
|
| 323 |
+
return [c.copy() for _, c in scored[:top_k]]
|
| 324 |
+
|
| 325 |
+
vector_store = VectorStore()
|
| 326 |
+
|
| 327 |
+
# =================== CHUNKING ===================
|
| 328 |
+
class TextChunker:
|
| 329 |
+
@staticmethod
|
| 330 |
+
def chunk_text(text, chunk_size=Config.CHUNK_SIZE, overlap=Config.CHUNK_OVERLAP):
|
| 331 |
+
sentences = re.split(r'(?<=[.!?])\s+', text)
|
| 332 |
+
chunks, current_chunk, current_length = [], [], 0
|
| 333 |
+
for sentence in sentences:
|
| 334 |
+
sentence_len = len(sentence)
|
| 335 |
+
if current_length + sentence_len > chunk_size and current_chunk:
|
| 336 |
+
chunks.append(" ".join(current_chunk))
|
| 337 |
+
overlap_text = " ".join(current_chunk[-2:]) if len(current_chunk) > 2 else ""
|
| 338 |
+
current_chunk = [overlap_text, sentence] if overlap_text else [sentence]
|
| 339 |
+
current_length = len(overlap_text) + sentence_len if overlap_text else sentence_len
|
| 340 |
+
else:
|
| 341 |
+
current_chunk.append(sentence)
|
| 342 |
+
current_length += sentence_len + 1
|
| 343 |
+
if current_chunk:
|
| 344 |
+
chunks.append(" ".join(current_chunk))
|
| 345 |
+
return chunks
|
| 346 |
+
|
| 347 |
+
# =================== RERANKER ===================
|
| 348 |
+
class Reranker:
|
| 349 |
+
def __init__(self):
|
| 350 |
+
self.model = None
|
| 351 |
+
try:
|
| 352 |
+
self.model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2', device=Config.DEVICE)
|
| 353 |
+
logger.info(f"Cross-Encoder charge sur {Config.DEVICE}")
|
| 354 |
+
except Exception as e:
|
| 355 |
+
logger.warning(f"Cross-Encoder desactive: {e}")
|
| 356 |
+
|
| 357 |
+
async def rerank(self, query, chunks, top_k=5):
|
| 358 |
+
if not chunks or self.model is None:
|
| 359 |
+
return chunks[:top_k]
|
| 360 |
+
pairs = [(query, c.get("content", "")) for c in chunks]
|
| 361 |
+
try:
|
| 362 |
+
loop = asyncio.get_running_loop()
|
| 363 |
+
scores = await loop.run_in_executor(None, self.model.predict, pairs)
|
| 364 |
+
for i, c in enumerate(chunks):
|
| 365 |
+
c["rerank_score"] = float(scores[i])
|
| 366 |
+
return sorted(chunks, key=lambda x: x.get("rerank_score", 0), reverse=True)[:top_k]
|
| 367 |
+
except Exception as e:
|
| 368 |
+
logger.error(f"Reranking echoue: {e}")
|
| 369 |
+
return chunks[:top_k]
|
| 370 |
+
|
| 371 |
+
reranker = Reranker()
|
| 372 |
|
| 373 |
# =================== INFÉRENCE ===================
|
| 374 |
class LocalInference:
|
|
|
|
| 449 |
{"name": "run_python", "description": "Execute Python code", "parameters": {"code": {"type": "string"}}}
|
| 450 |
]
|
| 451 |
|
| 452 |
+
# =================== AGENT EXPERT ===================
|
| 453 |
class AgentV103:
|
| 454 |
+
MAX_NUDGES_PER_TASK = 3
|
| 455 |
_CONFUSION_MARKERS = (
|
| 456 |
"je ne peux pas", "je n'ai pas", "je ne suis pas capable",
|
| 457 |
"désolé", "je ne sais pas", "je ne trouve pas",
|
|
|
|
| 466 |
self.system_prompt = self._build_system_prompt()
|
| 467 |
|
| 468 |
def _build_system_prompt(self) -> str:
|
|
|
|
| 469 |
return """You are an EXPERT DEVELOPMENT AGENT in ADN NEXUS IDE.
|
| 470 |
You have been given access to the following TOOLS. You MUST use them to perform actions on the user's behalf.
|
| 471 |
NEVER claim you cannot access files or execute code – you have the tools to do so.
|
|
|
|
| 642 |
messages.append({"role": "tool", "content": json.dumps(result)})
|
| 643 |
continue
|
| 644 |
|
|
|
|
| 645 |
if nudges_used < self.MAX_NUDGES_PER_TASK:
|
| 646 |
nudges_used += 1
|
|
|
|
| 647 |
await websocket.send_json({
|
| 648 |
"type": "thinking",
|
| 649 |
"iteration": i + 1,
|
|
|
|
| 661 |
})
|
| 662 |
continue
|
| 663 |
|
|
|
|
| 664 |
await websocket.send_json({"type": "complete", "result": response})
|
| 665 |
return {"success": True, "result": response}
|
| 666 |
|
|
|
|
| 668 |
return {"success": False, "error": "Max iterations"}
|
| 669 |
|
| 670 |
def _parse_tool_call(self, text):
|
|
|
|
| 671 |
decoder = json.JSONDecoder()
|
| 672 |
start = 0
|
| 673 |
while True:
|
|
|
|
| 697 |
result = {"success": False, "error": f"Tool {name} unknown"}
|
| 698 |
return result
|
| 699 |
|
|
|
|
| 700 |
async def _save_task_memory(self, task: str, result: Dict):
|
| 701 |
if not Config.MEMORY_ENABLED:
|
| 702 |
return
|
|
|
|
| 802 |
Path(temp_path).unlink(missing_ok=True)
|
| 803 |
|
| 804 |
async def run_command(self, args: list, timeout=30):
|
|
|
|
| 805 |
try:
|
| 806 |
proc = await asyncio.create_subprocess_exec(
|
| 807 |
*args,
|
|
|
|
| 820 |
|
| 821 |
sandbox = Sandbox()
|
| 822 |
|
| 823 |
+
# =================== TELEMETRY & GIT & KNOWLEDGE ===================
|
| 824 |
+
class RuntimeTelemetry:
|
| 825 |
+
def __init__(self, workspace):
|
| 826 |
+
self.workspace = workspace
|
| 827 |
+
async def run_with_trace(self, code, filename="<script>"):
|
| 828 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
|
| 829 |
+
f.write(code)
|
| 830 |
+
temp_path = f.name
|
| 831 |
+
try:
|
| 832 |
+
proc = await asyncio.create_subprocess_exec(
|
| 833 |
+
sys.executable, '-m', 'trace', '--trace', temp_path,
|
| 834 |
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
| 835 |
+
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
|
| 836 |
+
return {"success": proc.returncode == 0,
|
| 837 |
+
"stdout": stdout.decode('utf-8', errors='replace'),
|
| 838 |
+
"stderr": stderr.decode('utf-8', errors='replace')}
|
| 839 |
+
except Exception as e:
|
| 840 |
+
return {"success": False, "error": str(e)}
|
| 841 |
+
finally:
|
| 842 |
+
Path(temp_path).unlink(missing_ok=True)
|
| 843 |
+
|
| 844 |
+
telemetry = RuntimeTelemetry(Config.WORKSPACE_ROOT)
|
| 845 |
+
|
| 846 |
+
class APIContractParser:
|
| 847 |
+
@staticmethod
|
| 848 |
+
def parse_openapi(path):
|
| 849 |
+
content = Path(path).read_text()
|
| 850 |
+
spec = yaml.safe_load(content) if path.suffix in ('.yaml', '.yml') else json.loads(content)
|
| 851 |
+
endpoints = []
|
| 852 |
+
for p, methods in spec.get('paths', {}).items():
|
| 853 |
+
for m, d in methods.items():
|
| 854 |
+
if m in ('get', 'post', 'put', 'patch', 'delete'):
|
| 855 |
+
endpoints.append({"path": p, "method": m.upper(), "operation_id": d.get('operationId')})
|
| 856 |
+
return {"title": spec.get('info', {}).get('title'), "version": spec.get('info', {}).get('version'), "endpoints": endpoints}
|
| 857 |
+
|
| 858 |
+
contract_parser = APIContractParser()
|
| 859 |
+
|
| 860 |
+
class GitGraphAnalyzer:
|
| 861 |
+
def __init__(self, repo_path):
|
| 862 |
+
self.repo = repo_path
|
| 863 |
+
if not (self.repo / '.git').exists():
|
| 864 |
+
raise ValueError("Not a git repository")
|
| 865 |
+
def get_commit_graph(self, max_commits=20):
|
| 866 |
+
try:
|
| 867 |
+
result = subprocess.run(['git', '-C', str(self.repo), 'log', f'-{max_commits}', '--format=%H|%s|%ad', '--date=short'],
|
| 868 |
+
capture_output=True, text=True)
|
| 869 |
+
commits = []
|
| 870 |
+
for line in result.stdout.strip().split('\n'):
|
| 871 |
+
if '|' in line:
|
| 872 |
+
parts = line.split('|', 2)
|
| 873 |
+
commits.append({"hash": parts[0], "message": parts[1], "date": parts[2]})
|
| 874 |
+
return commits
|
| 875 |
+
except Exception:
|
| 876 |
+
return []
|
| 877 |
+
|
| 878 |
+
git_analyzer = None
|
| 879 |
+
try:
|
| 880 |
+
git_dir = Config.WORKSPACE_ROOT / '.git'
|
| 881 |
+
if git_dir.exists() and git_dir.is_dir():
|
| 882 |
+
git_analyzer = GitGraphAnalyzer(Config.WORKSPACE_ROOT)
|
| 883 |
+
logger.info("Git analyzer initialise")
|
| 884 |
+
else:
|
| 885 |
+
logger.info("Pas de repo Git detecte")
|
| 886 |
+
except Exception as e:
|
| 887 |
+
logger.warning(f"Git analyzer non disponible: {e}")
|
| 888 |
+
|
| 889 |
+
class KnowledgeGraphLoader:
|
| 890 |
+
def __init__(self, db_path="/tmp/kg.db"):
|
| 891 |
+
self.db_path = db_path
|
| 892 |
+
conn = sqlite3.connect(db_path)
|
| 893 |
+
c = conn.cursor()
|
| 894 |
+
c.executescript('''
|
| 895 |
+
CREATE TABLE IF NOT EXISTS symbols (id TEXT PRIMARY KEY, name TEXT, type TEXT, file_path TEXT);
|
| 896 |
+
CREATE TABLE IF NOT EXISTS relationships (id INTEGER PRIMARY KEY, source_id TEXT, target_id TEXT, relation_type TEXT);
|
| 897 |
+
''')
|
| 898 |
+
conn.commit()
|
| 899 |
+
conn.close()
|
| 900 |
+
def query_symbol(self, name):
|
| 901 |
+
conn = sqlite3.connect(self.db_path)
|
| 902 |
+
conn.row_factory = sqlite3.Row
|
| 903 |
+
c = conn.cursor()
|
| 904 |
+
c.execute("SELECT * FROM symbols WHERE name LIKE ?", (f'%{name}%',))
|
| 905 |
+
rows = c.fetchall()
|
| 906 |
+
conn.close()
|
| 907 |
+
return [dict(r) for r in rows]
|
| 908 |
+
|
| 909 |
+
kg_loader = KnowledgeGraphLoader()
|
| 910 |
+
|
| 911 |
+
class KnowledgeUnifier:
|
| 912 |
+
def __init__(self):
|
| 913 |
+
self.kb = {"symbols": {}, "runtime": {}, "contracts": {}, "history": {}}
|
| 914 |
+
def ingest_lsp_data(self, data):
|
| 915 |
+
for sym in data:
|
| 916 |
+
key = f"lsp:{sym.get('file_path', '')}:{sym.get('name', '')}"
|
| 917 |
+
self.kb["symbols"][key] = sym
|
| 918 |
+
def generate_context_for_llm(self, task):
|
| 919 |
+
parts = []
|
| 920 |
+
if self.kb["symbols"]:
|
| 921 |
+
parts.append("## Symbols")
|
| 922 |
+
for k, v in list(self.kb["symbols"].items())[:5]:
|
| 923 |
+
parts.append(f"- {v.get('name', '')} ({v.get('type', '')})")
|
| 924 |
+
return "\n".join(parts) if parts else "No context available"
|
| 925 |
+
|
| 926 |
+
unifier = KnowledgeUnifier()
|
| 927 |
|
| 928 |
# =================== AGENT INSTANCIATION ===================
|
| 929 |
agent = AgentV103(inference, TOOLS)
|
| 930 |
|
| 931 |
+
# =================== CLIENT HTML ===================
|
| 932 |
+
IDE_HTML = """<!DOCTYPE html>
|
| 933 |
+
<html lang="fr">
|
| 934 |
+
<head>
|
| 935 |
+
<meta charset="UTF-8">
|
| 936 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 937 |
+
<title>ADN NEXUS V10.3.2 — Agentic IDE</title>
|
| 938 |
+
<style>
|
| 939 |
+
*{margin:0;padding:0;box-sizing:border-box}
|
| 940 |
+
:root{--bg:#0d1117;--bg2:#161b22;--bg3:#21262d;--border:#30363d;--text:#c9d1d9;--text2:#8b949e;--accent:#58a6ff;--green:#3fb950;--red:#f85149;--yellow:#d29922}
|
| 941 |
+
body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--bg);color:var(--text);height:100vh;overflow:hidden}
|
| 942 |
+
|
| 943 |
+
#login{position:fixed;inset:0;background:var(--bg);display:flex;align-items:center;justify-content:center;z-index:1000}
|
| 944 |
+
#login .box{background:var(--bg2);border:1px solid var(--border);border-radius:10px;padding:32px;width:320px;text-align:center}
|
| 945 |
+
#login h1{font-size:16px;color:var(--accent);margin-bottom:4px}
|
| 946 |
+
#login p{font-size:12px;color:var(--text2);margin-bottom:20px}
|
| 947 |
+
#login input{width:100%;padding:10px;background:var(--bg3);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;margin-bottom:12px;outline:none}
|
| 948 |
+
#login input:focus{border-color:var(--accent)}
|
| 949 |
+
#login button{width:100%;padding:10px;background:var(--accent);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px}
|
| 950 |
+
#login button:hover{opacity:.9}
|
| 951 |
+
#login .err{color:var(--red);font-size:12px;margin-top:10px;min-height:16px}
|
| 952 |
+
#app{display:none}
|
| 953 |
+
|
| 954 |
+
.app{display:grid;grid-template-columns:250px 1fr 350px;grid-template-rows:40px 1fr 180px;height:100vh;gap:1px;background:var(--border)}
|
| 955 |
+
.header{grid-column:1/-1;background:var(--bg2);display:flex;align-items:center;padding:0 16px;gap:16px}
|
| 956 |
+
.logo{font-weight:bold;color:var(--accent)}.conn{margin-left:auto;display:flex;align-items:center;gap:8px;font-size:12px}
|
| 957 |
+
.dot{width:8px;height:8px;border-radius:50%;background:var(--red)}.dot.on{background:var(--green)}
|
| 958 |
+
.sidebar{background:var(--bg);overflow-y:auto;padding:8px}
|
| 959 |
+
.tree-item{padding:4px 8px;cursor:pointer;border-radius:4px;display:flex;align-items:center;gap:6px;font-size:13px}
|
| 960 |
+
.tree-item:hover{background:var(--bg3)}.tree-item.on{background:var(--accent);color:#fff}
|
| 961 |
+
.editor{background:var(--bg);display:flex;flex-direction:column;position:relative}
|
| 962 |
+
.tabs{display:flex;background:var(--bg2);border-bottom:1px solid var(--border);overflow-x:auto}
|
| 963 |
+
.tab{padding:8px 16px;cursor:pointer;border-right:1px solid var(--border);font-size:12px;display:flex;align-items:center;gap:8px;white-space:nowrap}
|
| 964 |
+
.tab.on{background:var(--bg);border-bottom:2px solid var(--accent)}
|
| 965 |
+
#code{flex:1;padding:16px;font-family:Consolas,monospace;font-size:14px;background:var(--bg);color:var(--text);border:none;outline:none;resize:none;white-space:pre;overflow:auto;line-height:1.6}
|
| 966 |
+
.diff{position:absolute;top:0;left:0;right:0;bottom:0;background:var(--bg);display:none;flex-direction:column;z-index:100}
|
| 967 |
+
.diff.show{display:flex}
|
| 968 |
+
.diff-h{padding:12px 16px;background:var(--bg2);border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
|
| 969 |
+
.diff-c{flex:1;overflow-y:auto;padding:16px;font-family:Consolas,monospace;font-size:13px;line-height:1.6}
|
| 970 |
+
.dl{padding:2px 8px;white-space:pre}.dl.rm{background:rgba(248,81,73,.2)}.dl.add{background:rgba(63,185,80,.2)}.dl.hd{color:var(--text2)}
|
| 971 |
+
.agent{background:var(--bg);border-left:1px solid var(--border);display:flex;flex-direction:column}
|
| 972 |
+
.agent-h{padding:12px;background:var(--bg2);border-bottom:1px solid var(--border);font-weight:bold;display:flex;align-items:center;gap:8px}
|
| 973 |
+
.chat{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:12px}
|
| 974 |
+
.msg{padding:10px 12px;border-radius:8px;font-size:13px;line-height:1.5;max-width:100%}
|
| 975 |
+
.msg.u{background:var(--bg3);align-self:flex-end}.msg.a{background:var(--bg2);border-left:3px solid var(--accent)}
|
| 976 |
+
.msg.t{background:var(--bg2);border-left:3px solid var(--yellow);font-family:monospace;font-size:11px}
|
| 977 |
+
.msg.e{border-left:3px solid var(--red)}
|
| 978 |
+
.inp{padding:12px;border-top:1px solid var(--border);display:flex;gap:8px}
|
| 979 |
+
.inp textarea{flex:1;background:var(--bg2);border:1px solid var(--border);border-radius:6px;padding:8px;color:var(--text);font-size:13px;resize:none;height:60px}
|
| 980 |
+
.btn{padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px}
|
| 981 |
+
.btn:hover{opacity:.9}.btn2{background:var(--bg3)}
|
| 982 |
+
.term{grid-column:1/-1;background:var(--bg);border-top:1px solid var(--border);display:flex;flex-direction:column}
|
| 983 |
+
.term-h{padding:6px 12px;background:var(--bg2);display:flex;gap:16px;font-size:12px}
|
| 984 |
+
.term-t{cursor:pointer;padding:2px 8px}.term-t.on{border-bottom:2px solid var(--accent)}
|
| 985 |
+
.term-c{flex:1;padding:8px 12px;font-family:Consolas,monospace;font-size:12px;overflow-y:auto;white-space:pre-wrap;color:var(--text2)}
|
| 986 |
+
.term-l{margin:2px 0}.term-l.out{color:var(--text)}.term-l.err{color:var(--red)}.term-l.inf{color:var(--yellow)}
|
| 987 |
+
.qa{position:absolute;bottom:200px;right:360px;display:flex;gap:8px;padding:8px}
|
| 988 |
+
.qb{padding:6px 12px;background:var(--bg2);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:11px;color:var(--text2)}
|
| 989 |
+
.qb:hover{border-color:var(--accent);color:var(--accent)}
|
| 990 |
+
</style>
|
| 991 |
+
</head>
|
| 992 |
+
<body>
|
| 993 |
+
|
| 994 |
+
<div id="login">
|
| 995 |
+
<div class="box">
|
| 996 |
+
<h1>ADN NEXUS V10.3.2</h1>
|
| 997 |
+
<p>Entrez votre token d'acces pour ouvrir l'IDE</p>
|
| 998 |
+
<input id="tokinp" type="password" placeholder="Token" autocomplete="off">
|
| 999 |
+
<button onclick="tryLogin()">Se connecter</button>
|
| 1000 |
+
<div class="err" id="loginerr"></div>
|
| 1001 |
+
</div>
|
| 1002 |
+
</div>
|
| 1003 |
+
|
| 1004 |
+
<div id="app">
|
| 1005 |
+
<div class="app">
|
| 1006 |
+
<div class="header"><span class="logo">ADN NEXUS V10.3.2</span><span style="color:var(--text2);font-size:12px">Agentic IDE</span><div class="conn"><span class="dot" id="dot"></span><span id="cst">Disconnected</span></div></div>
|
| 1007 |
+
<div class="sidebar"><div style="padding:8px;color:var(--text2);font-size:11px;text-transform:uppercase">Explorer</div><div id="tree">Loading...</div><hr style="border-color:var(--border);margin:15px 0"><div style="font-size:12px;color:var(--text2)"><button class="btn btn2" onclick="refreshFiles()">Sync</button> <button class="btn btn2" onclick="runTelemetry()">Telemetry</button></div></div>
|
| 1008 |
+
<div class="editor"><div class="tabs" id="tabs"></div><textarea id="code" spellcheck="false"></textarea><div class="diff" id="diff"><div class="diff-h"><span id="dtit">Changes</span><div style="display:flex;gap:8px"><button class="btn btn2" onclick="rejDiff()">Reject</button><button class="btn" onclick="accDiff()">Accept</button></div></div><div class="diff-c" id="diffc"></div></div></div>
|
| 1009 |
+
<div class="agent"><div class="agent-h"><span>Agent</span><label style="margin-left:auto;font-size:11px;color:var(--text2);display:flex;align-items:center;gap:4px;cursor:pointer"><input type="checkbox" id="reasonchk" style="cursor:pointer">Raisonnement (2x plus lent)</label><button class="btn btn2" style="padding:4px 8px;font-size:11px" onclick="clearChat()">Clear</button></div><div class="chat" id="chat"></div><div class="inp"><textarea id="ainp" placeholder="Describe what to build..."></textarea><button class="btn" onclick="sendTask()">Run</button></div></div>
|
| 1010 |
+
<div class="term"><div class="term-h"><span class="term-t on">Terminal</span><span class="term-t">Output</span><span class="term-t">Problems</span></div><div class="term-c" id="term"></div></div>
|
| 1011 |
+
</div>
|
| 1012 |
+
<div class="qa"><button class="qb" onclick="qTest()">Tests</button><button class="qb" onclick="qFix()">Fix</button><button class="qb" onclick="qExp()">Explain</button></div>
|
| 1013 |
+
</div>
|
| 1014 |
+
|
| 1015 |
+
<script>
|
| 1016 |
+
let sessionToken = null;
|
| 1017 |
+
let ws = null, curFile = null;
|
| 1018 |
+
|
| 1019 |
+
function tryLogin(){
|
| 1020 |
+
const val = document.getElementById('tokinp').value.trim();
|
| 1021 |
+
if (!val) return;
|
| 1022 |
+
document.getElementById('loginerr').textContent = '';
|
| 1023 |
+
sessionToken = val;
|
| 1024 |
+
connectWs();
|
| 1025 |
+
}
|
| 1026 |
+
|
| 1027 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 1028 |
+
document.getElementById('tokinp').addEventListener('keydown', e => {
|
| 1029 |
+
if (e.key === 'Enter') tryLogin();
|
| 1030 |
+
});
|
| 1031 |
+
});
|
| 1032 |
+
|
| 1033 |
+
function connectWs(){
|
| 1034 |
+
const WS_URL = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws';
|
| 1035 |
+
ws = new WebSocket(WS_URL);
|
| 1036 |
+
let authenticated = false;
|
| 1037 |
+
|
| 1038 |
+
ws.onopen = () => {
|
| 1039 |
+
ws.send(JSON.stringify({ token: sessionToken }));
|
| 1040 |
+
};
|
| 1041 |
+
ws.onclose = (ev) => {
|
| 1042 |
+
document.getElementById('dot').classList.remove('on');
|
| 1043 |
+
document.getElementById('cst').textContent = 'Disconnected';
|
| 1044 |
+
if (!authenticated || ev.code === 1008) {
|
| 1045 |
+
document.getElementById('app').style.display = 'none';
|
| 1046 |
+
document.getElementById('login').style.display = 'flex';
|
| 1047 |
+
document.getElementById('loginerr').textContent = 'Token invalide ou expire.';
|
| 1048 |
+
sessionToken = null;
|
| 1049 |
+
} else {
|
| 1050 |
+
setTimeout(() => { if (sessionToken) connectWs(); }, 3000);
|
| 1051 |
+
}
|
| 1052 |
+
};
|
| 1053 |
+
ws.onmessage = (e) => {
|
| 1054 |
+
const m = JSON.parse(e.data);
|
| 1055 |
+
if (m.type === 'auth_ok') {
|
| 1056 |
+
authenticated = true;
|
| 1057 |
+
document.getElementById('login').style.display = 'none';
|
| 1058 |
+
document.getElementById('app').style.display = 'block';
|
| 1059 |
+
document.getElementById('dot').classList.add('on');
|
| 1060 |
+
document.getElementById('cst').textContent = 'Connected (GPU T4)';
|
| 1061 |
+
refreshFiles();
|
| 1062 |
+
}
|
| 1063 |
+
else if (m.type === 'files') renderFiles(m.data);
|
| 1064 |
+
else if (m.type === 'content') {
|
| 1065 |
+
document.getElementById('code').value = m.data || '';
|
| 1066 |
+
curFile = m.path;
|
| 1067 |
+
}
|
| 1068 |
+
else if (m.type === 'execution') {
|
| 1069 |
+
const out = m.data.stdout || m.data.stderr || m.data.error || 'Done';
|
| 1070 |
+
log(out, m.data.stderr ? 'err' : 'out');
|
| 1071 |
+
}
|
| 1072 |
+
else if (m.type === 'agent_result') log('Agent: '+JSON.stringify(m.data), 'inf');
|
| 1073 |
+
else if (m.type === 'telemetry_result') log('Telemetry: '+JSON.stringify(m.data), 'inf');
|
| 1074 |
+
else if (m.type === 'sampling_candidate') log(`Candidat ${m.candidate} (score ${m.score.toFixed(2)}): ${m.preview}`, 'inf');
|
| 1075 |
+
else if (m.type === 'sampling_summary') log(`Meilleur candidat: #${m.best_candidate} — scores ${JSON.stringify(m.scores)}`, 'inf');
|
| 1076 |
+
else if (m.type === 'error') log('Error: '+m.message, 'err');
|
| 1077 |
+
};
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
function renderFiles(items){
|
| 1081 |
+
const c = document.getElementById('tree');
|
| 1082 |
+
if (!items || !items.length) { c.innerHTML = '<div style="color:#666">(empty)</div>'; return; }
|
| 1083 |
+
let h = '';
|
| 1084 |
+
items.forEach(f => {
|
| 1085 |
+
const icon = f.is_dir ? '[DIR]' : '[FILE]';
|
| 1086 |
+
h += `<div class="tree-item" onclick="loadFile('${f.path}')">${icon} ${f.name}</div>`;
|
| 1087 |
+
});
|
| 1088 |
+
c.innerHTML = h;
|
| 1089 |
+
}
|
| 1090 |
+
|
| 1091 |
+
function loadFile(path){ ws.send(JSON.stringify({action:'read_file', path})); }
|
| 1092 |
+
function refreshFiles(){ ws.send(JSON.stringify({action:'list_files'})); }
|
| 1093 |
+
function saveFile(){
|
| 1094 |
+
if (!curFile){ alert('No file open'); return; }
|
| 1095 |
+
ws.send(JSON.stringify({action:'write_file', path:curFile, content:document.getElementById('code').value}));
|
| 1096 |
+
}
|
| 1097 |
+
function executeFile(){
|
| 1098 |
+
if (!curFile){ alert('No file open'); return; }
|
| 1099 |
+
ws.send(JSON.stringify({action:'execute', path:curFile}));
|
| 1100 |
+
}
|
| 1101 |
+
function sendTask(){
|
| 1102 |
+
const inp = document.getElementById('ainp');
|
| 1103 |
+
const t = inp.value.trim();
|
| 1104 |
+
if (!t) return;
|
| 1105 |
+
addMsg('u', t);
|
| 1106 |
+
inp.value = '';
|
| 1107 |
+
const useReasoning = document.getElementById('reasonchk').checked;
|
| 1108 |
+
ws.send(JSON.stringify({action:'agent', task:t, use_reasoning: useReasoning}));
|
| 1109 |
+
}
|
| 1110 |
+
function clearChat(){ document.getElementById('chat').innerHTML = ''; }
|
| 1111 |
+
function qTest(){ addMsg('u','Run all tests and report failures'); ws.send(JSON.stringify({action:'quick_test'})); }
|
| 1112 |
+
function qFix(){ addMsg('u','Scan for bugs and fix them'); ws.send(JSON.stringify({action:'quick_fix'})); }
|
| 1113 |
+
function qExp(){
|
| 1114 |
+
if (!curFile){ addMsg('e','Open a file first'); return; }
|
| 1115 |
+
addMsg('u','Explain '+curFile);
|
| 1116 |
+
ws.send(JSON.stringify({action:'quick_explain', path:curFile}));
|
| 1117 |
+
}
|
| 1118 |
+
function sendDirect(t){ addMsg('u',t); ws.send(JSON.stringify({action:'agent', task:t, use_reasoning:false})); }
|
| 1119 |
+
function runTelemetry(){
|
| 1120 |
+
if (!curFile){ alert('No file open'); return; }
|
| 1121 |
+
ws.send(JSON.stringify({action:'telemetry_run', path:curFile}));
|
| 1122 |
+
}
|
| 1123 |
+
function addMsg(type, content){
|
| 1124 |
+
const chat = document.getElementById('chat');
|
| 1125 |
+
const msg = document.createElement('div');
|
| 1126 |
+
msg.className = 'msg '+type;
|
| 1127 |
+
msg.textContent = content;
|
| 1128 |
+
chat.appendChild(msg);
|
| 1129 |
+
chat.scrollTop = chat.scrollHeight;
|
| 1130 |
+
}
|
| 1131 |
+
function log(msg, type='out'){
|
| 1132 |
+
const t = document.getElementById('term');
|
| 1133 |
+
const l = document.createElement('div');
|
| 1134 |
+
l.className = 'term-l '+type;
|
| 1135 |
+
l.textContent = '[' + new Date().toLocaleTimeString() + '] ' + msg;
|
| 1136 |
+
t.appendChild(l);
|
| 1137 |
+
t.scrollTop = t.scrollHeight;
|
| 1138 |
+
}
|
| 1139 |
+
function accDiff(){ document.getElementById('diff').classList.remove('show'); }
|
| 1140 |
+
function rejDiff(){ document.getElementById('diff').classList.remove('show'); }
|
| 1141 |
+
|
| 1142 |
+
window.addEventListener('keydown', e => {
|
| 1143 |
+
if (e.ctrlKey && e.key === 's') { e.preventDefault(); saveFile(); }
|
| 1144 |
+
});
|
| 1145 |
+
document.getElementById('ainp') && document.getElementById('ainp').addEventListener('keydown', e => {
|
| 1146 |
+
if (e.key === 'Enter') sendTask();
|
| 1147 |
+
});
|
| 1148 |
+
</script>
|
| 1149 |
+
</body>
|
| 1150 |
+
</html>"""
|
| 1151 |
|
| 1152 |
# =================== FASTAPI APP ===================
|
| 1153 |
+
@asynccontextmanager
|
| 1154 |
+
async def lifespan(app: FastAPI):
|
| 1155 |
+
db_pool._init_db()
|
| 1156 |
+
await db_pool.initialize()
|
| 1157 |
+
await vector_store.load_from_db()
|
| 1158 |
+
for i in range(Config.NUM_SCRAPE_WORKERS):
|
| 1159 |
+
worker = asyncio.create_task(scrape_worker(i))
|
| 1160 |
+
scrape_workers.append(worker)
|
| 1161 |
+
logger.info("=" * 50)
|
| 1162 |
+
logger.info("ADN NEXUS V10.3.2 Agentic IDE demarre (avec memoire persistante)")
|
| 1163 |
+
logger.info(f"Workspace: {Config.WORKSPACE_ROOT}")
|
| 1164 |
+
logger.info(f"Workers: {Config.NUM_SCRAPE_WORKERS}")
|
| 1165 |
+
logger.info("=" * 50)
|
| 1166 |
+
yield
|
| 1167 |
+
logger.info("Arret en cours...")
|
| 1168 |
+
global scrape_worker_running
|
| 1169 |
+
scrape_worker_running = False
|
| 1170 |
+
for w in scrape_workers:
|
| 1171 |
+
w.cancel()
|
| 1172 |
+
try:
|
| 1173 |
+
await w
|
| 1174 |
+
except asyncio.CancelledError:
|
| 1175 |
+
pass
|
| 1176 |
+
logger.info("Arret complet")
|
| 1177 |
+
|
| 1178 |
+
# =================== SCRAPING ===================
|
| 1179 |
+
scrape_queue = asyncio.Queue(maxsize=Config.QUEUE_MAXSIZE)
|
| 1180 |
+
scrape_worker_running = True
|
| 1181 |
+
scrape_workers = []
|
| 1182 |
+
|
| 1183 |
+
async def scrape_worker(worker_id):
|
| 1184 |
+
logger.info(f"Worker {worker_id} demarre")
|
| 1185 |
+
while scrape_worker_running:
|
| 1186 |
+
try:
|
| 1187 |
+
url_data = await asyncio.wait_for(scrape_queue.get(), timeout=5.0)
|
| 1188 |
+
url = url_data.get("url")
|
| 1189 |
+
logger.info(f"Worker {worker_id}: {url}")
|
| 1190 |
+
success, content, title = await _scrape_url(url)
|
| 1191 |
+
if success:
|
| 1192 |
+
await vector_store.add(content=content, metadata={"title": title, "url": url}, source_url=url)
|
| 1193 |
+
await db_pool.execute("UPDATE source_states SET last_scraped = ?, status = ? WHERE url = ?",
|
| 1194 |
+
(datetime.utcnow().isoformat(), "ok", url))
|
| 1195 |
+
logger.info(f"Worker {worker_id}: {url} -> OK")
|
| 1196 |
+
else:
|
| 1197 |
+
await db_pool.execute("UPDATE source_states SET status = ? WHERE url = ?", (f"error_{content}", url))
|
| 1198 |
+
logger.warning(f"Worker {worker_id}: echec {url}")
|
| 1199 |
+
scrape_queue.task_done()
|
| 1200 |
+
except asyncio.TimeoutError:
|
| 1201 |
+
continue
|
| 1202 |
+
except Exception as e:
|
| 1203 |
+
logger.error(f"Worker {worker_id} erreur: {e}")
|
| 1204 |
+
try:
|
| 1205 |
+
scrape_queue.task_done()
|
| 1206 |
+
except Exception:
|
| 1207 |
+
pass
|
| 1208 |
+
logger.info(f"Worker {worker_id} arrete")
|
| 1209 |
+
|
| 1210 |
+
async def _scrape_url(url):
|
| 1211 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
| 1212 |
+
try:
|
| 1213 |
+
resp = requests.get(url, headers=headers, timeout=15)
|
| 1214 |
+
if resp.status_code != 200:
|
| 1215 |
+
return False, str(resp.status_code), "Error"
|
| 1216 |
+
soup = BeautifulSoup(resp.text, 'html.parser')
|
| 1217 |
+
title = soup.title.string if soup.title else "No title"
|
| 1218 |
+
for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
|
| 1219 |
+
tag.decompose()
|
| 1220 |
+
paragraphs = [p.get_text(strip=True) for p in soup.find_all('p') if len(p.get_text(strip=True)) > 20]
|
| 1221 |
+
content = "\n".join(paragraphs)
|
| 1222 |
+
if len(content) < 100:
|
| 1223 |
+
article = soup.find('article') or soup.find('main') or soup.body
|
| 1224 |
+
if article:
|
| 1225 |
+
content = article.get_text(separator='\n', strip=True)
|
| 1226 |
+
content = content[:Config.MAX_CONTENT_LENGTH]
|
| 1227 |
+
return True, content, title
|
| 1228 |
+
except Exception as e:
|
| 1229 |
+
return False, str(e), "Error"
|
| 1230 |
+
|
| 1231 |
+
app = FastAPI(title="ADN NEXUS V10.3.2", version="10.3.2", lifespan=lifespan,
|
| 1232 |
+
docs_url=None, redoc_url=None, openapi_url=None)
|
| 1233 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"])
|
| 1234 |
+
|
| 1235 |
+
# =================== ROUTES ===================
|
| 1236 |
+
@app.get("/")
|
| 1237 |
+
async def root():
|
| 1238 |
+
return HTMLResponse(content=IDE_HTML)
|
| 1239 |
+
|
| 1240 |
+
@app.get("/health")
|
| 1241 |
+
async def health():
|
| 1242 |
+
return {"status": "ok", "version": "10.3.2", "gpu": "T4"}
|
| 1243 |
+
|
| 1244 |
+
@app.get("/workspace")
|
| 1245 |
+
async def list_workspace(token: str = Depends(verify_any_token)):
|
| 1246 |
+
return file_mgr.list_dir("")
|
| 1247 |
+
|
| 1248 |
+
@app.get("/file")
|
| 1249 |
+
async def read_file(path: str, token: str = Depends(verify_any_token)):
|
| 1250 |
+
return file_mgr.read(path)
|
| 1251 |
+
|
| 1252 |
+
@app.post("/file")
|
| 1253 |
+
async def write_file(data: dict, token: str = Depends(verify_any_token)):
|
| 1254 |
+
return file_mgr.write(data.get("path"), data.get("content"))
|
| 1255 |
+
|
| 1256 |
+
@app.post("/run")
|
| 1257 |
+
async def run_code(data: dict, token: str = Depends(verify_any_token)):
|
| 1258 |
+
return await sandbox.run_python(data.get("code", ""))
|
| 1259 |
+
|
| 1260 |
+
@app.post("/agent")
|
| 1261 |
+
async def agent_task(data: dict, token: str = Depends(verify_any_token)):
|
| 1262 |
+
session_id = str(uuid.uuid4())
|
| 1263 |
+
result = await agent.run_task(session_id, data.get("task", ""), DummyWebSocket())
|
| 1264 |
+
return result
|
| 1265 |
+
|
| 1266 |
+
class DummyWebSocket:
|
| 1267 |
+
async def send_json(self, data):
|
| 1268 |
+
logger.info(f"Agent: {data}")
|
| 1269 |
+
|
| 1270 |
+
# =================== WEBSOCKET AVEC AUTH ET PLAFOND ===================
|
| 1271 |
+
@app.websocket("/ws")
|
| 1272 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 1273 |
+
client_host = websocket.client.host if websocket.client else "unknown"
|
| 1274 |
+
|
| 1275 |
+
if not await rate_limiter.is_allowed(f"ws-preauth:{client_host}"):
|
| 1276 |
+
await websocket.close(code=1013, reason="Rate limit exceeded")
|
| 1277 |
+
return
|
| 1278 |
+
|
| 1279 |
+
await websocket.accept()
|
| 1280 |
+
|
| 1281 |
+
acquired = False
|
| 1282 |
+
try:
|
| 1283 |
+
await asyncio.wait_for(_auth_semaphore.acquire(), timeout=5.0)
|
| 1284 |
+
acquired = True
|
| 1285 |
+
except asyncio.TimeoutError:
|
| 1286 |
+
logger.warning(f"Trop de connexions en attente d'auth, rejet de {client_host}")
|
| 1287 |
+
await websocket.close(code=1013, reason="Too many pending connections")
|
| 1288 |
+
return
|
| 1289 |
+
|
| 1290 |
+
try:
|
| 1291 |
+
first_msg = await asyncio.wait_for(websocket.receive_json(), timeout=10)
|
| 1292 |
+
except Exception:
|
| 1293 |
+
await websocket.close(code=1008, reason="Authentication timeout")
|
| 1294 |
+
return
|
| 1295 |
+
finally:
|
| 1296 |
+
if acquired:
|
| 1297 |
+
_auth_semaphore.release()
|
| 1298 |
+
|
| 1299 |
+
token = first_msg.get("token") if isinstance(first_msg, dict) else None
|
| 1300 |
+
if not token or token not in _valid_tokens():
|
| 1301 |
+
try:
|
| 1302 |
+
await websocket.send_json({"type": "error", "message": "Authentification requise"})
|
| 1303 |
+
except Exception:
|
| 1304 |
+
pass
|
| 1305 |
+
await websocket.close(code=1008, reason="Unauthorized")
|
| 1306 |
+
return
|
| 1307 |
+
if not await rate_limiter.is_allowed(f"ws:{token[:16]}"):
|
| 1308 |
+
await websocket.close(code=1013, reason="Rate limit exceeded")
|
| 1309 |
+
return
|
| 1310 |
+
|
| 1311 |
+
await websocket.send_json({"type": "auth_ok"})
|
| 1312 |
+
session_id = str(uuid.uuid4())
|
| 1313 |
+
try:
|
| 1314 |
+
while True:
|
| 1315 |
+
msg = await websocket.receive_json()
|
| 1316 |
+
action = msg.get("action")
|
| 1317 |
+
if action == "list_files":
|
| 1318 |
+
result = file_mgr.list_dir("")
|
| 1319 |
+
await websocket.send_json({"type": "files", "data": result.get("items", [])})
|
| 1320 |
+
elif action == "read_file":
|
| 1321 |
+
result = file_mgr.read(msg.get("path", ""))
|
| 1322 |
+
await websocket.send_json({"type": "content", "path": msg.get("path"), "data": result.get("content")})
|
| 1323 |
+
elif action == "write_file":
|
| 1324 |
+
result = file_mgr.write(msg.get("path"), msg.get("content"))
|
| 1325 |
+
await websocket.send_json({"type": "saved", "data": result})
|
| 1326 |
+
elif action == "execute":
|
| 1327 |
+
code = file_mgr.read(msg.get("path")).get("content", "")
|
| 1328 |
+
result = await sandbox.run_python(code)
|
| 1329 |
+
await websocket.send_json({"type": "execution", "data": result})
|
| 1330 |
+
elif action == "agent":
|
| 1331 |
+
task = msg.get("task", "")
|
| 1332 |
+
if msg.get("use_reasoning"):
|
| 1333 |
+
result = await agent.run_task_with_reasoning(session_id, task, websocket, msg.get("max_candidates"))
|
| 1334 |
+
else:
|
| 1335 |
+
result = await agent.run_task(session_id, task, websocket)
|
| 1336 |
+
await websocket.send_json({"type": "agent_result", "data": result})
|
| 1337 |
+
elif action == "quick_test":
|
| 1338 |
+
result = await sandbox.run_command([sys.executable, "-m", "pytest", "."])
|
| 1339 |
+
summary = await inference.generate([
|
| 1340 |
+
{"role": "system", "content": "You are a coding assistant. Summarize this pytest output concisely in plain text for a developer: how many passed/failed, and the key error if any. No JSON, no tool calls."},
|
| 1341 |
+
{"role": "user", "content": f"stdout:\n{result.get('stdout','')}\n\nstderr:\n{result.get('stderr','')}"},
|
| 1342 |
+
], max_tokens=300, do_sample=False)
|
| 1343 |
+
await websocket.send_json({"type": "agent_result", "data": {"success": True, "result": summary, "raw": result}})
|
| 1344 |
+
elif action == "quick_fix":
|
| 1345 |
+
result = await sandbox.run_command([sys.executable, "-m", "flake8", "."])
|
| 1346 |
+
if result.get("stdout", "").strip() == "" and result.get("returncode") == 0:
|
| 1347 |
+
summary = "Aucun probleme detecte par flake8."
|
| 1348 |
+
else:
|
| 1349 |
+
summary = await inference.generate([
|
| 1350 |
+
{"role": "system", "content": "You are a coding assistant. Given this flake8 output, list the issues found and suggest concise fixes in plain text. No JSON, no tool calls."},
|
| 1351 |
+
{"role": "user", "content": result.get("stdout", "") or result.get("stderr", "")},
|
| 1352 |
+
], max_tokens=400, do_sample=False)
|
| 1353 |
+
await websocket.send_json({"type": "agent_result", "data": {"success": True, "result": summary, "raw": result}})
|
| 1354 |
+
elif action == "quick_explain":
|
| 1355 |
+
path = msg.get("path", "")
|
| 1356 |
+
if not path:
|
| 1357 |
+
await websocket.send_json({"type": "agent_result", "data": {"success": False, "result": "Aucun fichier ouvert."}})
|
| 1358 |
+
else:
|
| 1359 |
+
full_path = Config.WORKSPACE_ROOT / path
|
| 1360 |
+
if full_path.is_dir():
|
| 1361 |
+
await websocket.send_json({"type": "agent_result", "data": {"success": False, "result": f"{path} est un dossier, pas un fichier."}})
|
| 1362 |
+
continue
|
| 1363 |
+
file_result = file_mgr.read(path)
|
| 1364 |
+
if not file_result.get("success"):
|
| 1365 |
+
await websocket.send_json({"type": "agent_result", "data": {"success": False, "result": file_result.get("error", "Fichier introuvable.")}})
|
| 1366 |
+
else:
|
| 1367 |
+
summary = await inference.generate([
|
| 1368 |
+
{"role": "system", "content": "You are a coding assistant. Explain the given file's purpose, structure and possible improvements, concisely, in plain text. No JSON, no tool calls."},
|
| 1369 |
+
{"role": "user", "content": f"File: {path}\n\n{file_result.get('content','')}"},
|
| 1370 |
+
], max_tokens=400, do_sample=False)
|
| 1371 |
+
await websocket.send_json({"type": "agent_result", "data": {"success": True, "result": summary}})
|
| 1372 |
+
elif action == "telemetry_run":
|
| 1373 |
+
code = file_mgr.read(msg.get("path")).get("content", "")
|
| 1374 |
+
result = await telemetry.run_with_trace(code)
|
| 1375 |
+
await websocket.send_json({"type": "telemetry_result", "data": result})
|
| 1376 |
+
elif action == "impact_analysis":
|
| 1377 |
+
symbol = msg.get("symbol", "")
|
| 1378 |
+
results = kg_loader.query_symbol(symbol)
|
| 1379 |
+
await websocket.send_json({"type": "impact_result", "data": results})
|
| 1380 |
+
elif action == "git_log":
|
| 1381 |
+
if git_analyzer:
|
| 1382 |
+
commits = git_analyzer.get_commit_graph(20)
|
| 1383 |
+
await websocket.send_json({"type": "git_log", "data": commits})
|
| 1384 |
+
else:
|
| 1385 |
+
await websocket.send_json({"type": "git_log", "data": {"error": "Git not available"}})
|
| 1386 |
+
elif action == "api_contract":
|
| 1387 |
+
path = msg.get("path")
|
| 1388 |
+
if path:
|
| 1389 |
+
try:
|
| 1390 |
+
contract = contract_parser.parse_openapi(path)
|
| 1391 |
+
await websocket.send_json({"type": "api_contract", "data": contract})
|
| 1392 |
+
except Exception as e:
|
| 1393 |
+
await websocket.send_json({"type": "error", "message": str(e)})
|
| 1394 |
+
else:
|
| 1395 |
+
await websocket.send_json({"type": "error", "message": "Missing path"})
|
| 1396 |
+
else:
|
| 1397 |
+
await websocket.send_json({"type": "error", "message": f"Unknown action: {action}"})
|
| 1398 |
+
except WebSocketDisconnect:
|
| 1399 |
+
logger.info(f"Session {session_id} disconnectee")
|
| 1400 |
+
except Exception as e:
|
| 1401 |
+
logger.error(f"WS error: {e}")
|
| 1402 |
+
try:
|
| 1403 |
+
await websocket.send_json({"type": "error", "message": str(e)})
|
| 1404 |
+
except Exception:
|
| 1405 |
+
pass
|
| 1406 |
|
| 1407 |
# =================== LANCEMENT ===================
|
| 1408 |
if __name__ == "__main__":
|