from hopx_ai import Sandbox
import os
from typing import Dict, Any
class EditorBackend:
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 editor project"""
self.sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=3600
)
self.sandbox.files.mkdir("/workspace/project")
return {
"success": True,
"project_id": project_id,
"sandbox_id": self.sandbox.sandbox_id
}
def handle_file_request(self, method: str, path: str, content: str = None) -> Dict[str, Any]:
"""Handle file operation requests"""
full_path = f"/workspace/project{path}"
if method == "GET":
# Read file
try:
content = self.sandbox.files.read(full_path)
return {"success": True, "content": content}
except Exception as e:
return {"success": False, "error": str(e)}
elif method == "PUT":
# Write file
try:
self.sandbox.files.write(full_path, content)
return {"success": True, "path": path}
except Exception as e:
return {"success": False, "error": str(e)}
elif method == "DELETE":
# Delete file
try:
self.sandbox.files.remove(full_path)
return {"success": True, "path": path}
except Exception as e:
return {"success": False, "error": str(e)}
elif method == "LIST":
# List directory
try:
files = self.sandbox.files.list(full_path)
return {
"success": True,
"files": [
{
"name": f.name,
"path": f.path,
"is_dir": f.is_dir,
"size": f.size
}
for f in files
]
}
except Exception as e:
return {"success": False, "error": str(e)}
return {"success": False, "error": f"Unknown method: {method}"}
def cleanup(self):
"""Clean up editor resources"""
if self.sandbox:
self.sandbox.kill()
self.sandbox = None
# Usage
backend = EditorBackend(api_key=os.getenv("HOPX_API_KEY"))
backend.initialize_project("my-project")
# File operations
result = backend.handle_file_request("PUT", "/app.js", "console.log('Hello');")
print(result)
result = backend.handle_file_request("GET", "/app.js")
print(result)
backend.cleanup()