Source code for mindroot.coreplugins.admin.agent_importer
frompathlibimportPathimportjsonimportshutilimportloggingfromtypingimportDict,Listimportosimporttempfileimportrequestsimportzipfile# Configure logginglogging.basicConfig(level=logging.INFO)logger=logging.getLogger(__name__)# These should be moved to a config file or environment variablesAGENT_BASE_DIR=Path('data/agents')PERSONA_BASE_DIR=Path('personas')CONFIRM_OVERWRITE_AGENT=os.environ.get('CONFIRM_OVERWRITE_AGENT','false')ifCONFIRM_OVERWRITE_AGENT.lower()in['true','1']:CONFIRM_OVERWRITE_AGENT=Trueelse:CONFIRM_OVERWRITE_AGENT=False
[docs]defdownload_github_files(repo_path:str,tag:str=None)->tuple[str,str]:"""Download GitHub repo files to temp directory"""# Format the download URLiftag:download_url=f"https://github.com/{repo_path}/archive/refs/tags/{tag}.zip"else:download_url=f"https://github.com/{repo_path}/archive/refs/heads/main.zip"# Create temp directorytemp_dir=tempfile.mkdtemp()zip_path=os.path.join(temp_dir,'repo.zip')try:# Download the zip fileresponse=requests.get(download_url)response.raise_for_status()withopen(zip_path,'wb')asf:f.write(response.content)# Extract zipwithzipfile.ZipFile(zip_path,'r')aszip_ref:zip_ref.extractall(temp_dir)returntemp_dir,os.path.dirname(zip_path)exceptExceptionase:shutil.rmtree(temp_dir)raisee
[docs]defscan_for_agents(directory:Path)->Dict[str,Dict]:discovered_agents={}foragent_fileindirectory.rglob('agent.json'):try:withagent_file.open('r')asf:agent_data=json.load(f)agent_name=agent_data.get('name')ifagent_name:discovered_agents[agent_name]={'path':agent_file.parent,'data':agent_data}exceptjson.JSONDecodeError:logger.error(f"Failed to parse agent file: {agent_file}")exceptPermissionError:logger.error(f"Permission denied when reading: {agent_file}")returndiscovered_agents
[docs]defimport_agent(agent_name:str,agent_info:Dict,scope:str)->None:target_dir=Path(AGENT_BASE_DIR)/scope/agent_nameifCONFIRM_OVERWRITE_AGENTandtarget_dir.exists():logger.warning(f"Agent {agent_name} already exists in {scope} scope, skipping")returnifnotvalidate_agent_structure(agent_info['data']):logger.error(f"Agent {agent_name} has invalid structure, skipping")returntry:shutil.copytree(agent_info['path'],target_dir,dirs_exist_ok=True)logger.info(f"Imported agent {agent_name} to {target_dir}")persona_name=agent_info['data'].get('persona')ifpersona_name:persona_dir=os.path.join(agent_info['path'].parent.parent,"personas")import_persona(persona_name,persona_dir,scope)exceptPermissionError:logger.error(f"Permission denied when copying agent {agent_name}")exceptshutil.Errorase:logger.error(f"Error copying agent {agent_name}: {e}")
[docs]defimport_persona(persona_name:str,source_dir:Path,scope:str)->None:persona_source=Path(source_dir)/persona_nameifnotpersona_source.exists():logger.warning(f"Referenced persona {persona_name} not found in {source_dir}")returnpersona_target=PERSONA_BASE_DIR/scope/persona_nameifCONFIRM_OVERWRITE_AGENTandpersona_target.exists():logger.warning(f"Persona {persona_name} already exists, skipping import")returntry:shutil.copytree(persona_source,persona_target,dirs_exist_ok=True)logger.info(f"Imported persona {persona_name} to {persona_target}")exceptPermissionError:logger.error(f"Permission denied when copying persona {persona_name}")exceptshutil.Errorase:logger.error(f"Error copying persona {persona_name}: {e}")
[docs]defimport_github_agent(repo_path:str,scope:str,tag:str=None)->Dict[str,any]:"""Import an agent from a GitHub repository"""try:# Download and extract GitHub repositorytemp_dir,extract_path=download_github_files(repo_path,tag)try:# Scan the downloaded directory for agentsdiscovered=scan_for_agents(Path(temp_dir))ifnotdiscovered:raiseValueError("No valid agents found in repository")# Import each discovered agentresult=scan_and_import_agents(Path(temp_dir),scope)return{'success':True,'message':f"Successfully imported {result['total_imported']} agents from GitHub",'imported_agents':result['imported_agents']}finally:# Clean up temp directoryshutil.rmtree(temp_dir)exceptExceptionase:logger.error(f"Failed to import agent from GitHub: {str(e)}")return{'success':False,'message':f"Failed to import agent: {str(e)}",'imported_agents':[]}