from hopx_ai import Sandbox
import os
from typing import Dict, List, Any
class IDEFileSystem:
def __init__(self, api_key: str):
self.api_key = api_key
self.sandbox = None
def initialize_project(self, project_id: str) -> Dict[str, Any]:
"""Initialize a new project sandbox"""
try:
self.sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=3600 # 1 hour for IDE session
)
# Create project structure
self.sandbox.files.mkdir("/workspace/project")
self.sandbox.files.write("/workspace/project/.gitignore", "__pycache__/\n*.pyc\n")
return {
"success": True,
"sandbox_id": self.sandbox.sandbox_id,
"project_path": "/workspace/project"
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def list_files(self, path: str = "/workspace/project") -> List[Dict[str, Any]]:
"""List files and directories"""
try:
files = self.sandbox.files.list(path)
return [
{
"name": f.name,
"path": f.path,
"is_dir": f.is_dir,
"size": f.size,
"modified": f.modified_time.isoformat() if hasattr(f.modified_time, 'isoformat') else str(f.modified_time)
}
for f in files
]
except Exception as e:
return []
def read_file(self, file_path: str) -> Dict[str, Any]:
"""Read file contents"""
try:
content = self.sandbox.files.read(file_path)
return {
"success": True,
"content": content,
"path": file_path
}
except Exception as e:
return {
"success": False,
"error": str(e),
"path": file_path
}
def write_file(self, file_path: str, content: str) -> Dict[str, Any]:
"""Write file contents"""
try:
self.sandbox.files.write(file_path, content)
return {
"success": True,
"path": file_path,
"size": len(content)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"path": file_path
}
def create_directory(self, dir_path: str) -> Dict[str, Any]:
"""Create a directory"""
try:
self.sandbox.files.mkdir(dir_path)
return {
"success": True,
"path": dir_path
}
except Exception as e:
return {
"success": False,
"error": str(e),
"path": dir_path
}
def delete_file(self, file_path: str) -> Dict[str, Any]:
"""Delete a file or directory"""
try:
self.sandbox.files.remove(file_path)
return {
"success": True,
"path": file_path
}
except Exception as e:
return {
"success": False,
"error": str(e),
"path": file_path
}
def cleanup(self):
"""Clean up sandbox"""
if self.sandbox:
self.sandbox.kill()
self.sandbox = None
# Usage
fs = IDEFileSystem(api_key=os.getenv("HOPX_API_KEY"))
result = fs.initialize_project("my-project")
print(result)
# List files
files = fs.list_files()
print(files)
# Create a file
fs.write_file("/workspace/project/main.py", "print('Hello, World!')")
# Read the file
content = fs.read_file("/workspace/project/main.py")
print(content)
fs.cleanup()