#!/usr/bin/env python3 """ Correction définitive : Modifier l'agent v0 pour charger automatiquement .env.local """ import os from pathlib import Path def load_env_file(env_path): """Charge un fichier .env dans les variables d'environnement""" if not env_path.exists(): return False print(f"📁 Chargement de {env_path}") with open(env_path, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) os.environ[key.strip()] = value.strip() if key.strip() in ['RPA_TOKEN_ADMIN', 'RPA_TOKEN_READONLY']: print(f" ✓ {key.strip()}: {value.strip()[:16]}...") return True def fix_agent_config(): """Modifie config.py de l'agent v0 pour charger .env.local automatiquement""" print("🔧 === CORRECTION AGENT V0 - CHARGEMENT .env.local ===") config_path = Path("agent_v0/config.py") if not config_path.exists(): print("❌ Fichier agent_v0/config.py non trouvé") return False # Lire le fichier actuel with open(config_path, 'r') as f: content = f.read() # Vérifier si la correction est déjà appliquée if "load_env_file" in content: print("✅ Correction déjà appliquée dans config.py") return True # Ajouter le code de chargement .env.local au début env_loading_code = ''' # Chargement automatique de .env.local depuis le répertoire parent def load_env_file(env_path): """Charge un fichier .env dans les variables d'environnement""" if not env_path.exists(): return False with open(env_path, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) os.environ[key.strip()] = value.strip() return True # Charger .env.local depuis le répertoire parent (racine du projet) env_local_path = BASE_DIR.parent / ".env.local" if load_env_file(env_local_path): print(f"[agent_v0] Variables d'environnement chargées depuis {env_local_path}") ''' # Insérer le code après les imports mais avant les autres définitions lines = content.split('\n') insert_index = -1 # Trouver la ligne après les imports for i, line in enumerate(lines): if line.startswith('BASE_DIR = '): insert_index = i + 1 break if insert_index == -1: print("❌ Impossible de trouver l'endroit où insérer le code") return False # Insérer le code lines.insert(insert_index, env_loading_code) new_content = '\n'.join(lines) # Sauvegarder le fichier modifié with open(config_path, 'w') as f: f.write(new_content) print("✅ Fichier config.py modifié avec succès") return True def test_fix(): """Teste la correction en simulant le chargement""" print("\n🧪 === TEST DE LA CORRECTION ===") # Simuler le chargement comme le ferait l'agent v0 base_dir = Path("agent_v0").resolve() env_local_path = base_dir.parent / ".env.local" if load_env_file(env_local_path): print("✅ .env.local chargé avec succès") # Vérifier le token token = os.environ.get('RPA_TOKEN_ADMIN') if token: print(f"✅ Token RPA_TOKEN_ADMIN disponible: {token[:16]}...") # Test d'authentification import requests try: response = requests.get( "http://localhost:8000/api/traces/status", headers={"Authorization": f"Bearer {token}"}, timeout=5 ) if response.status_code == 200: print("✅ Test d'authentification réussi!") return True else: print(f"❌ Test d'authentification échoué: {response.status_code}") return False except Exception as e: print(f"❌ Erreur test d'authentification: {e}") return False else: print("❌ Token RPA_TOKEN_ADMIN non trouvé") return False else: print("❌ Impossible de charger .env.local") return False def main(): """Correction complète""" print("🎯 === CORRECTION DÉFINITIVE AGENT V0 ===") # Étape 1: Modifier config.py if not fix_agent_config(): print("❌ Échec de la modification de config.py") return False # Étape 2: Tester la correction if not test_fix(): print("❌ Test de la correction échoué") return False print("\n🎉 === CORRECTION APPLIQUÉE AVEC SUCCÈS ===") print("✅ L'agent v0 chargera maintenant automatiquement .env.local au démarrage") print("✅ Le token d'authentification sera disponible pour l'uploader") print("✅ Les uploads devraient maintenant fonctionner sans erreur 401") print("\n📝 PROCHAINES ÉTAPES:") print("1. Redémarrer l'agent v0 : cd agent_v0 && python main.py") print("2. Capturer une session de test") print("3. Vérifier que l'upload fonctionne sans erreur HTTP 401") return True if __name__ == "__main__": success = main() exit(0 if success else 1)