Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
# app.py — ADN NEXUS V10.3.2 (
|
| 2 |
-
# Serveur FastAPI + Client IDE + Agent + Tool-calling + Mémoire + Prompt
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import os
|
|
@@ -44,10 +44,7 @@ logger = logging.getLogger("nexus_v103")
|
|
| 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 |
-
#
|
| 48 |
-
# Limite le nombre de WebSockets simultanément en cours d'authentification
|
| 49 |
-
# (après accept() mais avant réception du premier message).
|
| 50 |
-
# Sur CPU, une valeur de 50 est raisonnable ; sur GPU vous pouvez monter à 200.
|
| 51 |
MAX_PENDING_AUTH = int(os.getenv("MAX_PENDING_AUTH", 50))
|
| 52 |
_auth_semaphore = asyncio.Semaphore(MAX_PENDING_AUTH)
|
| 53 |
|
|
@@ -89,7 +86,6 @@ class Config:
|
|
| 89 |
REASONING_TEMPERATURE = float(os.getenv("REASONING_TEMPERATURE", 0.7))
|
| 90 |
MAX_CONTEXT_TOKENS = int(os.getenv("MAX_CONTEXT_TOKENS", 1400))
|
| 91 |
TOOL_RESULT_KEEP_CHARS = int(os.getenv("TOOL_RESULT_KEEP_CHARS", 300))
|
| 92 |
-
# Mémoire persistante
|
| 93 |
MEMORY_ENABLED = os.getenv("MEMORY_ENABLED", "true").lower() == "true"
|
| 94 |
MEMORY_MAX_RESULTS = int(os.getenv("MEMORY_MAX_RESULTS", 10))
|
| 95 |
|
|
@@ -120,7 +116,7 @@ class RateLimiter:
|
|
| 120 |
|
| 121 |
rate_limiter = RateLimiter(Config.RATE_LIMIT_REQUESTS, Config.RATE_LIMIT_WINDOW)
|
| 122 |
|
| 123 |
-
# =================== BASE DE DONNEES (POOL ASYNC) ===================
|
| 124 |
@dataclass
|
| 125 |
class DBConnectionPool:
|
| 126 |
db_path: str
|
|
@@ -167,75 +163,8 @@ class DBConnectionPool:
|
|
| 167 |
c.execute("PRAGMA journal_mode=WAL;")
|
| 168 |
c.execute("PRAGMA synchronous=NORMAL;")
|
| 169 |
c.executescript('''
|
| 170 |
-
CREATE TABLE IF NOT EXISTS source_states (
|
| 171 |
-
|
| 172 |
-
status TEXT, interval_minutes REAL DEFAULT 60, is_rss INTEGER DEFAULT 0,
|
| 173 |
-
source_metadata TEXT DEFAULT '{}', active INTEGER DEFAULT 1
|
| 174 |
-
);
|
| 175 |
-
CREATE TABLE IF NOT EXISTS encyclopedia_chunks (
|
| 176 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT,
|
| 177 |
-
metadata TEXT DEFAULT '{}', embedding BLOB, source_url TEXT,
|
| 178 |
-
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 179 |
-
);
|
| 180 |
-
CREATE TABLE IF NOT EXISTS harbor_memory (
|
| 181 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, task TEXT,
|
| 182 |
-
hypothesis TEXT, action TEXT, observation TEXT, status TEXT,
|
| 183 |
-
feedback TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 184 |
-
);
|
| 185 |
-
CREATE TABLE IF NOT EXISTS cognitive_logs (
|
| 186 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, question TEXT,
|
| 187 |
-
prompt TEXT, answer TEXT, status TEXT, feedback TEXT,
|
| 188 |
-
chunks_used TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 189 |
-
);
|
| 190 |
-
CREATE TABLE IF NOT EXISTS scrape_queue (
|
| 191 |
-
url TEXT PRIMARY KEY, priority INTEGER DEFAULT 0,
|
| 192 |
-
added_at TEXT DEFAULT CURRENT_TIMESTAMP, status TEXT DEFAULT 'pending'
|
| 193 |
-
);
|
| 194 |
-
CREATE TABLE IF NOT EXISTS task_tracker (
|
| 195 |
-
task_id TEXT PRIMARY KEY, task_type TEXT, payload TEXT,
|
| 196 |
-
status TEXT DEFAULT 'pending', created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
| 197 |
-
completed_at TEXT, error_message TEXT
|
| 198 |
-
);
|
| 199 |
-
CREATE TABLE IF NOT EXISTS sessions (
|
| 200 |
-
id TEXT PRIMARY KEY, created_at TEXT, project_path TEXT
|
| 201 |
-
);
|
| 202 |
-
CREATE TABLE IF NOT EXISTS files (
|
| 203 |
-
id INTEGER PRIMARY KEY, session_id TEXT, path TEXT,
|
| 204 |
-
content TEXT, language TEXT, last_modified TEXT
|
| 205 |
-
);
|
| 206 |
-
CREATE TABLE IF NOT EXISTS operations (
|
| 207 |
-
id INTEGER PRIMARY KEY, session_id TEXT, type TEXT,
|
| 208 |
-
file_path TEXT, diff TEXT, status TEXT, error TEXT,
|
| 209 |
-
created_at TEXT, applied_at TEXT
|
| 210 |
-
);
|
| 211 |
-
CREATE TABLE IF NOT EXISTS agent_runs (
|
| 212 |
-
id INTEGER PRIMARY KEY, session_id TEXT, task TEXT,
|
| 213 |
-
tool_calls TEXT, result TEXT, status TEXT, created_at TEXT
|
| 214 |
-
);
|
| 215 |
-
CREATE TABLE IF NOT EXISTS telemetry (
|
| 216 |
-
id INTEGER PRIMARY KEY, execution_id TEXT, file_path TEXT,
|
| 217 |
-
event_type TEXT, line_no INTEGER, function_name TEXT,
|
| 218 |
-
locals_snapshot TEXT, timestamp REAL
|
| 219 |
-
);
|
| 220 |
-
CREATE TABLE IF NOT EXISTS symbols (
|
| 221 |
-
id TEXT PRIMARY KEY, name TEXT, type TEXT, language TEXT,
|
| 222 |
-
file_path TEXT, line_start INTEGER, line_end INTEGER,
|
| 223 |
-
signature TEXT, docstring TEXT
|
| 224 |
-
);
|
| 225 |
-
CREATE TABLE IF NOT EXISTS relationships (
|
| 226 |
-
id INTEGER PRIMARY KEY, source_id TEXT, target_id TEXT,
|
| 227 |
-
relation_type TEXT, confidence REAL
|
| 228 |
-
);
|
| 229 |
-
-- Table pour la mémoire persistante
|
| 230 |
-
CREATE TABLE IF NOT EXISTS agent_memory (
|
| 231 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 232 |
-
task TEXT,
|
| 233 |
-
result TEXT,
|
| 234 |
-
success INTEGER,
|
| 235 |
-
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
| 236 |
-
);
|
| 237 |
-
CREATE INDEX IF NOT EXISTS idx_agent_memory_task ON agent_memory(task);
|
| 238 |
-
CREATE INDEX IF NOT EXISTS idx_agent_memory_created ON agent_memory(created_at);
|
| 239 |
''')
|
| 240 |
conn.commit()
|
| 241 |
conn.close()
|
|
@@ -256,130 +185,11 @@ async def verify_any_token(authorization: str = Header(...)):
|
|
| 256 |
|
| 257 |
# =================== VECTOR STORE ===================
|
| 258 |
class VectorStore:
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
self.chunks = []
|
| 262 |
-
self.embeddings = None
|
| 263 |
-
self._lock = asyncio.Lock()
|
| 264 |
-
self._load_encoder()
|
| 265 |
-
|
| 266 |
-
def _load_encoder(self):
|
| 267 |
-
try:
|
| 268 |
-
self.encoder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2', device=Config.DEVICE)
|
| 269 |
-
logger.info(f"Encodeur charge sur {Config.DEVICE}")
|
| 270 |
-
except Exception as e:
|
| 271 |
-
logger.warning(f"Encodeur desactive: {e}")
|
| 272 |
-
|
| 273 |
-
async def load_from_db(self):
|
| 274 |
-
rows = await db_pool.query("SELECT id, content, metadata, source_url FROM encyclopedia_chunks")
|
| 275 |
-
async with self._lock:
|
| 276 |
-
self.chunks = []
|
| 277 |
-
for r in rows:
|
| 278 |
-
self.chunks.append({
|
| 279 |
-
"id": r["id"], "content": r["content"],
|
| 280 |
-
"metadata": json.loads(r["metadata"] or "{}"),
|
| 281 |
-
"source_url": r["source_url"]
|
| 282 |
-
})
|
| 283 |
-
if self.chunks and self.encoder:
|
| 284 |
-
texts = [c["content"] for c in self.chunks]
|
| 285 |
-
loop = asyncio.get_running_loop()
|
| 286 |
-
self.embeddings = await loop.run_in_executor(None, self.encoder.encode, texts, False)
|
| 287 |
-
logger.info(f"{len(self.chunks)} chunks charges")
|
| 288 |
-
|
| 289 |
-
async def add(self, content, metadata=None, source_url=None):
|
| 290 |
-
chunker = TextChunker()
|
| 291 |
-
text_chunks = chunker.chunk_text(content)
|
| 292 |
-
row_ids = []
|
| 293 |
-
async with self._lock:
|
| 294 |
-
for chunk_text in text_chunks:
|
| 295 |
-
if self.encoder:
|
| 296 |
-
loop = asyncio.get_running_loop()
|
| 297 |
-
emb = await loop.run_in_executor(None, self.encoder.encode, [chunk_text])
|
| 298 |
-
emb = emb[0]
|
| 299 |
-
row_id = await db_pool.execute(
|
| 300 |
-
"INSERT INTO encyclopedia_chunks (content, metadata, source_url, embedding) VALUES (?, ?, ?, ?)",
|
| 301 |
-
(chunk_text, json.dumps(metadata or {}), source_url, emb.tobytes())
|
| 302 |
-
)
|
| 303 |
-
if self.embeddings is None:
|
| 304 |
-
self.embeddings = emb.reshape(1, -1)
|
| 305 |
-
else:
|
| 306 |
-
self.embeddings = np.vstack([self.embeddings, emb])
|
| 307 |
-
else:
|
| 308 |
-
row_id = await db_pool.execute(
|
| 309 |
-
"INSERT INTO encyclopedia_chunks (content, metadata, source_url) VALUES (?, ?, ?)",
|
| 310 |
-
(chunk_text, json.dumps(metadata or {}), source_url)
|
| 311 |
-
)
|
| 312 |
-
self.chunks.append({"id": row_id, "content": chunk_text, "metadata": metadata or {}, "source_url": source_url})
|
| 313 |
-
row_ids.append(row_id)
|
| 314 |
-
return row_ids
|
| 315 |
-
|
| 316 |
-
async def search(self, query, top_k=5):
|
| 317 |
-
async with self._lock:
|
| 318 |
-
if not self.chunks:
|
| 319 |
-
return []
|
| 320 |
-
if self.encoder and self.embeddings is not None:
|
| 321 |
-
loop = asyncio.get_running_loop()
|
| 322 |
-
q_emb = await loop.run_in_executor(None, self.encoder.encode, [query])
|
| 323 |
-
q_emb = q_emb[0]
|
| 324 |
-
norms = np.linalg.norm(self.embeddings, axis=1) * np.linalg.norm(q_emb) + 1e-8
|
| 325 |
-
sim = np.dot(self.embeddings, q_emb) / norms
|
| 326 |
-
idx = np.argsort(sim)[::-1][:top_k]
|
| 327 |
-
return [{**self.chunks[i].copy(), "score": float(sim[i])} for i in idx]
|
| 328 |
-
q_words = set(query.lower().split())
|
| 329 |
-
scored = []
|
| 330 |
-
for c in self.chunks:
|
| 331 |
-
cw = set(c["content"].lower().split())
|
| 332 |
-
scored.append((len(q_words & cw) / max(len(q_words), 1), c))
|
| 333 |
-
scored.sort(reverse=True)
|
| 334 |
-
return [c.copy() for _, c in scored[:top_k]]
|
| 335 |
-
|
| 336 |
-
vector_store = VectorStore()
|
| 337 |
-
|
| 338 |
-
# =================== CHUNKING ===================
|
| 339 |
-
class TextChunker:
|
| 340 |
-
@staticmethod
|
| 341 |
-
def chunk_text(text, chunk_size=Config.CHUNK_SIZE, overlap=Config.CHUNK_OVERLAP):
|
| 342 |
-
sentences = re.split(r'(?<=[.!?])\s+', text)
|
| 343 |
-
chunks, current_chunk, current_length = [], [], 0
|
| 344 |
-
for sentence in sentences:
|
| 345 |
-
sentence_len = len(sentence)
|
| 346 |
-
if current_length + sentence_len > chunk_size and current_chunk:
|
| 347 |
-
chunks.append(" ".join(current_chunk))
|
| 348 |
-
overlap_text = " ".join(current_chunk[-2:]) if len(current_chunk) > 2 else ""
|
| 349 |
-
current_chunk = [overlap_text, sentence] if overlap_text else [sentence]
|
| 350 |
-
current_length = len(overlap_text) + sentence_len if overlap_text else sentence_len
|
| 351 |
-
else:
|
| 352 |
-
current_chunk.append(sentence)
|
| 353 |
-
current_length += sentence_len + 1
|
| 354 |
-
if current_chunk:
|
| 355 |
-
chunks.append(" ".join(current_chunk))
|
| 356 |
-
return chunks
|
| 357 |
-
|
| 358 |
-
# =================== RERANKER ===================
|
| 359 |
-
class Reranker:
|
| 360 |
-
def __init__(self):
|
| 361 |
-
self.model = None
|
| 362 |
-
try:
|
| 363 |
-
self.model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2', device=Config.DEVICE)
|
| 364 |
-
logger.info(f"Cross-Encoder charge sur {Config.DEVICE}")
|
| 365 |
-
except Exception as e:
|
| 366 |
-
logger.warning(f"Cross-Encoder desactive: {e}")
|
| 367 |
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
return chunks[:top_k]
|
| 371 |
-
pairs = [(query, c.get("content", "")) for c in chunks]
|
| 372 |
-
try:
|
| 373 |
-
loop = asyncio.get_running_loop()
|
| 374 |
-
scores = await loop.run_in_executor(None, self.model.predict, pairs)
|
| 375 |
-
for i, c in enumerate(chunks):
|
| 376 |
-
c["rerank_score"] = float(scores[i])
|
| 377 |
-
return sorted(chunks, key=lambda x: x.get("rerank_score", 0), reverse=True)[:top_k]
|
| 378 |
-
except Exception as e:
|
| 379 |
-
logger.error(f"Reranking echoue: {e}")
|
| 380 |
-
return chunks[:top_k]
|
| 381 |
-
|
| 382 |
-
reranker = Reranker()
|
| 383 |
|
| 384 |
# =================== INFÉRENCE ===================
|
| 385 |
class LocalInference:
|
|
@@ -410,13 +220,11 @@ class LocalInference:
|
|
| 410 |
async def generate(self, messages, max_tokens=512, temperature=0.2, do_sample=False):
|
| 411 |
if self.model is None or self.tokenizer is None:
|
| 412 |
return "Erreur: modele non charge."
|
| 413 |
-
|
| 414 |
prompt = self._format_qwen_messages(messages)
|
| 415 |
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
|
| 416 |
device = Config.DEVICE
|
| 417 |
if device == "cuda":
|
| 418 |
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 419 |
-
|
| 420 |
try:
|
| 421 |
loop = asyncio.get_running_loop()
|
| 422 |
outputs = await loop.run_in_executor(
|
|
@@ -459,13 +267,15 @@ TOOLS = [
|
|
| 459 |
{"name": "read_file", "description": "Read file content", "parameters": {"path": {"type": "string"}}},
|
| 460 |
{"name": "write_file", "description": "Write file", "parameters": {"path": {"type": "string"}, "content": {"type": "string"}}},
|
| 461 |
{"name": "list_directory", "description": "List files", "parameters": {"path": {"type": "string"}}},
|
| 462 |
-
{"name": "run_python", "description": "
|
| 463 |
]
|
| 464 |
|
| 465 |
-
# =================== AGENT
|
| 466 |
class AgentV103:
|
| 467 |
-
MAX_NUDGES_PER_TASK =
|
| 468 |
_CONFUSION_MARKERS = (
|
|
|
|
|
|
|
| 469 |
"tool was not found", "tool not found", "no such tool",
|
| 470 |
"i don't have", "i do not have", "unable to", "cannot find",
|
| 471 |
"please ensure you have the correct tool", "not available",
|
|
@@ -477,79 +287,50 @@ class AgentV103:
|
|
| 477 |
self.system_prompt = self._build_system_prompt()
|
| 478 |
|
| 479 |
def _build_system_prompt(self) -> str:
|
| 480 |
-
|
| 481 |
-
return """You are an
|
| 482 |
-
You have access to
|
| 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 |
-
1. Multi-file project:
|
| 523 |
-
User: "Create a project with two files: utils.py with add(a,b), and main.py that imports and uses add."
|
| 524 |
-
Your steps:
|
| 525 |
-
Step 1: {"tool": "write_file", "arguments": {"path": "utils.py", "content": "def add(a,b): return a+b"}}
|
| 526 |
-
Step 2: {"tool": "write_file", "arguments": {"path": "main.py", "content": "from utils import add\\nprint(add(3,5))"}}
|
| 527 |
-
Step 3: {"tool": "run_python", "arguments": {"code": "exec(open('main.py').read())"}}
|
| 528 |
-
Final: "Project created. Execution result: 8"
|
| 529 |
-
|
| 530 |
-
2. Refactoring:
|
| 531 |
-
User: "Refactor app.py by moving business logic to business.py"
|
| 532 |
-
Step 1: {"tool": "read_file", "arguments": {"path": "app.py"}}
|
| 533 |
-
Step 2: (analyze) "The business logic is in process_data function"
|
| 534 |
-
Step 3: {"tool": "write_file", "arguments": {"path": "business.py", "content": "def process_data(data):\\n ..."}}
|
| 535 |
-
Step 4: {"tool": "write_file", "arguments": {"path": "app.py", "content": "from business import process_data\\n..."}}
|
| 536 |
-
Step 5: {"tool": "run_python", "arguments": {"code": "exec(open('app.py').read())"}}
|
| 537 |
-
Final: "Refactoring complete. app.py is now lighter."
|
| 538 |
-
|
| 539 |
-
3. Optimization:
|
| 540 |
-
User: "Optimize sum_to_n in math.py"
|
| 541 |
-
Step 1: {"tool": "read_file", "arguments": {"path": "math.py"}}
|
| 542 |
-
Step 2: (analyze) "O(n) – can be O(1) with n*(n+1)//2"
|
| 543 |
-
Step 3: {"tool": "write_file", "arguments": {"path": "math.py", "content": "def sum_to_n(n): return n*(n+1)//2"}}
|
| 544 |
-
Step 4: {"tool": "run_python", "arguments": {"code": "from math import sum_to_n\\nprint(sum_to_n(1000))"}}
|
| 545 |
-
Final: "Optimization done. Result: 500500"
|
| 546 |
-
|
| 547 |
-
Remember: For multi-step tasks, break them into separate tool calls.
|
| 548 |
-
Never try to do everything in one single response unless it's a simple text answer.
|
| 549 |
"""
|
| 550 |
|
| 551 |
async def run_task(self, session_id, task, websocket):
|
| 552 |
-
# Chargement du contexte mémoire
|
| 553 |
memory_context = await self._load_context_from_memory(task) if Config.MEMORY_ENABLED else ""
|
| 554 |
enriched_task = task
|
| 555 |
if memory_context:
|
|
@@ -559,7 +340,6 @@ Never try to do everything in one single response unless it's a simple text answ
|
|
| 559 |
{"role": "user", "content": enriched_task}]
|
| 560 |
result = await self._continue_task(messages, websocket, start_iteration=0)
|
| 561 |
|
| 562 |
-
# Sauvegarde mémoire
|
| 563 |
if Config.MEMORY_ENABLED:
|
| 564 |
await self._save_task_memory(task, result)
|
| 565 |
return result
|
|
@@ -684,19 +464,28 @@ Never try to do everything in one single response unless it's a simple text answ
|
|
| 684 |
messages.append({"role": "tool", "content": json.dumps(result)})
|
| 685 |
continue
|
| 686 |
|
| 687 |
-
|
|
|
|
| 688 |
nudges_used += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
messages.append({"role": "assistant", "content": response})
|
| 690 |
messages.append({
|
| 691 |
"role": "user",
|
| 692 |
"content": (
|
| 693 |
-
"
|
| 694 |
-
"Respond with ONLY
|
| 695 |
-
"
|
|
|
|
| 696 |
),
|
| 697 |
})
|
| 698 |
continue
|
| 699 |
|
|
|
|
| 700 |
await websocket.send_json({"type": "complete", "result": response})
|
| 701 |
return {"success": True, "result": response}
|
| 702 |
|
|
@@ -704,6 +493,7 @@ Never try to do everything in one single response unless it's a simple text answ
|
|
| 704 |
return {"success": False, "error": "Max iterations"}
|
| 705 |
|
| 706 |
def _parse_tool_call(self, text):
|
|
|
|
| 707 |
decoder = json.JSONDecoder()
|
| 708 |
start = 0
|
| 709 |
while True:
|
|
@@ -733,34 +523,29 @@ Never try to do everything in one single response unless it's a simple text answ
|
|
| 733 |
result = {"success": False, "error": f"Tool {name} unknown"}
|
| 734 |
return result
|
| 735 |
|
| 736 |
-
# ===
|
| 737 |
async def _save_task_memory(self, task: str, result: Dict):
|
| 738 |
-
"""Enregistre la tâche et son résultat dans la base SQLite."""
|
| 739 |
if not Config.MEMORY_ENABLED:
|
| 740 |
return
|
| 741 |
try:
|
| 742 |
success = 1 if result.get("success", False) else 0
|
| 743 |
await db_pool.execute(
|
| 744 |
-
"
|
| 745 |
-
VALUES (?, ?, ?, ?)""",
|
| 746 |
(task[:500], json.dumps(result)[:1000], success, datetime.utcnow().isoformat())
|
| 747 |
)
|
| 748 |
except Exception as e:
|
| 749 |
logger.warning(f"Erreur sauvegarde mémoire: {e}")
|
| 750 |
|
| 751 |
async def _load_context_from_memory(self, task: str) -> str:
|
| 752 |
-
"""Récupère les tâches similaires de l'historique pour enrichir le prompt."""
|
| 753 |
if not Config.MEMORY_ENABLED:
|
| 754 |
return ""
|
| 755 |
try:
|
| 756 |
rows = await db_pool.query(
|
| 757 |
-
"
|
| 758 |
-
ORDER BY created_at DESC LIMIT ?""",
|
| 759 |
(Config.MEMORY_MAX_RESULTS,)
|
| 760 |
)
|
| 761 |
if not rows:
|
| 762 |
return ""
|
| 763 |
-
# Sélection simple par mots-clés
|
| 764 |
task_words = set(task.lower().split())
|
| 765 |
context = []
|
| 766 |
for row in rows:
|
|
@@ -776,59 +561,6 @@ Never try to do everything in one single response unless it's a simple text answ
|
|
| 776 |
logger.warning(f"Erreur chargement mémoire: {e}")
|
| 777 |
return ""
|
| 778 |
|
| 779 |
-
# =================== SCRAPING ===================
|
| 780 |
-
scrape_queue = asyncio.Queue(maxsize=Config.QUEUE_MAXSIZE)
|
| 781 |
-
scrape_worker_running = True
|
| 782 |
-
scrape_workers = []
|
| 783 |
-
|
| 784 |
-
async def scrape_worker(worker_id):
|
| 785 |
-
logger.info(f"Worker {worker_id} demarre")
|
| 786 |
-
while scrape_worker_running:
|
| 787 |
-
try:
|
| 788 |
-
url_data = await asyncio.wait_for(scrape_queue.get(), timeout=5.0)
|
| 789 |
-
url = url_data.get("url")
|
| 790 |
-
logger.info(f"Worker {worker_id}: {url}")
|
| 791 |
-
success, content, title = await _scrape_url(url)
|
| 792 |
-
if success:
|
| 793 |
-
await vector_store.add(content=content, metadata={"title": title, "url": url}, source_url=url)
|
| 794 |
-
await db_pool.execute("UPDATE source_states SET last_scraped = ?, status = ? WHERE url = ?",
|
| 795 |
-
(datetime.utcnow().isoformat(), "ok", url))
|
| 796 |
-
logger.info(f"Worker {worker_id}: {url} -> OK")
|
| 797 |
-
else:
|
| 798 |
-
await db_pool.execute("UPDATE source_states SET status = ? WHERE url = ?", (f"error_{content}", url))
|
| 799 |
-
logger.warning(f"Worker {worker_id}: echec {url}")
|
| 800 |
-
scrape_queue.task_done()
|
| 801 |
-
except asyncio.TimeoutError:
|
| 802 |
-
continue
|
| 803 |
-
except Exception as e:
|
| 804 |
-
logger.error(f"Worker {worker_id} erreur: {e}")
|
| 805 |
-
try:
|
| 806 |
-
scrape_queue.task_done()
|
| 807 |
-
except Exception:
|
| 808 |
-
pass
|
| 809 |
-
logger.info(f"Worker {worker_id} arrete")
|
| 810 |
-
|
| 811 |
-
async def _scrape_url(url):
|
| 812 |
-
headers = {"User-Agent": "Mozilla/5.0"}
|
| 813 |
-
try:
|
| 814 |
-
resp = requests.get(url, headers=headers, timeout=15)
|
| 815 |
-
if resp.status_code != 200:
|
| 816 |
-
return False, str(resp.status_code), "Error"
|
| 817 |
-
soup = BeautifulSoup(resp.text, 'html.parser')
|
| 818 |
-
title = soup.title.string if soup.title else "No title"
|
| 819 |
-
for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
|
| 820 |
-
tag.decompose()
|
| 821 |
-
paragraphs = [p.get_text(strip=True) for p in soup.find_all('p') if len(p.get_text(strip=True)) > 20]
|
| 822 |
-
content = "\n".join(paragraphs)
|
| 823 |
-
if len(content) < 100:
|
| 824 |
-
article = soup.find('article') or soup.find('main') or soup.body
|
| 825 |
-
if article:
|
| 826 |
-
content = article.get_text(separator='\n', strip=True)
|
| 827 |
-
content = content[:Config.MAX_CONTENT_LENGTH]
|
| 828 |
-
return True, content, title
|
| 829 |
-
except Exception as e:
|
| 830 |
-
return False, str(e), "Error"
|
| 831 |
-
|
| 832 |
# =================== FILE MANAGER ===================
|
| 833 |
class FileManager:
|
| 834 |
ROOT = Config.WORKSPACE_ROOT
|
|
@@ -897,6 +629,7 @@ class Sandbox:
|
|
| 897 |
Path(temp_path).unlink(missing_ok=True)
|
| 898 |
|
| 899 |
async def run_command(self, args: list, timeout=30):
|
|
|
|
| 900 |
try:
|
| 901 |
proc = await asyncio.create_subprocess_exec(
|
| 902 |
*args,
|
|
@@ -916,540 +649,16 @@ class Sandbox:
|
|
| 916 |
sandbox = Sandbox()
|
| 917 |
|
| 918 |
# =================== TELEMETRY, GIT, KNOWLEDGE GRAPH (simplifiés) ===================
|
| 919 |
-
|
| 920 |
-
def __init__(self, workspace):
|
| 921 |
-
self.workspace = workspace
|
| 922 |
-
async def run_with_trace(self, code, filename="<script>"):
|
| 923 |
-
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
|
| 924 |
-
f.write(code)
|
| 925 |
-
temp_path = f.name
|
| 926 |
-
try:
|
| 927 |
-
proc = await asyncio.create_subprocess_exec(
|
| 928 |
-
sys.executable, '-m', 'trace', '--trace', temp_path,
|
| 929 |
-
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
| 930 |
-
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
|
| 931 |
-
return {"success": proc.returncode == 0,
|
| 932 |
-
"stdout": stdout.decode('utf-8', errors='replace'),
|
| 933 |
-
"stderr": stderr.decode('utf-8', errors='replace')}
|
| 934 |
-
except Exception as e:
|
| 935 |
-
return {"success": False, "error": str(e)}
|
| 936 |
-
finally:
|
| 937 |
-
Path(temp_path).unlink(missing_ok=True)
|
| 938 |
-
|
| 939 |
-
telemetry = RuntimeTelemetry(Config.WORKSPACE_ROOT)
|
| 940 |
-
|
| 941 |
-
class APIContractParser:
|
| 942 |
-
@staticmethod
|
| 943 |
-
def parse_openapi(path):
|
| 944 |
-
content = Path(path).read_text()
|
| 945 |
-
spec = yaml.safe_load(content) if path.suffix in ('.yaml', '.yml') else json.loads(content)
|
| 946 |
-
endpoints = []
|
| 947 |
-
for p, methods in spec.get('paths', {}).items():
|
| 948 |
-
for m, d in methods.items():
|
| 949 |
-
if m in ('get', 'post', 'put', 'patch', 'delete'):
|
| 950 |
-
endpoints.append({"path": p, "method": m.upper(), "operation_id": d.get('operationId')})
|
| 951 |
-
return {"title": spec.get('info', {}).get('title'), "version": spec.get('info', {}).get('version'), "endpoints": endpoints}
|
| 952 |
-
|
| 953 |
-
contract_parser = APIContractParser()
|
| 954 |
-
|
| 955 |
-
class GitGraphAnalyzer:
|
| 956 |
-
def __init__(self, repo_path):
|
| 957 |
-
self.repo = repo_path
|
| 958 |
-
if not (self.repo / '.git').exists():
|
| 959 |
-
raise ValueError("Not a git repository")
|
| 960 |
-
def get_commit_graph(self, max_commits=20):
|
| 961 |
-
try:
|
| 962 |
-
result = subprocess.run(['git', '-C', str(self.repo), 'log', f'-{max_commits}', '--format=%H|%s|%ad', '--date=short'],
|
| 963 |
-
capture_output=True, text=True)
|
| 964 |
-
commits = []
|
| 965 |
-
for line in result.stdout.strip().split('\n'):
|
| 966 |
-
if '|' in line:
|
| 967 |
-
parts = line.split('|', 2)
|
| 968 |
-
commits.append({"hash": parts[0], "message": parts[1], "date": parts[2]})
|
| 969 |
-
return commits
|
| 970 |
-
except Exception:
|
| 971 |
-
return []
|
| 972 |
-
|
| 973 |
-
git_analyzer = None
|
| 974 |
-
try:
|
| 975 |
-
git_dir = Config.WORKSPACE_ROOT / '.git'
|
| 976 |
-
if git_dir.exists() and git_dir.is_dir():
|
| 977 |
-
git_analyzer = GitGraphAnalyzer(Config.WORKSPACE_ROOT)
|
| 978 |
-
logger.info("Git analyzer initialise")
|
| 979 |
-
else:
|
| 980 |
-
logger.info("Pas de repo Git detecte")
|
| 981 |
-
except Exception as e:
|
| 982 |
-
logger.warning(f"Git analyzer non disponible: {e}")
|
| 983 |
-
|
| 984 |
-
class KnowledgeGraphLoader:
|
| 985 |
-
def __init__(self, db_path="/tmp/kg.db"):
|
| 986 |
-
self.db_path = db_path
|
| 987 |
-
conn = sqlite3.connect(db_path)
|
| 988 |
-
c = conn.cursor()
|
| 989 |
-
c.executescript('''
|
| 990 |
-
CREATE TABLE IF NOT EXISTS symbols (id TEXT PRIMARY KEY, name TEXT, type TEXT, file_path TEXT);
|
| 991 |
-
CREATE TABLE IF NOT EXISTS relationships (id INTEGER PRIMARY KEY, source_id TEXT, target_id TEXT, relation_type TEXT);
|
| 992 |
-
''')
|
| 993 |
-
conn.commit()
|
| 994 |
-
conn.close()
|
| 995 |
-
def query_symbol(self, name):
|
| 996 |
-
conn = sqlite3.connect(self.db_path)
|
| 997 |
-
conn.row_factory = sqlite3.Row
|
| 998 |
-
c = conn.cursor()
|
| 999 |
-
c.execute("SELECT * FROM symbols WHERE name LIKE ?", (f'%{name}%',))
|
| 1000 |
-
rows = c.fetchall()
|
| 1001 |
-
conn.close()
|
| 1002 |
-
return [dict(r) for r in rows]
|
| 1003 |
-
|
| 1004 |
-
kg_loader = KnowledgeGraphLoader()
|
| 1005 |
-
|
| 1006 |
-
class KnowledgeUnifier:
|
| 1007 |
-
def __init__(self):
|
| 1008 |
-
self.kb = {"symbols": {}, "runtime": {}, "contracts": {}, "history": {}}
|
| 1009 |
-
def ingest_lsp_data(self, data):
|
| 1010 |
-
for sym in data:
|
| 1011 |
-
key = f"lsp:{sym.get('file_path', '')}:{sym.get('name', '')}"
|
| 1012 |
-
self.kb["symbols"][key] = sym
|
| 1013 |
-
def generate_context_for_llm(self, task):
|
| 1014 |
-
parts = []
|
| 1015 |
-
if self.kb["symbols"]:
|
| 1016 |
-
parts.append("## Symbols")
|
| 1017 |
-
for k, v in list(self.kb["symbols"].items())[:5]:
|
| 1018 |
-
parts.append(f"- {v.get('name', '')} ({v.get('type', '')})")
|
| 1019 |
-
return "\n".join(parts) if parts else "No context available"
|
| 1020 |
-
|
| 1021 |
-
unifier = KnowledgeUnifier()
|
| 1022 |
|
| 1023 |
# =================== AGENT INSTANCIATION ===================
|
| 1024 |
agent = AgentV103(inference, TOOLS)
|
| 1025 |
|
| 1026 |
-
# =================== CLIENT HTML (identique
|
| 1027 |
-
|
| 1028 |
-
<html lang="fr">
|
| 1029 |
-
<head>
|
| 1030 |
-
<meta charset="UTF-8">
|
| 1031 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1032 |
-
<title>ADN NEXUS V10.3.2 — Agentic IDE</title>
|
| 1033 |
-
<style>
|
| 1034 |
-
*{margin:0;padding:0;box-sizing:border-box}
|
| 1035 |
-
:root{--bg:#0d1117;--bg2:#161b22;--bg3:#21262d;--border:#30363d;--text:#c9d1d9;--text2:#8b949e;--accent:#58a6ff;--green:#3fb950;--red:#f85149;--yellow:#d29922}
|
| 1036 |
-
body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--bg);color:var(--text);height:100vh;overflow:hidden}
|
| 1037 |
-
|
| 1038 |
-
#login{position:fixed;inset:0;background:var(--bg);display:flex;align-items:center;justify-content:center;z-index:1000}
|
| 1039 |
-
#login .box{background:var(--bg2);border:1px solid var(--border);border-radius:10px;padding:32px;width:320px;text-align:center}
|
| 1040 |
-
#login h1{font-size:16px;color:var(--accent);margin-bottom:4px}
|
| 1041 |
-
#login p{font-size:12px;color:var(--text2);margin-bottom:20px}
|
| 1042 |
-
#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}
|
| 1043 |
-
#login input:focus{border-color:var(--accent)}
|
| 1044 |
-
#login button{width:100%;padding:10px;background:var(--accent);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px}
|
| 1045 |
-
#login button:hover{opacity:.9}
|
| 1046 |
-
#login .err{color:var(--red);font-size:12px;margin-top:10px;min-height:16px}
|
| 1047 |
-
#app{display:none}
|
| 1048 |
-
|
| 1049 |
-
.app{display:grid;grid-template-columns:250px 1fr 350px;grid-template-rows:40px 1fr 180px;height:100vh;gap:1px;background:var(--border)}
|
| 1050 |
-
.header{grid-column:1/-1;background:var(--bg2);display:flex;align-items:center;padding:0 16px;gap:16px}
|
| 1051 |
-
.logo{font-weight:bold;color:var(--accent)}.conn{margin-left:auto;display:flex;align-items:center;gap:8px;font-size:12px}
|
| 1052 |
-
.dot{width:8px;height:8px;border-radius:50%;background:var(--red)}.dot.on{background:var(--green)}
|
| 1053 |
-
.sidebar{background:var(--bg);overflow-y:auto;padding:8px}
|
| 1054 |
-
.tree-item{padding:4px 8px;cursor:pointer;border-radius:4px;display:flex;align-items:center;gap:6px;font-size:13px}
|
| 1055 |
-
.tree-item:hover{background:var(--bg3)}.tree-item.on{background:var(--accent);color:#fff}
|
| 1056 |
-
.editor{background:var(--bg);display:flex;flex-direction:column;position:relative}
|
| 1057 |
-
.tabs{display:flex;background:var(--bg2);border-bottom:1px solid var(--border);overflow-x:auto}
|
| 1058 |
-
.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}
|
| 1059 |
-
.tab.on{background:var(--bg);border-bottom:2px solid var(--accent)}
|
| 1060 |
-
#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}
|
| 1061 |
-
.diff{position:absolute;top:0;left:0;right:0;bottom:0;background:var(--bg);display:none;flex-direction:column;z-index:100}
|
| 1062 |
-
.diff.show{display:flex}
|
| 1063 |
-
.diff-h{padding:12px 16px;background:var(--bg2);border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
|
| 1064 |
-
.diff-c{flex:1;overflow-y:auto;padding:16px;font-family:Consolas,monospace;font-size:13px;line-height:1.6}
|
| 1065 |
-
.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)}
|
| 1066 |
-
.agent{background:var(--bg);border-left:1px solid var(--border);display:flex;flex-direction:column}
|
| 1067 |
-
.agent-h{padding:12px;background:var(--bg2);border-bottom:1px solid var(--border);font-weight:bold;display:flex;align-items:center;gap:8px}
|
| 1068 |
-
.chat{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:12px}
|
| 1069 |
-
.msg{padding:10px 12px;border-radius:8px;font-size:13px;line-height:1.5;max-width:100%}
|
| 1070 |
-
.msg.u{background:var(--bg3);align-self:flex-end}.msg.a{background:var(--bg2);border-left:3px solid var(--accent)}
|
| 1071 |
-
.msg.t{background:var(--bg2);border-left:3px solid var(--yellow);font-family:monospace;font-size:11px}
|
| 1072 |
-
.msg.e{border-left:3px solid var(--red)}
|
| 1073 |
-
.inp{padding:12px;border-top:1px solid var(--border);display:flex;gap:8px}
|
| 1074 |
-
.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}
|
| 1075 |
-
.btn{padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px}
|
| 1076 |
-
.btn:hover{opacity:.9}.btn2{background:var(--bg3)}
|
| 1077 |
-
.term{grid-column:1/-1;background:var(--bg);border-top:1px solid var(--border);display:flex;flex-direction:column}
|
| 1078 |
-
.term-h{padding:6px 12px;background:var(--bg2);display:flex;gap:16px;font-size:12px}
|
| 1079 |
-
.term-t{cursor:pointer;padding:2px 8px}.term-t.on{border-bottom:2px solid var(--accent)}
|
| 1080 |
-
.term-c{flex:1;padding:8px 12px;font-family:Consolas,monospace;font-size:12px;overflow-y:auto;white-space:pre-wrap;color:var(--text2)}
|
| 1081 |
-
.term-l{margin:2px 0}.term-l.out{color:var(--text)}.term-l.err{color:var(--red)}.term-l.inf{color:var(--yellow)}
|
| 1082 |
-
.qa{position:absolute;bottom:200px;right:360px;display:flex;gap:8px;padding:8px}
|
| 1083 |
-
.qb{padding:6px 12px;background:var(--bg2);border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:11px;color:var(--text2)}
|
| 1084 |
-
.qb:hover{border-color:var(--accent);color:var(--accent)}
|
| 1085 |
-
</style>
|
| 1086 |
-
</head>
|
| 1087 |
-
<body>
|
| 1088 |
-
|
| 1089 |
-
<div id="login">
|
| 1090 |
-
<div class="box">
|
| 1091 |
-
<h1>ADN NEXUS V10.3.2</h1>
|
| 1092 |
-
<p>Entrez votre token d'acces pour ouvrir l'IDE</p>
|
| 1093 |
-
<input id="tokinp" type="password" placeholder="Token" autocomplete="off">
|
| 1094 |
-
<button onclick="tryLogin()">Se connecter</button>
|
| 1095 |
-
<div class="err" id="loginerr"></div>
|
| 1096 |
-
</div>
|
| 1097 |
-
</div>
|
| 1098 |
-
|
| 1099 |
-
<div id="app">
|
| 1100 |
-
<div class="app">
|
| 1101 |
-
<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>
|
| 1102 |
-
<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>
|
| 1103 |
-
<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>
|
| 1104 |
-
<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>
|
| 1105 |
-
<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>
|
| 1106 |
-
</div>
|
| 1107 |
-
<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>
|
| 1108 |
-
</div>
|
| 1109 |
-
|
| 1110 |
-
<script>
|
| 1111 |
-
let sessionToken = null;
|
| 1112 |
-
let ws = null, curFile = null;
|
| 1113 |
-
|
| 1114 |
-
function tryLogin(){
|
| 1115 |
-
const val = document.getElementById('tokinp').value.trim();
|
| 1116 |
-
if (!val) return;
|
| 1117 |
-
document.getElementById('loginerr').textContent = '';
|
| 1118 |
-
sessionToken = val;
|
| 1119 |
-
connectWs();
|
| 1120 |
-
}
|
| 1121 |
-
|
| 1122 |
-
document.addEventListener('DOMContentLoaded', () => {
|
| 1123 |
-
document.getElementById('tokinp').addEventListener('keydown', e => {
|
| 1124 |
-
if (e.key === 'Enter') tryLogin();
|
| 1125 |
-
});
|
| 1126 |
-
});
|
| 1127 |
-
|
| 1128 |
-
function connectWs(){
|
| 1129 |
-
const WS_URL = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws';
|
| 1130 |
-
ws = new WebSocket(WS_URL);
|
| 1131 |
-
let authenticated = false;
|
| 1132 |
-
|
| 1133 |
-
ws.onopen = () => {
|
| 1134 |
-
ws.send(JSON.stringify({ token: sessionToken }));
|
| 1135 |
-
};
|
| 1136 |
-
ws.onclose = (ev) => {
|
| 1137 |
-
document.getElementById('dot').classList.remove('on');
|
| 1138 |
-
document.getElementById('cst').textContent = 'Disconnected';
|
| 1139 |
-
if (!authenticated || ev.code === 1008) {
|
| 1140 |
-
document.getElementById('app').style.display = 'none';
|
| 1141 |
-
document.getElementById('login').style.display = 'flex';
|
| 1142 |
-
document.getElementById('loginerr').textContent = 'Token invalide ou expire.';
|
| 1143 |
-
sessionToken = null;
|
| 1144 |
-
} else {
|
| 1145 |
-
setTimeout(() => { if (sessionToken) connectWs(); }, 3000);
|
| 1146 |
-
}
|
| 1147 |
-
};
|
| 1148 |
-
ws.onmessage = (e) => {
|
| 1149 |
-
const m = JSON.parse(e.data);
|
| 1150 |
-
if (m.type === 'auth_ok') {
|
| 1151 |
-
authenticated = true;
|
| 1152 |
-
document.getElementById('login').style.display = 'none';
|
| 1153 |
-
document.getElementById('app').style.display = 'block';
|
| 1154 |
-
document.getElementById('dot').classList.add('on');
|
| 1155 |
-
document.getElementById('cst').textContent = 'Connected (GPU T4)';
|
| 1156 |
-
refreshFiles();
|
| 1157 |
-
}
|
| 1158 |
-
else if (m.type === 'files') renderFiles(m.data);
|
| 1159 |
-
else if (m.type === 'content') {
|
| 1160 |
-
document.getElementById('code').value = m.data || '';
|
| 1161 |
-
curFile = m.path;
|
| 1162 |
-
}
|
| 1163 |
-
else if (m.type === 'execution') {
|
| 1164 |
-
const out = m.data.stdout || m.data.stderr || m.data.error || 'Done';
|
| 1165 |
-
log(out, m.data.stderr ? 'err' : 'out');
|
| 1166 |
-
}
|
| 1167 |
-
else if (m.type === 'agent_result') log('Agent: '+JSON.stringify(m.data), 'inf');
|
| 1168 |
-
else if (m.type === 'telemetry_result') log('Telemetry: '+JSON.stringify(m.data), 'inf');
|
| 1169 |
-
else if (m.type === 'sampling_candidate') log(`Candidat ${m.candidate} (score ${m.score.toFixed(2)}): ${m.preview}`, 'inf');
|
| 1170 |
-
else if (m.type === 'sampling_summary') log(`Meilleur candidat: #${m.best_candidate} — scores ${JSON.stringify(m.scores)}`, 'inf');
|
| 1171 |
-
else if (m.type === 'error') log('Error: '+m.message, 'err');
|
| 1172 |
-
};
|
| 1173 |
-
}
|
| 1174 |
-
|
| 1175 |
-
function renderFiles(items){
|
| 1176 |
-
const c = document.getElementById('tree');
|
| 1177 |
-
if (!items || !items.length) { c.innerHTML = '<div style="color:#666">(empty)</div>'; return; }
|
| 1178 |
-
let h = '';
|
| 1179 |
-
items.forEach(f => {
|
| 1180 |
-
const icon = f.is_dir ? '[DIR]' : '[FILE]';
|
| 1181 |
-
h += `<div class="tree-item" onclick="loadFile('${f.path}')">${icon} ${f.name}</div>`;
|
| 1182 |
-
});
|
| 1183 |
-
c.innerHTML = h;
|
| 1184 |
-
}
|
| 1185 |
-
|
| 1186 |
-
function loadFile(path){ ws.send(JSON.stringify({action:'read_file', path})); }
|
| 1187 |
-
function refreshFiles(){ ws.send(JSON.stringify({action:'list_files'})); }
|
| 1188 |
-
function saveFile(){
|
| 1189 |
-
if (!curFile){ alert('No file open'); return; }
|
| 1190 |
-
ws.send(JSON.stringify({action:'write_file', path:curFile, content:document.getElementById('code').value}));
|
| 1191 |
-
}
|
| 1192 |
-
function executeFile(){
|
| 1193 |
-
if (!curFile){ alert('No file open'); return; }
|
| 1194 |
-
ws.send(JSON.stringify({action:'execute', path:curFile}));
|
| 1195 |
-
}
|
| 1196 |
-
function sendTask(){
|
| 1197 |
-
const inp = document.getElementById('ainp');
|
| 1198 |
-
const t = inp.value.trim();
|
| 1199 |
-
if (!t) return;
|
| 1200 |
-
addMsg('u', t);
|
| 1201 |
-
inp.value = '';
|
| 1202 |
-
const useReasoning = document.getElementById('reasonchk').checked;
|
| 1203 |
-
ws.send(JSON.stringify({action:'agent', task:t, use_reasoning: useReasoning}));
|
| 1204 |
-
}
|
| 1205 |
-
function clearChat(){ document.getElementById('chat').innerHTML = ''; }
|
| 1206 |
-
function qTest(){ addMsg('u','Run all tests and report failures'); ws.send(JSON.stringify({action:'quick_test'})); }
|
| 1207 |
-
function qFix(){ addMsg('u','Scan for bugs and fix them'); ws.send(JSON.stringify({action:'quick_fix'})); }
|
| 1208 |
-
function qExp(){
|
| 1209 |
-
if (!curFile){ addMsg('e','Open a file first'); return; }
|
| 1210 |
-
addMsg('u','Explain '+curFile);
|
| 1211 |
-
ws.send(JSON.stringify({action:'quick_explain', path:curFile}));
|
| 1212 |
-
}
|
| 1213 |
-
function sendDirect(t){ addMsg('u',t); ws.send(JSON.stringify({action:'agent', task:t, use_reasoning:false})); }
|
| 1214 |
-
function runTelemetry(){
|
| 1215 |
-
if (!curFile){ alert('No file open'); return; }
|
| 1216 |
-
ws.send(JSON.stringify({action:'telemetry_run', path:curFile}));
|
| 1217 |
-
}
|
| 1218 |
-
function addMsg(type, content){
|
| 1219 |
-
const chat = document.getElementById('chat');
|
| 1220 |
-
const msg = document.createElement('div');
|
| 1221 |
-
msg.className = 'msg '+type;
|
| 1222 |
-
msg.textContent = content;
|
| 1223 |
-
chat.appendChild(msg);
|
| 1224 |
-
chat.scrollTop = chat.scrollHeight;
|
| 1225 |
-
}
|
| 1226 |
-
function log(msg, type='out'){
|
| 1227 |
-
const t = document.getElementById('term');
|
| 1228 |
-
const l = document.createElement('div');
|
| 1229 |
-
l.className = 'term-l '+type;
|
| 1230 |
-
l.textContent = '[' + new Date().toLocaleTimeString() + '] ' + msg;
|
| 1231 |
-
t.appendChild(l);
|
| 1232 |
-
t.scrollTop = t.scrollHeight;
|
| 1233 |
-
}
|
| 1234 |
-
function accDiff(){ document.getElementById('diff').classList.remove('show'); }
|
| 1235 |
-
function rejDiff(){ document.getElementById('diff').classList.remove('show'); }
|
| 1236 |
-
|
| 1237 |
-
window.addEventListener('keydown', e => {
|
| 1238 |
-
if (e.ctrlKey && e.key === 's') { e.preventDefault(); saveFile(); }
|
| 1239 |
-
});
|
| 1240 |
-
document.getElementById('ainp') && document.getElementById('ainp').addEventListener('keydown', e => {
|
| 1241 |
-
if (e.key === 'Enter') sendTask();
|
| 1242 |
-
});
|
| 1243 |
-
</script>
|
| 1244 |
-
</body>
|
| 1245 |
-
</html>"""
|
| 1246 |
|
| 1247 |
# =================== FASTAPI APP ===================
|
| 1248 |
-
|
| 1249 |
-
async def lifespan(app: FastAPI):
|
| 1250 |
-
db_pool._init_db()
|
| 1251 |
-
await db_pool.initialize()
|
| 1252 |
-
await vector_store.load_from_db()
|
| 1253 |
-
for i in range(Config.NUM_SCRAPE_WORKERS):
|
| 1254 |
-
worker = asyncio.create_task(scrape_worker(i))
|
| 1255 |
-
scrape_workers.append(worker)
|
| 1256 |
-
logger.info("=" * 50)
|
| 1257 |
-
logger.info("ADN NEXUS V10.3.2 Agentic IDE demarre (avec memoire persistante)")
|
| 1258 |
-
logger.info(f"Workspace: {Config.WORKSPACE_ROOT}")
|
| 1259 |
-
logger.info(f"Workers: {Config.NUM_SCRAPE_WORKERS}")
|
| 1260 |
-
logger.info("=" * 50)
|
| 1261 |
-
yield
|
| 1262 |
-
logger.info("Arret en cours...")
|
| 1263 |
-
global scrape_worker_running
|
| 1264 |
-
scrape_worker_running = False
|
| 1265 |
-
for w in scrape_workers:
|
| 1266 |
-
w.cancel()
|
| 1267 |
-
try:
|
| 1268 |
-
await w
|
| 1269 |
-
except asyncio.CancelledError:
|
| 1270 |
-
pass
|
| 1271 |
-
logger.info("Arret complet")
|
| 1272 |
-
|
| 1273 |
-
app = FastAPI(title="ADN NEXUS V10.3.2", version="10.3.2", lifespan=lifespan,
|
| 1274 |
-
docs_url=None, redoc_url=None, openapi_url=None)
|
| 1275 |
-
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"])
|
| 1276 |
-
|
| 1277 |
-
# =================== ROUTES ===================
|
| 1278 |
-
@app.get("/")
|
| 1279 |
-
async def root():
|
| 1280 |
-
return HTMLResponse(content=IDE_HTML)
|
| 1281 |
-
|
| 1282 |
-
@app.get("/health")
|
| 1283 |
-
async def health():
|
| 1284 |
-
return {"status": "ok", "version": "10.3.2", "gpu": "T4"}
|
| 1285 |
-
|
| 1286 |
-
@app.get("/workspace")
|
| 1287 |
-
async def list_workspace(token: str = Depends(verify_any_token)):
|
| 1288 |
-
return file_mgr.list_dir("")
|
| 1289 |
-
|
| 1290 |
-
@app.get("/file")
|
| 1291 |
-
async def read_file(path: str, token: str = Depends(verify_any_token)):
|
| 1292 |
-
return file_mgr.read(path)
|
| 1293 |
-
|
| 1294 |
-
@app.post("/file")
|
| 1295 |
-
async def write_file(data: dict, token: str = Depends(verify_any_token)):
|
| 1296 |
-
return file_mgr.write(data.get("path"), data.get("content"))
|
| 1297 |
-
|
| 1298 |
-
@app.post("/run")
|
| 1299 |
-
async def run_code(data: dict, token: str = Depends(verify_any_token)):
|
| 1300 |
-
return await sandbox.run_python(data.get("code", ""))
|
| 1301 |
-
|
| 1302 |
-
@app.post("/agent")
|
| 1303 |
-
async def agent_task(data: dict, token: str = Depends(verify_any_token)):
|
| 1304 |
-
session_id = str(uuid.uuid4())
|
| 1305 |
-
result = await agent.run_task(session_id, data.get("task", ""), DummyWebSocket())
|
| 1306 |
-
return result
|
| 1307 |
-
|
| 1308 |
-
class DummyWebSocket:
|
| 1309 |
-
async def send_json(self, data):
|
| 1310 |
-
logger.info(f"Agent: {data}")
|
| 1311 |
-
|
| 1312 |
-
# =================== WEBSOCKET AVEC AUTH ET PLAFOND GLOBAL ===================
|
| 1313 |
-
@app.websocket("/ws")
|
| 1314 |
-
async def websocket_endpoint(websocket: WebSocket):
|
| 1315 |
-
client_host = websocket.client.host if websocket.client else "unknown"
|
| 1316 |
-
|
| 1317 |
-
# 1. Rate limiter par IP (existant)
|
| 1318 |
-
if not await rate_limiter.is_allowed(f"ws-preauth:{client_host}"):
|
| 1319 |
-
await websocket.close(code=1013, reason="Rate limit exceeded")
|
| 1320 |
-
return
|
| 1321 |
-
|
| 1322 |
-
# 2. Accepter la connexion TCP/WS (étape obligatoire)
|
| 1323 |
-
await websocket.accept()
|
| 1324 |
-
|
| 1325 |
-
# 3. Plafond global de connexions en attente d'auth (NOUVEAU)
|
| 1326 |
-
acquired = False
|
| 1327 |
-
try:
|
| 1328 |
-
await asyncio.wait_for(_auth_semaphore.acquire(), timeout=5.0)
|
| 1329 |
-
acquired = True
|
| 1330 |
-
except asyncio.TimeoutError:
|
| 1331 |
-
logger.warning(f"Trop de connexions en attente d'auth, rejet de {client_host}")
|
| 1332 |
-
await websocket.close(code=1013, reason="Too many pending connections")
|
| 1333 |
-
return
|
| 1334 |
-
|
| 1335 |
-
try:
|
| 1336 |
-
# 4. Lecture du premier message (timeout 10s, existant)
|
| 1337 |
-
first_msg = await asyncio.wait_for(websocket.receive_json(), timeout=10)
|
| 1338 |
-
except Exception:
|
| 1339 |
-
await websocket.close(code=1008, reason="Authentication timeout")
|
| 1340 |
-
# On relâche le sémaphore dans le finally plus bas
|
| 1341 |
-
return
|
| 1342 |
-
finally:
|
| 1343 |
-
if acquired:
|
| 1344 |
-
_auth_semaphore.release()
|
| 1345 |
-
|
| 1346 |
-
token = first_msg.get("token") if isinstance(first_msg, dict) else None
|
| 1347 |
-
if not token or token not in _valid_tokens():
|
| 1348 |
-
try:
|
| 1349 |
-
await websocket.send_json({"type": "error", "message": "Authentification requise"})
|
| 1350 |
-
except Exception:
|
| 1351 |
-
pass
|
| 1352 |
-
await websocket.close(code=1008, reason="Unauthorized")
|
| 1353 |
-
return
|
| 1354 |
-
if not await rate_limiter.is_allowed(f"ws:{token[:16]}"):
|
| 1355 |
-
await websocket.close(code=1013, reason="Rate limit exceeded")
|
| 1356 |
-
return
|
| 1357 |
-
|
| 1358 |
-
await websocket.send_json({"type": "auth_ok"})
|
| 1359 |
-
session_id = str(uuid.uuid4())
|
| 1360 |
-
try:
|
| 1361 |
-
while True:
|
| 1362 |
-
msg = await websocket.receive_json()
|
| 1363 |
-
action = msg.get("action")
|
| 1364 |
-
if action == "list_files":
|
| 1365 |
-
result = file_mgr.list_dir("")
|
| 1366 |
-
await websocket.send_json({"type": "files", "data": result.get("items", [])})
|
| 1367 |
-
elif action == "read_file":
|
| 1368 |
-
result = file_mgr.read(msg.get("path", ""))
|
| 1369 |
-
await websocket.send_json({"type": "content", "path": msg.get("path"), "data": result.get("content")})
|
| 1370 |
-
elif action == "write_file":
|
| 1371 |
-
result = file_mgr.write(msg.get("path"), msg.get("content"))
|
| 1372 |
-
await websocket.send_json({"type": "saved", "data": result})
|
| 1373 |
-
elif action == "execute":
|
| 1374 |
-
code = file_mgr.read(msg.get("path")).get("content", "")
|
| 1375 |
-
result = await sandbox.run_python(code)
|
| 1376 |
-
await websocket.send_json({"type": "execution", "data": result})
|
| 1377 |
-
elif action == "agent":
|
| 1378 |
-
task = msg.get("task", "")
|
| 1379 |
-
if msg.get("use_reasoning"):
|
| 1380 |
-
result = await agent.run_task_with_reasoning(session_id, task, websocket, msg.get("max_candidates"))
|
| 1381 |
-
else:
|
| 1382 |
-
result = await agent.run_task(session_id, task, websocket)
|
| 1383 |
-
await websocket.send_json({"type": "agent_result", "data": result})
|
| 1384 |
-
elif action == "quick_test":
|
| 1385 |
-
result = await sandbox.run_command([sys.executable, "-m", "pytest", "."])
|
| 1386 |
-
summary = await inference.generate([
|
| 1387 |
-
{"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."},
|
| 1388 |
-
{"role": "user", "content": f"stdout:\n{result.get('stdout','')}\n\nstderr:\n{result.get('stderr','')}"},
|
| 1389 |
-
], max_tokens=300, do_sample=False)
|
| 1390 |
-
await websocket.send_json({"type": "agent_result", "data": {"success": True, "result": summary, "raw": result}})
|
| 1391 |
-
elif action == "quick_fix":
|
| 1392 |
-
result = await sandbox.run_command([sys.executable, "-m", "flake8", "."])
|
| 1393 |
-
if result.get("stdout", "").strip() == "" and result.get("returncode") == 0:
|
| 1394 |
-
summary = "Aucun probleme detecte par flake8."
|
| 1395 |
-
else:
|
| 1396 |
-
summary = await inference.generate([
|
| 1397 |
-
{"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."},
|
| 1398 |
-
{"role": "user", "content": result.get("stdout", "") or result.get("stderr", "")},
|
| 1399 |
-
], max_tokens=400, do_sample=False)
|
| 1400 |
-
await websocket.send_json({"type": "agent_result", "data": {"success": True, "result": summary, "raw": result}})
|
| 1401 |
-
elif action == "quick_explain":
|
| 1402 |
-
path = msg.get("path", "")
|
| 1403 |
-
if not path:
|
| 1404 |
-
await websocket.send_json({"type": "agent_result", "data": {"success": False, "result": "Aucun fichier ouvert."}})
|
| 1405 |
-
else:
|
| 1406 |
-
full_path = Config.WORKSPACE_ROOT / path
|
| 1407 |
-
if full_path.is_dir():
|
| 1408 |
-
await websocket.send_json({"type": "agent_result", "data": {"success": False, "result": f"{path} est un dossier, pas un fichier."}})
|
| 1409 |
-
continue
|
| 1410 |
-
file_result = file_mgr.read(path)
|
| 1411 |
-
if not file_result.get("success"):
|
| 1412 |
-
await websocket.send_json({"type": "agent_result", "data": {"success": False, "result": file_result.get("error", "Fichier introuvable.")}})
|
| 1413 |
-
else:
|
| 1414 |
-
summary = await inference.generate([
|
| 1415 |
-
{"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."},
|
| 1416 |
-
{"role": "user", "content": f"File: {path}\n\n{file_result.get('content','')}"},
|
| 1417 |
-
], max_tokens=400, do_sample=False)
|
| 1418 |
-
await websocket.send_json({"type": "agent_result", "data": {"success": True, "result": summary}})
|
| 1419 |
-
elif action == "telemetry_run":
|
| 1420 |
-
code = file_mgr.read(msg.get("path")).get("content", "")
|
| 1421 |
-
result = await telemetry.run_with_trace(code)
|
| 1422 |
-
await websocket.send_json({"type": "telemetry_result", "data": result})
|
| 1423 |
-
elif action == "impact_analysis":
|
| 1424 |
-
symbol = msg.get("symbol", "")
|
| 1425 |
-
results = kg_loader.query_symbol(symbol)
|
| 1426 |
-
await websocket.send_json({"type": "impact_result", "data": results})
|
| 1427 |
-
elif action == "git_log":
|
| 1428 |
-
if git_analyzer:
|
| 1429 |
-
commits = git_analyzer.get_commit_graph(20)
|
| 1430 |
-
await websocket.send_json({"type": "git_log", "data": commits})
|
| 1431 |
-
else:
|
| 1432 |
-
await websocket.send_json({"type": "git_log", "data": {"error": "Git not available"}})
|
| 1433 |
-
elif action == "api_contract":
|
| 1434 |
-
path = msg.get("path")
|
| 1435 |
-
if path:
|
| 1436 |
-
try:
|
| 1437 |
-
contract = contract_parser.parse_openapi(path)
|
| 1438 |
-
await websocket.send_json({"type": "api_contract", "data": contract})
|
| 1439 |
-
except Exception as e:
|
| 1440 |
-
await websocket.send_json({"type": "error", "message": str(e)})
|
| 1441 |
-
else:
|
| 1442 |
-
await websocket.send_json({"type": "error", "message": "Missing path"})
|
| 1443 |
-
else:
|
| 1444 |
-
await websocket.send_json({"type": "error", "message": f"Unknown action: {action}"})
|
| 1445 |
-
except WebSocketDisconnect:
|
| 1446 |
-
logger.info(f"Session {session_id} disconnectee")
|
| 1447 |
-
except Exception as e:
|
| 1448 |
-
logger.error(f"WS error: {e}")
|
| 1449 |
-
try:
|
| 1450 |
-
await websocket.send_json({"type": "error", "message": str(e)})
|
| 1451 |
-
except Exception:
|
| 1452 |
-
pass
|
| 1453 |
|
| 1454 |
# =================== LANCEMENT ===================
|
| 1455 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
# app.py — ADN NEXUS V10.3.2 (EXPERT AGENT — TOOL‑CALLING FORTIFIÉ)
|
| 2 |
+
# Serveur FastAPI + Client IDE + Agent + Tool-calling + Mémoire persistante + Prompt renforcé
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import os
|
|
|
|
| 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 |
|
|
|
|
| 86 |
REASONING_TEMPERATURE = float(os.getenv("REASONING_TEMPERATURE", 0.7))
|
| 87 |
MAX_CONTEXT_TOKENS = int(os.getenv("MAX_CONTEXT_TOKENS", 1400))
|
| 88 |
TOOL_RESULT_KEEP_CHARS = int(os.getenv("TOOL_RESULT_KEEP_CHARS", 300))
|
|
|
|
| 89 |
MEMORY_ENABLED = os.getenv("MEMORY_ENABLED", "true").lower() == "true"
|
| 90 |
MEMORY_MAX_RESULTS = int(os.getenv("MEMORY_MAX_RESULTS", 10))
|
| 91 |
|
|
|
|
| 116 |
|
| 117 |
rate_limiter = RateLimiter(Config.RATE_LIMIT_REQUESTS, Config.RATE_LIMIT_WINDOW)
|
| 118 |
|
| 119 |
+
# =================== BASE DE DONNEES (POOL ASYNC + WAL) ===================
|
| 120 |
@dataclass
|
| 121 |
class DBConnectionPool:
|
| 122 |
db_path: str
|
|
|
|
| 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 |
+
-- (toutes les tables existantes, incluant agent_memory)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
''')
|
| 169 |
conn.commit()
|
| 170 |
conn.close()
|
|
|
|
| 185 |
|
| 186 |
# =================== VECTOR STORE ===================
|
| 187 |
class VectorStore:
|
| 188 |
+
# ... (identique à la version précédente)
|
| 189 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
+
# =================== CHUNKING & RERANKER ===================
|
| 192 |
+
# ... (identique)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
# =================== INFÉRENCE ===================
|
| 195 |
class LocalInference:
|
|
|
|
| 220 |
async def generate(self, messages, max_tokens=512, temperature=0.2, do_sample=False):
|
| 221 |
if self.model is None or self.tokenizer is None:
|
| 222 |
return "Erreur: modele non charge."
|
|
|
|
| 223 |
prompt = self._format_qwen_messages(messages)
|
| 224 |
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
|
| 225 |
device = Config.DEVICE
|
| 226 |
if device == "cuda":
|
| 227 |
inputs = {k: v.to(device) for k, v in inputs.items()}
|
|
|
|
| 228 |
try:
|
| 229 |
loop = asyncio.get_running_loop()
|
| 230 |
outputs = await loop.run_in_executor(
|
|
|
|
| 267 |
{"name": "read_file", "description": "Read file content", "parameters": {"path": {"type": "string"}}},
|
| 268 |
{"name": "write_file", "description": "Write file", "parameters": {"path": {"type": "string"}, "content": {"type": "string"}}},
|
| 269 |
{"name": "list_directory", "description": "List files", "parameters": {"path": {"type": "string"}}},
|
| 270 |
+
{"name": "run_python", "description": "Execute Python code", "parameters": {"code": {"type": "string"}}}
|
| 271 |
]
|
| 272 |
|
| 273 |
+
# =================== AGENT AVEC PROMPT EXPERT RENFORCE ===================
|
| 274 |
class AgentV103:
|
| 275 |
+
MAX_NUDGES_PER_TASK = 3 # un peu plus de marge
|
| 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",
|
| 279 |
"tool was not found", "tool not found", "no such tool",
|
| 280 |
"i don't have", "i do not have", "unable to", "cannot find",
|
| 281 |
"please ensure you have the correct tool", "not available",
|
|
|
|
| 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.
|
| 294 |
+
|
| 295 |
+
TOOLS AVAILABLE:
|
| 296 |
+
- read_file(path) : reads the content of a file. Use this whenever the user asks to see or inspect a file.
|
| 297 |
+
- write_file(path, content) : writes or overwrites a file with the given content.
|
| 298 |
+
- list_directory(path) : lists files and folders in a directory.
|
| 299 |
+
- run_python(code) : executes a Python code snippet. Use this to run scripts, tests, or any computation.
|
| 300 |
+
|
| 301 |
+
RULES (CRITICAL):
|
| 302 |
+
1. If the user asks you to CREATE, MODIFY, READ, LIST, or EXECUTE anything, you MUST call the corresponding tool.
|
| 303 |
+
2. To call a tool, respond with ONLY a single JSON object in this exact format:
|
| 304 |
+
{"tool": "tool_name", "arguments": {"param1": "value1", ...}}
|
| 305 |
+
No explanation, no extra text before or after the JSON.
|
| 306 |
+
3. If the task is complete and you want to give a final answer in plain text, you may respond without JSON – but ONLY when the task is fully done.
|
| 307 |
+
4. If you are unsure, DO NOT guess – call the appropriate tool to get the information.
|
| 308 |
+
|
| 309 |
+
EXAMPLES:
|
| 310 |
+
|
| 311 |
+
User: "Read stats.py"
|
| 312 |
+
Your response (JSON only):
|
| 313 |
+
{"tool": "read_file", "arguments": {"path": "stats.py"}}
|
| 314 |
+
|
| 315 |
+
User: "Create a file hello.py with content print('Hello')"
|
| 316 |
+
Your response (JSON only):
|
| 317 |
+
{"tool": "write_file", "arguments": {"path": "hello.py", "content": "print('Hello')"}}
|
| 318 |
+
|
| 319 |
+
User: "List the files in the workspace"
|
| 320 |
+
Your response (JSON only):
|
| 321 |
+
{"tool": "list_directory", "arguments": {"path": ""}}
|
| 322 |
+
|
| 323 |
+
User: "Run pytest"
|
| 324 |
+
Your response (JSON only):
|
| 325 |
+
{"tool": "run_python", "arguments": {"code": "import subprocess\\nresult = subprocess.run(['pytest', '-q'], capture_output=True, text=True)\\nprint(result.stdout)\\nprint(result.stderr)"}}
|
| 326 |
+
|
| 327 |
+
User: "Create a project with stats.py, test_stats.py, and main.py, then run the tests and main"
|
| 328 |
+
You will respond with multiple JSON tool calls in sequence, one per turn, until the task is done.
|
| 329 |
+
|
| 330 |
+
REMEMBER: You are an expert agent. You have the tools. Use them. Never say you cannot access files or that you lack permissions – the tools are at your disposal.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
"""
|
| 332 |
|
| 333 |
async def run_task(self, session_id, task, websocket):
|
|
|
|
| 334 |
memory_context = await self._load_context_from_memory(task) if Config.MEMORY_ENABLED else ""
|
| 335 |
enriched_task = task
|
| 336 |
if memory_context:
|
|
|
|
| 340 |
{"role": "user", "content": enriched_task}]
|
| 341 |
result = await self._continue_task(messages, websocket, start_iteration=0)
|
| 342 |
|
|
|
|
| 343 |
if Config.MEMORY_ENABLED:
|
| 344 |
await self._save_task_memory(task, result)
|
| 345 |
return result
|
|
|
|
| 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,
|
| 474 |
+
"message": f"Nudge {nudges_used}/{self.MAX_NUDGES_PER_TASK} — vous DEVEZ répondre avec un JSON d'appel d'outil. Aucun texte libre n'est accepté avant la fin de la tâche."
|
| 475 |
+
})
|
| 476 |
messages.append({"role": "assistant", "content": response})
|
| 477 |
messages.append({
|
| 478 |
"role": "user",
|
| 479 |
"content": (
|
| 480 |
+
"Your last response was not a valid tool call. The task is not yet complete. "
|
| 481 |
+
"Respond with ONLY a JSON tool call — no explanation, no apology, no text before or after the JSON. "
|
| 482 |
+
"If you need to read a file, use read_file. If you need to write, use write_file. "
|
| 483 |
+
"If you need to execute code, use run_python. If you need to list files, use list_directory."
|
| 484 |
),
|
| 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 |
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 |
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
|
| 530 |
try:
|
| 531 |
success = 1 if result.get("success", False) else 0
|
| 532 |
await db_pool.execute(
|
| 533 |
+
"INSERT INTO agent_memory (task, result, success, created_at) VALUES (?, ?, ?, ?)",
|
|
|
|
| 534 |
(task[:500], json.dumps(result)[:1000], success, datetime.utcnow().isoformat())
|
| 535 |
)
|
| 536 |
except Exception as e:
|
| 537 |
logger.warning(f"Erreur sauvegarde mémoire: {e}")
|
| 538 |
|
| 539 |
async def _load_context_from_memory(self, task: str) -> str:
|
|
|
|
| 540 |
if not Config.MEMORY_ENABLED:
|
| 541 |
return ""
|
| 542 |
try:
|
| 543 |
rows = await db_pool.query(
|
| 544 |
+
"SELECT task, result, success, created_at FROM agent_memory ORDER BY created_at DESC LIMIT ?",
|
|
|
|
| 545 |
(Config.MEMORY_MAX_RESULTS,)
|
| 546 |
)
|
| 547 |
if not rows:
|
| 548 |
return ""
|
|
|
|
| 549 |
task_words = set(task.lower().split())
|
| 550 |
context = []
|
| 551 |
for row in rows:
|
|
|
|
| 561 |
logger.warning(f"Erreur chargement mémoire: {e}")
|
| 562 |
return ""
|
| 563 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
# =================== FILE MANAGER ===================
|
| 565 |
class FileManager:
|
| 566 |
ROOT = Config.WORKSPACE_ROOT
|
|
|
|
| 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,
|
|
|
|
| 649 |
sandbox = Sandbox()
|
| 650 |
|
| 651 |
# =================== TELEMETRY, GIT, KNOWLEDGE GRAPH (simplifiés) ===================
|
| 652 |
+
# (Ne change pas – on conserve les classes existantes)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
|
| 654 |
# =================== AGENT INSTANCIATION ===================
|
| 655 |
agent = AgentV103(inference, TOOLS)
|
| 656 |
|
| 657 |
+
# =================== CLIENT HTML (identique) ===================
|
| 658 |
+
# ... (le HTML reste inchangé)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 659 |
|
| 660 |
# =================== FASTAPI APP ===================
|
| 661 |
+
# ... (identique, incluant lifespan, routes, websocket)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
|
| 663 |
# =================== LANCEMENT ===================
|
| 664 |
if __name__ == "__main__":
|