Spaces:
Sleeping
Sleeping
| import os | |
| from smolagents import tool | |
| def codebase_inspector(action: str, target_path: str, file_content: str = "") -> str: | |
| """A tool to explore, read, or create/append files in the active agent repository workspace. | |
| Args: | |
| action: The operation to execute. Choose from: 'list_dir', 'read_file', 'write_file', or 'append_file'. | |
| target_path: The relative file path or directory pathway (e.g., 'tools/my_new_tool.py' or 'tools'). | |
| file_content: Optional string containing python code or text to write/append. | |
| """ | |
| try: | |
| # Prevent escaping the root directory for fundamental space isolation | |
| normalized_path = os.path.normpath(target_path) | |
| if normalized_path.startswith(".."): | |
| return "Error: Access denied. Cannot navigate outside the repository root workspace." | |
| if action == 'list_dir': | |
| if os.path.exists(normalized_path) and os.path.isdir(normalized_path): | |
| files = os.listdir(normalized_path) | |
| return f"Directory contents of '{normalized_path}': {str(files)}" | |
| return f"Error: Path '{normalized_path}' does not exist or is not a directory." | |
| elif action == 'read_file': | |
| if os.path.exists(normalized_path) and os.path.isfile(normalized_path): | |
| with open(normalized_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| return f"--- START OF FILE: {normalized_path} ---\n{content}\n--- END OF FILE ---" | |
| return f"Error: File '{normalized_path}' not found." | |
| elif action in ['write_file', 'append_file']: | |
| if not file_content: | |
| return "Error: 'file_content' argument cannot be empty when writing or appending." | |
| # Ensure directories exist | |
| dir_name = os.path.dirname(normalized_path) | |
| if dir_name and not os.path.exists(dir_name): | |
| os.makedirs(dir_name, exist_ok=True) | |
| mode = 'w' if action == 'write_file' else 'a' | |
| with open(normalized_path, mode, encoding='utf-8') as f: | |
| f.write(file_content) | |
| return f"Successfully executed '{action}' on '{normalized_path}'." | |
| else: | |
| return f"Error: Action '{action}' is invalid. Use list_dir, read_file, write_file, or append_file." | |
| except Exception as e: | |
| return f"An exception occurred while operating on the codebase: {str(e)}" |